简体   繁体   中英

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?

PS 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.

I think you don't need the chooser:

@Override
public void onReceive(Context context, Intent intent) {
    Intent intIntent = new Intent(context, MainActivity.class);
    intIntent.putExtra("IsAlarm", true);
    context.startActivity(intIntent);
}

在活动onNewIntent回调中onNewIntent入,接收者应该有新的意图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM