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

Posted

技术标签:

【中文标题】如何清除android应用程序的通知?【英文标题】:How to clear notification of android app? 【发布时间】:2021-09-26 05:42:27 【问题描述】:

我为音乐播放器创建了一个运行良好的通知,但问题是通知没有被清除。它只是粘在我的通知面板上。

当我暂停音乐或关闭应用程序时如何清除我的通知?

  void showNotification(int playPauseBtn)
            Intent intent = new Intent(this, MainActivity.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);
        
        passPosition = position;
        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)
                .setContentIntent(contentIntent)
//                .setAutoCancel(true)
                .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);
    

【问题讨论】:

【参考方案1】:

我写的这个例子是一个简单的通知,通过点击歌曲按钮播放,点击停止按钮音乐被切断,通知被删除。现在你看到了这个例子,然后你可以随意给它一个按钮。

将此代码放入您的活动/片段中;

    public void getNotification()
    
    int notifId =new Random().nextInt(500);   //get random id
    NotificationManager notificationManager;
    Notification notification;
    notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
        channelID = "1";
        channelName = "news";
        channelDesc = "news description";
        NotificationChannel notificationChannel = new NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH);
        notificationChannel.setDescription(channelDesc);
        notificationChannel.enableLights(true);
        notificationChannel.setSound(null, null);
        notificationChannel.setLightColor(Color.GREEN);
        notificationManager.createNotificationChannel(notificationChannel);

    

    RingtoneManager.getRingtone(mContext,
            RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)).play();

    NotificationCompat.Builder   builder = new NotificationCompat.Builder(mContext, channelID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("title Of MUSIC")
            .setContentText("Content")
            .setVibrate(new long[]100, 500, 500, 500, 500)
            .setAutoCancel(true)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

    Intent actionReadMessage = new Intent(mContext, NotifAction.class);
    actionReadMessage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    actionReadMessage.setAction("Play");
   actionReadMessage.putExtra("NotifId",notifId);
    PendingIntent playPendingIntent = PendingIntent.getBroadcast(mContext, notifId, actionReadMessage,PendingIntent.FLAG_CANCEL_CURRENT);




    Intent mainAction = new Intent(mContext, NotifAction.class);
    mainAction.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    mainAction.setAction("Pause");
    mainAction.putExtra("NotifId",notifId);
    PendingIntent PausePendingIntent = PendingIntent.getBroadcast(mContext, notifId, mainAction,PendingIntent.FLAG_CANCEL_CURRENT);

    

    builder.setContentIntent(PausePendingIntent);
    builder.addAction(R.mipmap.ic_launcher, "Play", playPendingIntent);
    builder.addAction(R.mipmap.ic_launcher, "Pause", PausePendingIntent);
    
    notification = builder.build();
    notificationManager.notify(notifId,  notification);
    

    

并创建类 NotifAction.class 来处理所有操作:

public class NotifAction extends BroadcastReceiver 

private static final String TAG = "maybe";
private MediaPlayer mp;
@Override
public void onReceive(final Context context, Intent intent) 

    String action = intent.getAction();
    Bundle extra = intent.getExtras();

    if (extra != null) 
        int notifId = extra.getInt("NotifId");
        if (action.equals("Play")) 
            mp = MediaPlayer.create(context, R.raw.music);
            handleMusicState(mp);
         else if (action.equals("Pause")) 

            handleMusicState(mp);
            setMessageRead(notifId, context);

         else 
            Toast.makeText(context, "extra  action !", Toast.LENGTH_SHORT).show();
        

     else 
        Toast.makeText(context, "Empty extra !", Toast.LENGTH_SHORT).show();
    
    


private void setMessageRead(int id, Context context) 
    //  other  method
    clearNotification(id, context);

   

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

private void handleMusicState(MediaPlayer mediaPlayer) 
    if (mediaPlayer.isPlaying()) mediaPlayer.pause();
    else mediaPlayer.start();

    
   

定义此接收器以显示: 注意:在标签中

 <receiver android:name=".NotifAction">
        <intent-filter>
            <action android:name="Play" />
            <action android:name="Pause" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        </intent-filter>
    </receiver>

【讨论】:

感谢您的回答。我在这里找到了一种非常简单快捷的方法:***.com/a/35721582【参考方案2】:

我之所以回答,是因为它可以帮助某人并节省他们的时间来解决这个简单的问题,我花了几个小时才弄清楚。 我已经启动了前台服务startForeground(id, notification);,它使我的通知保持粘性且无法清除。使用stopForeground(false); 解决了我的问题。如需更详细的答案,您可以查看:https://***.com/a/35721582

【讨论】:

【参考方案3】:

如果您使用的是服务,则必须在覆盖 onDestroy 时取消通知。

override fun onDestroy() 
    (context.getSystemService(Context.NOTIFICATION_SERVICE) as 
    NotificationManager).cancel(notificationId)
    stopForeground(true)
    super.onDestroy()

【讨论】:

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

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

如何清除从 Android 中点击通知打开的先前活动?

android 如何让通知不被清除或者点击后不消失

android 如何让通知不被清除或者点击后不消失?

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

清除 Android 的本地通知 cordova 插件