Is it possible to check if a notification is visible or canceled?

前端 未结 6 1653
别那么骄傲
别那么骄傲 2020-12-08 06:31

I would like to update notification data, but the only way I found is to launch a new one with the same Id.

The problem is that I don\'t want to raise a new one if t

6条回答
  •  眼角桃花
    2020-12-08 07:01

    This is how I solved it:

        private boolean isNotificationVisible() {
        Intent notificationIntent = new Intent(context, MainActivity.class);
        PendingIntent test = PendingIntent.getActivity(context, MY_ID, notificationIntent, PendingIntent.FLAG_NO_CREATE);
        return test != null;
    }
    

    This is how I generate the notification:

        /**
     * Issues a notification to inform the user that server has sent a message.
     */
    private void generateNotification(String text) {
    
        int icon = R.drawable.notifiaction_icon;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, text, when);
        String title = context.getString(R.string.app_name);
        Intent notificationIntent = new Intent(context, MainActivity.class);
    
        // set intent so it does not start a new activity
        //notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, MY_ID, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, text, intent);
    
        notification.flags |= Notification.FLAG_AUTO_CANCEL; //PendingIntent.FLAG_ONE_SHOT
    
        notificationManager.notify(MY_ID, notification);
    }
    

提交回复
热议问题