catch on swipe to dismiss event

前端 未结 3 1295
耶瑟儿~
耶瑟儿~ 2020-11-27 12:22

I\'m using an android notification to alert the user once a service is finished (success or failure), and I want to delete local files once the process is done.

My p

3条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 12:26

    A fully flushed out answer (with thanks to Mr. Me for the answer):

    1) Create a receiver to handle the swipe-to-dismiss event:

    public class NotificationDismissedReceiver extends BroadcastReceiver {
      @Override
      public void onReceive(Context context, Intent intent) {
          int notificationId = intent.getExtras().getInt("com.my.app.notificationId");
          /* Your code to handle the event here */
      }
    }
    

    2) Add an entry to your manifest:

    
    
    

    3) Create the pending intent using a unique id for the pending intent (the notification id is used here) as without this the same extras will be reused for each dismissal event:

    private PendingIntent createOnDismissedIntent(Context context, int notificationId) {
        Intent intent = new Intent(context, NotificationDismissedReceiver.class);
        intent.putExtra("com.my.app.notificationId", notificationId);
    
        PendingIntent pendingIntent =
               PendingIntent.getBroadcast(context.getApplicationContext(), 
                                          notificationId, intent, 0);
        return pendingIntent;
    }
    

    4) Build your notification:

    Notification notification = new NotificationCompat.Builder(context)
                  .setContentTitle("My App")
                  .setContentText("hello world")
                  .setWhen(notificationTime)
                  .setDeleteIntent(createOnDismissedIntent(context, notificationId))
                  .build();
    
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notificationId, notification);
    

提交回复
热议问题