Android Alarm Manager with broadcast receiver registered in code rather than manifest

Shane picture Shane · Aug 10, 2010 · Viewed 26k times · Source

I want to use an alarm to run some code at a certain time. I have successfully implemented an alarm with the broadcast receiver registered in the manifest but the way i understand it, this method uses a separate class for the broadcast receiver.

I can use this method to start another activity but I cant use it to run a method in my main activity?

(how can I notify a running activity from a broadcast receiver?)

So I have been trying to register my broadcast receiver in my main activity as explained in the answer above.

private BroadcastReceiver receiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "hello", Toast.LENGTH_SHORT).show();
        uploadDB();         
    }
};    

public void onResume() {
    super.onResume();

    IntentFilter filter = new IntentFilter();
    filter.addAction(null);

    this.registerReceiver(this.receiver, filter);
}

public void onPause() {
    super.onPause();

    this.unregisterReceiver(this.receiver);
}

However I have been unable to get this to work with alarm manager, I am unsure as to how i should link the alarm intent to the broadcast receiver. Could anyone point me to an example of registering an alarm manager broadcast receiver dynamically in the activity? Or explain how i would do this?

Answer

user123321 picture user123321 · Aug 15, 2011

How about this?

Intent startIntent = new Intent("WhatEverYouWant");
PendingIntent startPIntent = PendingIntent.getBroadcast(context, 0, startIntent, 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, triggerTime, startPIntent);

And then in your Manifest.xml file:

<receiver android:name="com.package.YourOnReceiver">
   <intent-filter>
       <action android:name="WhatEverYouWant" />
   </intent-filter>
</receiver>

So as far as I know you still have to declare the receiver in the Manifest. I'm not sure if you can set it to a private instance inside of your activity. You could declare an onReceive inside of your activity and call that (if the BroadcastReceiver has an interface. I don't know if it does.)