Search code examples
androidandroid-intentbroadcastreceiver

Broadcast receiver start activity


I have an application that using "AlarmService". For handling alarms i have a Broadcast receiver. That receiver has to start certain activity. Code i'm using for achieving that is following:

@Override
public void onReceive(Context context, Intent intent) {
    ...other code....
    Intent intIntent = new Intent(context, MainActivity.class);
    intIntent .putExtra("IsAlarm", true);
    Intent alarmChooser = Intent.createChooser(intIntent , "Alarm");
    alarmChooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(alarmChooser);
}

That works but only if activity isn't shown already (if it's not in the foreground). If called activity is already opened nothing happens. How can i overcome that? Is there a flag that will start the activity if it's not started OR send intent to it even if it's in the foreground?

P.S. i tried using dedicated "broadcast" above the provided code. Reciever for that broadcast is registered programmatically in the MainActivity: "onResume" would register dedicated receiver, "onPause" would unregister it. That way in case MainActivity is already on it will receive a broadcast but then i have a problem when phone goes to "stand by" - "dedicated" receiver is unregistered.


Solution

  • Check in the activity onNewIntent callback there should be the new intent from the receiver