android开发app时setAutoCancel(true)无效

在开发开发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);

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值