清除 Android 应用程序通知 (Java)

Posted

技术标签:

【中文标题】清除 Android 应用程序通知 (Java)【英文标题】:Clear notification of an android app (Java) 【发布时间】:2021-09-14 16:38:55 【问题描述】:

我的音乐应用中有一条通知,代码如下:

void showNotification(int playPauseBtn)
        Intent intent = new Intent(this, PlayerActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);

        Intent prevIntent = new Intent(this, NotificationReceiver.class)
                .setAction(ACTION_PREVIOUS);
        PendingIntent prevPending = PendingIntent.getBroadcast(this, 0, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Intent pauseIntent = new Intent(this, NotificationReceiver.class)
                .setAction(ACTION_PLAY);
        PendingIntent  pausePending = PendingIntent.getBroadcast(this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Intent nextIntent = new Intent(this, NotificationReceiver.class)
                .setAction(ACTION_NEXT);
        PendingIntent nextPending = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        byte[] picture = null;
        picture = getAlbumArt(musicFiles.get(position).getPath());
        Bitmap thumb = null;
        if (picture != null)
            thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
        
        else
            thumb = BitmapFactory.decodeResource(getResources(), R.drawable.musicicon);
        
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_2)
                .setSmallIcon(playPauseBtn)
                .setLargeIcon(thumb)
                .setContentTitle(musicFiles.get(position).getTitle())
                .setContentText(musicFiles.get(position).getArtist())
                .addAction(R.drawable.ic_skip_previous, "Previous", prevPending)
                .addAction(playPauseBtn, "Pause", pausePending)
                .addAction(R.drawable.ic_skip_next, "Next", nextPending)
                .setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
                        .setMediaSession(mediaSessionCompat.getSessionToken()))
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setOnlyAlertOnce(true)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .build();
        startForeground(2, notification);
        notificationManager =
               (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(2, notification);

    

我已经创建了单独的类(ApplicationClass)来创建通知通道。

@Override
public void onCreate() 
    super.onCreate();
    createNotificationChannel();


private void createNotificationChannel() 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        NotificationChannel channel1 =
                new NotificationChannel(CHANNEL_ID_1,
                        "Channel(1)", NotificationManager.IMPORTANCE_HIGH);
        channel1.setDescription("Channel 1 Desc..");

        NotificationChannel channel2 =
                new NotificationChannel(CHANNEL_ID_2,
                        "Channel(2)", NotificationManager.IMPORTANCE_HIGH);
        channel1.setDescription("Channel 2 Desc..");

        //HERE ABOVE DOUBT

        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel1);
        notificationManager.createNotificationChannel(channel2);


    

另外,我有一个类 (NotificationReceiver) 用于接收通知操作:

 public class NotificationReceiver extends BroadcastReceiver 
    @Override
    public void onReceive(Context context, Intent intent) 
        String actionName = intent.getAction();
        Intent serviceIntent = new Intent(context, MusicService.class);
        if (actionName != null)
            switch (actionName)
                case ACTION_PLAY:
                    serviceIntent.putExtra("ActionName", "playPause");
                    context.startService(serviceIntent);
                    break;
                case ACTION_NEXT:
                    serviceIntent.putExtra("ActionName", "next");
                    context.startService(serviceIntent);
                    break;
                case ACTION_PREVIOUS:
                    serviceIntent.putExtra("ActionName", "previous");
                    context.startService(serviceIntent);
                    break;
            
        
    

我的通知功能(播放、暂停和下一个)工作正常,但我的问题是,我无法清除通知。我试了很多次,都做不好。

【问题讨论】:

【参考方案1】:

试试这个

void showNotification(int playPauseBtn)
    Intent intent = new Intent(this, NotifAction.class);

   //add this to get IdNotif.for all intent
    intent.putextra("NotifId",notifId);
   //

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);

    Intent prevIntent = new Intent(this, NotifAction.class)

            .setAction(ACTION_PREVIOUS);
    PendingIntent prevPending = PendingIntent.getBroadcast(this, 0, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent pauseIntent = new Intent(this, NotifAction.class)
            .setAction(ACTION_PLAY);
    PendingIntent  pausePending = PendingIntent.getBroadcast(this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent nextIntent = new Intent(this, NotifAction.class)
            .setAction(ACTION_NEXT);
    PendingIntent nextPending = PendingIntent.getBroadcast(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    byte[] picture = null;
    picture = getAlbumArt(musicFiles.get(position).getPath());
    Bitmap thumb = null;
    if (picture != null)
        thumb = BitmapFactory.decodeByteArray(picture, 0, picture.length);
    
    else
        thumb = BitmapFactory.decodeResource(getResources(), R.drawable.musicicon);
    
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID_2)
            .setSmallIcon(playPauseBtn)
            .setLargeIcon(thumb)
            .setContentTitle(musicFiles.get(position).getTitle())
            .setContentText(musicFiles.get(position).getArtist())
            .addAction(R.drawable.ic_skip_previous, "Previous", prevPending)
            .addAction(playPauseBtn, "Pause", pausePending)
            .addAction(R.drawable.ic_skip_next, "Next", nextPending)
            .setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
                    .setMediaSession(mediaSessionCompat.getSessionToken()))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setOnlyAlertOnce(true)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .build();
    startForeground(notifId, notification);
    notificationManager =
           (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(notifId, notification);

 

为 eachNotification 设置 notifId 并让这个类处理通知中的所有操作。

注意: 要为每个通知按钮设置每个事件,首先将所有操作合理化到 NotifAction 类,然后从那里为每个使用该类的事件定义点击事件。

为 HandleAction 创建类:

public class NotifAction extends BroadcastReceiver 


@Override
public void onReceive(final Context context, Intent intent) 
    String action = intent.getAction();
    Bundle extra = intent.getExtras();

    if (extra != null) 
       if (action.equals("YourActionName"))              
             clearNotification(extra.getInt("YourNotifId",0),context);
         Toast.makeText(context, "YourMessage!", Toast.LENGTH_SHORT).show();
         else
           /// another event for each action
          




private void clearNotification(int id, Context context) 
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancel(id);
    
   

【讨论】:

以上是关于清除 Android 应用程序通知 (Java)的主要内容,如果未能解决你的问题,请参考以下文章

如何清除android应用程序的通知?

如何清除状态栏上的推送通知警报 - android

清除 Android 的本地通知 cordova 插件

Android状态栏通知:使其无法清除并返回应用程序(不启动新实例)

在android应用程序中,调用onResume方法时清除状态栏中的小图标

Swift 清除特定的远程通知