Android Notification intent to clear it self

前端 未结 6 1420
旧巷少年郎
旧巷少年郎 2020-12-09 08:25

I have read many examples of how to create notification messages. What i wanted to achieve, is because the notification will be executed by a widget, i would like the notifi

相关标签:
6条回答
  • 2020-12-09 08:47

    Using setContentIntent should solve your problem:

    .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
    

    For example:

    NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.notification_icon)
            .setContentTitle("title")
            .setAutoCancel(true)
            .setContentText("content")
            .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
    NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, mBuilder.build());
    

    Often you might want to direct the user to the relevant content and so might replace 'new Intent()' with something else.

    0 讨论(0)
  • 2020-12-09 08:55
     /** 
          Post a notification to be shown in the status bar. 
          Obs.: You must save this values somewhere or even pass it as an extra through Intent to use it later
     */
     notificationManager.notify(NOTIFICATION_ID, notification);
    
     /** 
          Cancel a previously shown notification given the notification id you've saved before
     */
     notificationmanager.cancel(NOTIFICATION_ID);
    
    0 讨论(0)
  • 2020-12-09 08:57

    Set the flags in notification.flags instead of notification.defaults.

    Example:

    notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL;
    
    0 讨论(0)
  • 2020-12-09 08:59

    The only way I can see of doing this is to have your Notification's Intent point to a background Service. When this Service is launched, it would clear the given Notification using NotificationManager.cancel(int id). The Service would then stop itself. It's not pretty, and would not be easy to implement, but I can't find any other way of doing it.

    0 讨论(0)
  • 2020-12-09 09:01

    If you're using NotificationCompat.Builder (a part of android.support.v4) then simply call its object's method setAutoCancel

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setAutoCancel(true);
    

    Some guys were reporting that setAutoCancel() did not work for them, so you may try this way as well

    builder.build().flags |= Notification.FLAG_AUTO_CANCEL;
    
    0 讨论(0)
  • 2020-12-09 09:04

    Check out FLAG_AUTO_CANCEL

    Bit to be bitwise-ored into the flags field that should be set if the notification should be canceled when it is clicked by the user.

    EDIT :

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    
    0 讨论(0)
提交回复
热议问题