How to use getSystemService in a class without activity?

I am creating an application that starts an alarm through AlarmManager.

I would like to be able to call Alarm through my own inactivity class, but since I am not extending the Activity, I have no "context". This concept confuses me, and I read the sdk docs.

How can i use:

alarmTest = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 

in my non-activty class?

Also, I guess getting context will allow me to use SharedPrefs and Intents in my inactivity class?

+42
android android-context
Nov 10 '10 at 5:40
source share
4 answers

You can pass the context to the inactivity class, which is the preferred way, or you can encapsulate the application’s base context in a singleton, which allows you to access the context anywhere in the application. In some cases this may be a good solution, but in others it is certainly not very good.

In any case, if you want to call an alarm through the AlarmManager , I am sure that the alarm should be inherited from Service or even better from IntentService , and in such cases you have access to the context through this.getBaseContext() or this.getApplicationContext()

+34
Nov 10 '10 at 5:55
source share

Service and Activity inherit from Context - so when you call getSystemService in these classes, you really call super.getSystemService .

If you want Context be available in another class, you can pass it as an argument to the method of this class, save a link to it, etc.

Edit : sample code. But seriously, it is extremely simple - 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) { } } 
+16
Nov 10 '10 at 5:52
source share

You can try the following: it allows you to get the current context that the view is viewing.

 alarmTest = (AlarmManager)this.getContext().getSystemService(Context.ALARM_SERVICE); 
+12
Jun 28 '11 at 10:26
source share

You need to pass the context to the class without activity.

+4
Nov 10 '10 at 5:48
source share



All Articles