How to bring application from background to foreground via BroadcastReceiver

空扰寡人 提交于 2019-12-06 08:35:46

Do the following in your onReceive method of the BroadcastReceiver

@Override
public void onReceive(Context context, Intent intent) {
    Intent newIntent = new Intent();
    newIntent.setClassName("com.your.package", "com.your.package.MainActivity");
    newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    context.startActivity(newIntent);
}

You need the flag "FLAG_ACTIVITY_NEW_TASK" for your intent otherwise there will be a fatal exception being thrown.

The flag "FLAG_ACTIVITY_SINGLE_TOP" is to bring your MainActivity to the front and you can proceed to do whatever you want from there by overriding the onNewIntent method in MainActivity.

@Override
protected void onNewIntent(Intent intent) {
    // continue with your work here
}

Do this inside your onReceive method:

Intent activityIntent = new Intent(this, MainActivity.class);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activityIntent);

You might need to tweak the addFlags call for your specific needs!

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