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

    xiaoxiao2023-11-11  167

    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&¬ificationManager!=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); }

     

    最新回复(0)