Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use getSystemService in a non-activity class?

I am building an application which triggers an alarm via AlarmManager.

I would like to be able to call the Alarm via it's own non-activity class, but since I am not extending Activity, I don't appear to have any 'context'. This concept confuses me, and I've read the sdk docs.

How would I go about using:

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

in my non-activty class?

Also, I'm assuming getting context will allow me to use SharedPrefs and Intents in my non-activity class as well?

like image 991
eportermd Avatar asked Nov 10 '10 05:11

eportermd


People also ask

What is the use of getSystemService in Android?

getSystemService method is used when we want to access one of few Android system-level services. To name only few of managers that we can get: LocationManager – access GPS device information. NotificationManager – manage (create, cancel) notifications.


1 Answers

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()

like image 169
Marek Szanyi Avatar answered Oct 26 '22 02:10

Marek Szanyi