Пользовательское уведомление (Remoteview) не работает, когда приложение убито - PullRequest
1 голос
/ 20 апреля 2020

Пользовательское уведомление не работает, когда процесс приложения убит. Приложение не вызывает метод onMessageReceived, когда в фоновом режиме / fini sh.

Как заставить приложение вызывать onMessageReceived (), я просто хочу, когда я отправляю уведомление из firebase, оно показывает мое пользовательское уведомление ...

Вот код ...

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {

    Map<String, String> data = remoteMessage.getData();
    configs.notificationId = data.get("notificationId");
    configs.title = data.get("title");
    configs.subject = data.get("subject");
    configs.image = data.get("image");

    initwithimage(configs.image);
}

private void initwithimage(String imageUrl) {      
    //Code removed for simplified
    sendwithimage(bitmap);
}

private void sendwithimage(Bitmap bitmap) {
    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification_layout);
    contentView.setImageViewBitmap(R.id.image, bitmap);
    contentView.setTextViewText(R.id.title, configs.title);
    contentView.setTextViewText(R.id.subject, configs.subject);
    contentView.setTextViewText(R.id.timeago, DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME));

    Intent openit = new Intent(this, notificationintentservice.class);
    openit.setAction("openit");
    contentView.setOnClickPendingIntent(R.id.openit, PendingIntent.getService(this, 0, openit, PendingIntent.FLAG_UPDATE_CURRENT));

    Intent closeit = new Intent(this, notificationintentservice.class);
    closeit.setAction("closeit");
    contentView.setOnClickPendingIntent(R.id.closeit, PendingIntent.getService(this, 0, closeit, PendingIntent.FLAG_UPDATE_CURRENT));

    Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,0);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "101";

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_MAX);
        //Configure Notification Channel
        notificationChannel.setDescription("Epic Studio");
        notificationChannel.enableLights(true);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableVibration(true);
        assert notificationManager != null;
        notificationManager.createNotificationChannel(notificationChannel);
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .setContent(contentView)
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setAutoCancel(true)
            .setSound(defaultSound)
            .setContentIntent(pendingIntent)
            .setWhen(System.currentTimeMillis())
            .setPriority(Notification.PRIORITY_MAX);

    assert notificationManager != null;
    notificationManager.notify(Integer.parseInt(configs.notificationId), notificationBuilder.build());
}

@Override
public void onNewToken(@NonNull String token) {}

}

Я знаю, что firebase не поддерживает уведомления о типе данных, для этого мы используем клиент уведомлений, такой как Postman / AR C, но Я не знаю, как их использовать. Я попробовал Почтальон и AR C, но пользовательское уведомление все еще не работает.

Вот JSON

{
 "to" : "bLawblawblaw-FeR06mmyABLaBlawblawblawblawblaw",
 "collapse_key" : "type_a",
 "notification" : {
     "body" : "Body of Your Notification",
     "title": "Title of Your Notification"
 },
 "data" : {
     "body" : "Body of Your Notification in Data",
     "title": "Title of Your Notification in Title",
     "key_1" : "Value for key_1",
     "key_2" : "Value for key_2"
 }
}

Я также пробовал ниже JSON только для отправки данных, но не работает. Уведомление не приходит

{
 "to" : "bLawblawblaw-FeR06mmyABLaBlawblawblawblawblaw",
 "data" : {
     "body" : "Body of Your Notification in Data",
     "title": "Title of Your Notification in Title",
     "key_1" : "Value for key_1",
     "key_2" : "Value for key_2"
 }
}

Ответы [ 2 ]

0 голосов
/ 20 апреля 2020

Проблема была в @NonNull в onMessageReceived ( @ NonNull ....)

Я отправлял уведомление о данных в моем приложении через клиента, поэтому нет сообщений о том, что означает RemoteMessage имеет значение null, поэтому метод не вызывается.

0 голосов
/ 20 апреля 2020

Вы отправляете уведомление о данных, поэтому сначала вам нужно получить данные об отправке, а затем получить значения внутри объекта данных

Map<String, String> data = remoteMessage.getData().get("data");

, а также добавить ключ изображения subjectId субъекта в объект данных, другие уведомления не будут будет отображаться в стеке уведомлений, поскольку вы не получите исключение для ключа

...