Gavin Miller
Gavin Miller

Reputation: 43815

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);
}

Upvotes: 2

Views: 2856

Answers (1)

ABentSpoon
ABentSpoon

Reputation: 5169

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();
  }
});

Upvotes: 6

Related Questions