2013-02-27 105 views
93

我希望在用户点击通知后关闭通知。我看到每个人都说使用标志,但是我无法在任何地方找到标志,因为我使用的是NotificationCompat.Builder类而不是Notification类。有人有任何想法如何使她的自我消除通知?
下面是当我设置的通知我的代码:点击后删除通知

NotificationCompat.Builder mBuilder = 
      new NotificationCompat.Builder(this) 
      .setSmallIcon(R.drawable.ic_launcher) 
      .setContentTitle("New Question") 
      .setContentText("" + QuestionData.getAuthor().getUserName() + ": " + QuestionData.getQuestion() + ""); 

    Intent openHomePageActivity = new Intent("com.example.ihelp.HOMEPAGEACTIVITY"); 
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); 
    stackBuilder.addNextIntent(openHomePageActivity); 

    PendingIntent resultPendingIntent = 
      stackBuilder.getPendingIntent(
       0, 
       PendingIntent.FLAG_UPDATE_CURRENT 
      ); 
    mBuilder.setContentIntent(resultPendingIntent); 
    NotificationManager mNotificationManager = 
     (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  

    mNotificationManager.notify(0, mBuilder.build()); 

回答

1

您可以将标记添加到您的通知:

http://developer.android.com/reference/android/app/Notification.html#FLAG_AUTO_CANCEL

这将关闭它在点击。此外

mBuilder.setAutoCancel(true); 

,虽然它不是真的有必要,如果你真的想用FLAG_AUTO_CANCEL,只是称这个调用mNotificationManager.notify前:

+0

我在哪里添加标志?你可以在我的代码中显示我吗? – 2013-02-27 19:49:40

+0

将它添加到您的通知对象的通知标志。 – JoxTraex 2013-02-27 19:54:19

258

简单,只需拨打这个

mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL; 
+2

这是最好的答案.. flag_auto_cancel没有工作..你救了我的一天! – allemattio 2013-12-03 09:46:16

+1

后来的方法getNotification已被弃用! – sandalone 2014-04-14 18:24:26

+0

第一个作品!太感谢了! – Vladimir 2014-12-26 22:21:12

15

试试这个...

NotificationManager mNotificationManager = 
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

.......... 
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
      this).setSmallIcon(R.drawable.push_notify_icon) 
      .setContentTitle("New Question!") 
      .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) 
      .setAutoCancel(true).setContentText("" + QuestionData.getAuthor().getUserName() + ": " + QuestionData.getQuestion() + ""); 
mBuilder.setContentIntent(contentIntent); 

    ..............   


mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL; 
mNotificationManager.notify(0, mBuilder.build()); 
+1

'.getNotification()'现在不推荐使用'.build()'而不是像'mBuilder.build()。flags | = Notification.FLAG_AUTO_CANCEL;' – 2016-12-23 12:57:30