Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AlarmManager in a Broadcastreceiver

I have braodcastreceiver, that broadcast receiver shall schedule an alarm.

Usually I would do

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); 
am.set(AlarmManager.RTC, time,  myPendingIntent); 

The problem is that getSystemService is not available in a Broadcast receiver only in an Activty. How would I do it here?

Thanks, A.

like image 749
AndyAndroid Avatar asked Apr 07 '11 13:04

AndyAndroid


People also ask

How do I stop AlarmManager?

You can cancel the alarm like this: Intent intent = new Intent(this, Mote. class); PendingIntent pendingIntent = PendingIntent. getBroadcast(getApplicationContext(), 1253, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.

How do you use AlarmManager?

This example demonstrates how do I use AlarmManager in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What is the role of the onReceive () method in the BroadcastReceiver?

onReceive. This method is called when the BroadcastReceiver is receiving an Intent broadcast. During this time you can use the other methods on BroadcastReceiver to view/modify the current result values.


1 Answers

AndyAndroid,

getSystemService() is part of the Context. You will need to save the Context you receive in your onReceive() method like so...

private Context mContext;

@Override
public void onReceive(Context c, Intent i) {
    mContext = c;
}

Then..where you call getSystemService() you use...

AlarmManager am = (AlarmManager) mContext.getSystemService(mContext.ALARM_SERVICE); 
like image 65
Will Tate Avatar answered Oct 16 '22 15:10

Will Tate