Start Activity from a Broadcast Receiver

僤鯓⒐⒋嵵緔 提交于 2020-01-02 16:17:58

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/9386461/start-activity-from-a-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!