2013-02-22 162 views
18

我试图显示用户点击它时必须删除的通知。 我使用NotificationCompat类来构建我的通知,我在builder上拨打setAutoCancel(true)。这是一段代码:通知setAutoCancel(true)不起作用

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

该通知已正确添加,但是当我点击它时什么也没有发生!我错在哪里?

+0

通知只停留在那里?当你刷卡解雇它会发生什么?你运行什么设备和API版本? – 2013-02-22 21:46:16

+0

我在Galaxy Nexsus API 4.2.2上运行。如果我滑过它,通知消失,但如果我只是点击它,没有任何反应。 – TheModularMind 2013-02-22 22:41:48

回答

41

使用setContentIntent应该解决您的问题:

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

在您的例子:

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()); 

通常你可能希望将用户引导到相关的内容,因此可能会取代“新意图() '与别的东西。

我上传了demo github。

+2

为什么这个答案被降低了?它问题的问题是什么!谢谢,它为我工作。 – 2013-07-30 08:18:10

+0

谢谢。尽管用户仍然可以通过刷卡来清除通知。 – gatopeich 2013-11-08 18:45:25

+0

我发现这个方法可行,但它可能会导致一个特别的意外结果:我也从通知中单独打开contentIntent。这可以自动取消通知的声音(在moto g3上,Google Pixel没有)。 – jobbert 2017-02-20 12:09:43

17

我知道一个答案已经被接受,但我有一个不同的解决方案相同的问题,所以我会在这里分享。

对我来说,我使用的是同一个NotificationCompat.Builder对象来创建一个叫做setOngoing(true)的通知。这是上传进度通知,不应在工作时删除。

无论如何,在任务完成后,我打电话给setAutoCancel(true),但通知仍未消除。我所要做的也是拨打setOngoing(false)

现在看起来很明显,但它可能在未来的某个时间为别人节省。

+0

如果你已经找到解决问题的方法,请写下正确的方式将其整理出来 – 2015-07-31 14:18:56

+0

谢谢,我遇到同样的问题,你救了我的一天! – SalutonMondo 2015-11-05 13:42:35

+0

thnks budd hhhhhjhjh :) – Shikhar 2016-03-30 05:58:17