安卓Nofication取消的正确使用姿势

1.建立通知

private void  initNotificationBar(){

        RemoteViews contentView1;
        notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT>=26){//8.0以上需要先使用NotificationChannel
            NotificationChannel notificationChannel=new NotificationChannel("myid","myname",NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(notificationChannel);
            notification=new Notification.Builder(getApplicationContext(),"myid").build();
        }else {
            notification = new Notification();
        }
        notification.icon=R.drawable.ic_launcher_background;//添加通知图标
        contentView1=new RemoteViews(getPackageName(),R.layout.pan);//自定义布局
        notification.contentView=contentView1;
        contentView1.setTextViewText(R.id.textView,"点击录音");
        contentView1.setImageViewResource(R.id.imageButton,android.R.drawable.ic_media_play);
        contentView1.setImageViewResource(R.id.imageButton2,android.R.drawable.ic_media_pause);
        contentView1.setImageViewResource(R.id.imageButton3,android.R.drawable.ic_menu_add);
        contentView1.setImageViewResource(R.id.imageButton4,android.R.drawable.ic_menu_delete);
        Intent intent1=new Intent(Word.startRecord);
        PendingIntent pintent1=PendingIntent.getBroadcast(this,0,intent1,0);
        contentView1.setOnClickPendingIntent(R.id.imageButton,pintent1);


        Intent intent2=new Intent(Word.pauseRecord);
        PendingIntent pintent2=PendingIntent.getBroadcast(this,0,intent2,0);
        contentView1.setOnClickPendingIntent(R.id.imageButton2,pintent2);

        Intent intent3=new Intent(Word.stopRecord);
        PendingIntent pintent3=PendingIntent.getBroadcast(this,0,intent3,0);
        contentView1.setOnClickPendingIntent(R.id.imageButton3,pintent3);


        Intent intent4=new Intent(Word.cancleRecord);
        PendingIntent pintent4=PendingIntent.getBroadcast(this,0,intent4,0);
        contentView1.setOnClickPendingIntent(R.id.imageButton4,pintent4);

        notificationManager.notify("o",50,notification);//更新通知
        

    }

2.取消通知

直接使用notificationManager.cancel()发现不能取消,需要先移除图标,自定义布局等才可以移除

 if (notification!=null&&notificationManager!=null){
            notification.contentView=null;
            notification.icon=0;
            notificationManager.notify("o",50,notification);
          if (Build.VERSION.SDK_INT>=26) {
              notificationManager.deleteNotificationChannel(notification.getChannelId());
          }
            notificationManager.cancel("o",50);
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值