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

前端 未结 2 1737
谎友^
谎友^ 2021-01-14 22:00

When I click on a notification apply the following:

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


        
2条回答
  •  渐次进展
    2021-01-14 23:02

    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.

提交回复
热议问题