在开发开发app时,发现设置了setAutoCancel(true),但是点击通知后,通知没有消失,还在状态栏中,代码如下
PendingIntent pi=PendingIntent.getActivity(this,0,intent,0);
Notification notification=new NotificationCompat.Builder(this,"alarm")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher_round))
.setContentTitle("闹钟")
.setContentText("id="+alarmID)
.setSound(Uri.parse("android.resource://"+getApplicationContext().getPackageName()+
"/"+R.raw.bell))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setSound(Uri.parse("android.resource://"+getApplicationContext().getPackageName()+
"/"+R.raw.bell))
.setContentIntent(pi)
.setAutoCancel(true)//点击通知后,通知自动消失
.build();
notification.flags=Notification.FLAG_INSISTENT;//将重复音频,直到取消通知或打开通知窗口
notification.fullScreenIntent=pi;
notificationManager.notify(alarmID,notification);
最后发现,是因为notification.flags=Notification.FLAG_INSISTENT;影响了,因为setAutoCancel和notification.flags设置的是同一个标志位,所有最后notification.flags把之前的设置重置了。发现问题后,代码做了如下修改,就可以把问题解决了
PendingIntent pi=PendingIntent.getActivity(this,0,intent,0);
Notification notification=new NotificationCompat.Builder(this,"alarm")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher_round))
.setContentTitle("闹钟")
.setContentText("id="+alarmID)
.setSound(Uri.parse("android.resource://"+getApplicationContext().getPackageName()+
"/"+R.raw.bell))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setSound(Uri.parse("android.resource://"+getApplicationContext().getPackageName()+
"/"+R.raw.bell))
.setContentIntent(pi)
//.setAutoCancel(true)//不要在这里设置,用flags设置
.build();
notification.flags=Notification.FLAG_INSISTENT|Notification.FLAG_AUTO_CANCEL;//将重复音频,直到取消通知或打开通知窗口,且设置点击通知后,通知自动消失
notification.fullScreenIntent=pi;
notificationManager.notify(alarmID,notification);