简体   繁体   中英

Clear notification of an android app (Java)

I have a notification in my music app with following code:

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);

    }

I have created separate class(ApplicationClass) for creating notification channel.

@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);


    }
}

}

And also, I have a class (NotificationReceiver) for receiving notification action:

 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;
            }
        }
    }
}

My notification functions(play, pause & next) works properly, but my problem is that, I am unable to clear notification. I tried many times but I could not get it right.

try this

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);

 }

set notifId for eachNotification and make this class for handle all action in notification.

note : To set each event for each notification button, you first rationalize all actions to the NotifAction class, and from there define click events for each using the class.

create class for 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);
    }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM