简体   繁体   中英

Start Activity from a Broadcast Receiver

I've got the following scenario for Android: I have an app that when launched starts a service . That service checks a url every 30 minutes. If it gets a specific response, it sends a Broadcast which the app receives and processes. That scenario is working great for me.

I'd also like my service to continue running after the user has stopped running the application (app out of foreground.) Which I've got working as well.

The problem that I'm facing is that when the Activity receives the Broadcast message, I can't get the Activity to move back to the foreground . I've tried various combinations of intents, but haven't figured it out. What am I doing wrong?

My BroadcastReceiver code looks like this:

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        launchApp();
    }
};

private void launchApp() {
    Intent vukaniActivity = new Intent(this, Vukani.class);

    // I've tried multiple different flags to no avail.
    vukaniActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(vukaniActivity);
}

The flags you want are:

vukaniActivity.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK
                       | Intent.FLAG_ACTIVITY_CLEAR_TOP
                       | Intent.FLAG_ACTIVITY_SINGLE_TOP);

Also, make sure you're running on the UI Thread.

runOnUiThread(new Runnable(){
  @Override
  public void run(){
    launchApp();
  }
});

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