Все уведомления удаляются при нажатии только на одно уведомление - PullRequest
0 голосов
/ 13 февраля 2019

Я использовал службы обмена сообщениями Firebase и генерировал уведомления.Когда я получаю несколько уведомлений и когда я нажимаю на одно уведомление, все другие уведомления удаляются.Я не хочу удалять другие неиспользованные уведомления.Вот как я генерирую уведомление,

public class MyNotificationManager {

private Context mCtx;
private static  int notification_count=0;
private static MyNotificationManager mInstance;
public  static final String NOTIFICATION_CHANNEL_ID = "10001";
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
private MyNotificationManager(Context context) {
    mCtx = context;
}
public static synchronized MyNotificationManager getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MyNotificationManager(context);
    }
    return mInstance;
}
public void createNotification(String title, String message, int contentId)
{
    /**Creates an explicit intent for an Activity in your app**/
    Intent resultIntent = new Intent(mCtx,HomeActivity.class);
    resultIntent.putExtra("contentId", "" + contentId);
    resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    TaskStackBuilder mStackBuilder = TaskStackBuilder.create(mCtx);
    mStackBuilder.addNextIntent(resultIntent);

    PendingIntent resultPendingIntent =
            mStackBuilder.getPendingIntent(contentId, PendingIntent.FLAG_ONE_SHOT);

    mBuilder = new NotificationCompat.Builder(mCtx);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    mBuilder.setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(true)
            .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
            .setContentIntent(resultPendingIntent);

    mNotificationManager = (NotificationManager) mCtx.getSystemService(Context.NOTIFICATION_SERVICE);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
    {
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                "DEFAULT_CHANNEL", importance);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.enableVibration(true);
        notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        assert mNotificationManager != null;
        mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
        mNotificationManager.createNotificationChannel(notificationChannel);
    }

    assert mNotificationManager != null;
    mNotificationManager.notify(notification_count++ /* Request Code */, mBuilder.build());
}

}

1 Ответ

0 голосов
/ 13 февраля 2019

Попробуйте это поможет вам: -

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
    NotificationCompat.Builder builder;
    String CHANNEL_ID = "my_channel_01";
    PendingIntent pendingIntent;
    private NotificationUtils notificationUtils;
    private NotificationManager mNotificationManager;


    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

        if (remoteMessage.getNotification() == null)
            return;
        // Check if message contains a notification payload.
        if(remoteMessage.getNotification() != null) {
            handleNotification(remoteMessage, remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle());
        }

    }

    private void handleNotification(RemoteMessage remoteMessage, String body, String title) {
        if (mNotificationManager == null) {
            mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        }

        boolean isNotificationSound = true;
        //TODO: update count if app is open.
        if (!NotificationUtils.isAppIsInBackground(this)) {
            if (isNotificationSound) {
                try {
                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
                    r.play();
                } catch (Exception e) {
                }
            }
            covertRemoteToJson(remoteMessage, body, title);
        }else {
            covertRemoteToJson(remoteMessage, body, title);
        }
    }

    private void covertRemoteToJson(RemoteMessage remoteMessage, String body, String title) {
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                //Map<String, String> params = remoteMessage.getData();
                if (!StringUtils.isNullOrEmpty(remoteMessage.getData().toString())) {
                    JSONObject json = new JSONObject(remoteMessage.getData().toString());
                    handleDataMessage(json, body, title);
                }
            } catch (Exception e) {
                e.printStackTrace();
                e.getMessage();
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }

    private void handleDataMessage(JSONObject json, String body, String title) {
        int requestID = (int) System.currentTimeMillis();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            assert mNotificationManager != null;
            NotificationChannel mChannel = mNotificationManager.getNotificationChannel(CHANNEL_ID);
            if (mChannel == null) {
                mChannel = new NotificationChannel(CHANNEL_ID, title, importance);
                mChannel.enableVibration(true);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                mNotificationManager.createNotificationChannel(mChannel);
            }
            builder = new NotificationCompat.Builder(this);
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.putExtra(AppConstants.EXTRAS.IS_FROM_NOTIFICATION, true);
            intent.putExtra(AppConstants.EXTRAS.NOTIFICATION_LANDING_DATA, json.toString());
            pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
            builder.setContentTitle(title)                            // required
                    .setSmallIcon(getNotificationIcon())   // required
                    .setContentText(body).setWhen(System.currentTimeMillis()) // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
                    .setChannelId(CHANNEL_ID)
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        } else {
            builder = new NotificationCompat.Builder(this);
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            intent.putExtra(AppConstants.EXTRAS.IS_FROM_NOTIFICATION, true);
            intent.putExtra(AppConstants.EXTRAS.NOTIFICATION_LANDING_DATA, json.toString());
            pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
            builder.setContentTitle(title)                            // required
                    .setSmallIcon(getNotificationIcon())   // required
                    .setContentText(body).setWhen(System.currentTimeMillis()) // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setChannelId(CHANNEL_ID)
                    .setContentIntent(pendingIntent)
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                    .setPriority(Notification.PRIORITY_HIGH);
        }
        Notification notification = builder.build();
        mNotificationManager.notify(requestID, notification);
    }

    private static int getNotificationIcon() {
        return R.mipmap.ic_launcher;
    }

}
...