Search code examples
androidbroadcastreceiveralarmmanager

Call a method from Activity on BroadcastReceiver called by an AlarmManager


I'm new to asking, so I hope my question is correctly asked. Thanks in advance!

My problem is:

A BroadcastReceiver is called by an AlarmManager in this way by a method inside the same BroadcastReceiver:

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, Receiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis(), 5000, pi);

onRecieve works until I put there the method from MainActivity. When the call is on the code, i get this error every time the AlarmManager tries to start the onReceive:

12-22 21:56:01.020: W/BroadcastQueue(2192): Unable to launch app com.example/10000 for broadcast Intent { flg=0x14 cmp=com.example/.Receiver (has extras) }: process is bad

If I create a method on the BroadcastReceiver that recieves MainActivity, I can call methods from MainActivity inside that method of BroadcastReceiver:

public void SetHandler(Context context, MainActivity main) {
    MainActivity mainactivity;
this.mainactivity = main;
mainactivity.method();
}      

But I can't understand how to call them inside the onReceive of the BroadcastReceiver.

mainactivity.method() on the onRecieve doesn't work, I don't know if it is because it is not attached to the MainActivity by the AlarmManager or if it is because I'm doing it wrong.

If the problem is because of the attachment of the activity with the BroadcastReceiver, how is it done? If that's not the problem, what would it be?


Solution

  • Register your BroadcastReceiver to activity and create an IntentService put it in AlarmManager and in handleIntent function of your service send a braodcast to the provided IntentFilter and you will be able to call Activity methods in onReceive.