2013-02-27 104 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