How to close any activity of my application by clicking on a notification?

那年仲夏 提交于 2019-12-01 09:27:27

问题


When I click on a notification apply the following:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

In all "startActivity" of the app I applied the next flag:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

The startActivity my notification does the following: Call activity "Splash" and is called "Main".

Casulidad If I was in "Main" pulse notification, closes the current (working properly). But if I am in the activity "News" and pulse the notification, I have 2 activities open, the new "Main" and the former "News".

How to close any activity of my application by clicking on a notification?


回答1:


You could set a PendingIntent in the notification that would be caught by the Activity in a broadcastReceiver. Then in the broadcastReceiver of the activity, call finish(); This should close your activity.

i.e. Put this in your activity

BroadcastReceiver mReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        finish();
    }

};

This in your onCreate()

IntentFilter filter = new IntentFilter("android.intent.CLOSE_ACTIVITY");
registerReceiver(mReceiver, filter);

And then your PendingIntent in your notification should have action of "android.intent.CLOSE_ACTIVITY" and for safety a package of your activity's package.

This is done by

Intent intent = new Intent("android.intent.CLOSE_ACTIVITY");
PendingIntent pIntent = PendingIntent.getBroadcast(context, 0 , intent, 0);

Then add it to your notification by using the setContentIntent(pIntent) when building the notification with the Notification.Builder.




回答2:


I used a singleton with a static flag exitApp that was false at start of the application and it is set to true in the activity that returns from the notification.

This flag is checked in each of onResume() of all activities and if it is true the activity calls it's finish() method..

This way, even if the notification is activated some few activities down the road, each activity finish() and the onResume() of the parent activity is called which in turns also finish() until the mainActivity finish() and the application is terminated.



来源:https://stackoverflow.com/questions/19243137/how-to-close-any-activity-of-my-application-by-clicking-on-a-notification

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