Close application from broadcast receiver

我的未来我决定 提交于 2019-12-01 06:13:44

Your broadcast receiver is in the main activity class? If so you can save a global context of your app and close it later in the broadcast receiver.

If it is on a service or provider, just send an instance of your app to it when you start/register it. Then you call finish() from that instance.

EDIT:

Try this:

In your main activity create this public method:

   public static void closeActivity(){
        finish();
   }

Then in your broadcast receiver call this method like:

   MainActivity.closeActivity();

Hope it helps ;)

Use code below to send new intent to MainActivity from BroadcastReceiver:

Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags (Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.putExtra("close_activity",true);
context.startActivity(i);

in MainActivity use OnNewIntent as below:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    if(intent.getBooleanExtra("close_activity",false)){
        this.finish();

    }
}

FYI, I haven't tried the above code, But I have similar code working.

Harsha Vardhan
MainActivity m = new MainActivity();
m.finish();

When you say finish, it wont clear from stack because you didn't loaded the activity into stack first. The MainActivity is not activity here, it is just a class object in your code

Have broadcast receiver in mainactivity, when onreceive finish the activity. don't create instance with new.

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