How to use getSystemService in a non-activity class?
Solution 1:
You can pass the context to the non-activity class which is the preferred way or you could encapsulate the base context of the application to a singleton which would allow you to access the context anywhere within the application. At some cases this might be a good solution but in others its certainly not a good one.
Anyway, if you want to trigger an alarm via the AlarmManager
I'm pretty sure the alarm should inherit from a Service
or better yet from IntentService
and in such cases you have access to the context via this.getBaseContext()
or this.getApplicationContext()
Solution 2:
Service
and Activity
inherit from Context
- so when you are calling getSystemService
in these classes, you are really calling super.getSystemService
.
If you want to have a Context
available in another class, you can pass one as an argument to a method of that class, keep a reference to it, etc.
Edit: Code sample. But seriously, it is extremely basic - if you understand inheritance and methods.
class MyActivity extends Activity { // Activity extends Context, so MyActivity also extends Context
void someMethod() {
MyOtherClass.useStaticContext(this);
MyOtherClass instance = new MyOtherClass();
instance.useInstanceContext(this.getApplicationContext());
}
}
class MyOtherClass {
static void useStaticContext(Context context) {
}
void useInstanceContext(Context context) {
}
}