Push-уведомление FCM не работает на некоторых устройствах - PullRequest
0 голосов
/ 02 июля 2019

Мы создали приложение чата с уведомлениями, используя FCM мой код правильный, мое устройство также получает данные push-уведомлений, но некоторые устройства китайского производства, такие как vivo, oppo, one plus, xiaomi, не позволяютуведомление, чтобы показать, если я не добавлю приложение в список защищенных приложений соответствующего производителя.это их любое решение для этого.

https://hackernoon.com/notifications-in-android-are-horribly-broken-b8dbec63f48a

https://github.community/t5/Project-Development-Help-and/Firebase-Push-Notification-not-receiving-on-some-android-devices/td-p/5489

private NotificationManagerCompat notificationManager;

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    Log.d("test","call");

    notificationManager = NotificationManagerCompat.from(this);
    sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}

private void sendNotification(String title, String msg) {
    Intent resultIntent = new Intent(this, ActivitySplashScreen.class);

    String channelId = getString(R.string.chc);
    String channelName = "Message Notification";

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addNextIntentWithParentStack(resultIntent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(99, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentTitle(title)
            .setContentText(msg)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_MESSAGE)
            .setContentIntent(pendingIntent)
            .build();

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationManager manager = getSystemService(NotificationManager.class);
        NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
        manager.createNotificationChannel(channel);
    }

    notificationManager.notify(10, notification);
}

Ответы [ 2 ]

0 голосов
/ 09 июля 2019

Я могу подтвердить, что эта реализация хорошо работает с устройствами One Plus и Xiaomi (у нас есть множество пользователей, использующих наше приложение с этих устройств, и из них не возникает сбоев или проблем, связанных с уведомлениями FCM).

Невозможно подтвердить что-либо для Vivo или Oppo (пока мы знаем, что у нас нет пользователей, использующих устройства такого типа).

Самое главное, что функция уведомлений работает хорошореализовано, если приложение находится на переднем плане или в фоновом режиме.Если кто-то хочет увеличить масштаб этого вопроса, эта статья объясняет это простым способом.

Теперь код, который я использую для реализации FCM в Android:

// MyMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

  public static final String TAG = "Firebase Msg";

  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    Map<String, String> data = remoteMessage.getData();
    final LocalNotification localNotification = new LocalNotification();
    //data --> entityId - entityType - pushNotificationType
    // Check if message contains a data payload.
    if (data.size() > 0) {
        localNotification.setEntityId(data.get("entityId"));
        localNotification.setEntityType(data.get("entityType"));
        localNotification.setPushNotificationType(data.get("pushNotificationType"));
        localNotification.setTitle(data.get("title"));
        localNotification.setBody(data.get("body"));
        localNotification.setIcon(data.get("icon"));
        localNotification.setDate(new Date().getTime());
        localNotification.setRead(false);
    }

    if (localNotification.getEntityId() != null) {
        LocalNotification notificationRetrieved = FirebaseNotificationsHelper.insertLocalNotification(localNotification);
        FirebaseNotificationsHelper.createNotificationInStatus(notificationRetrieved);
    }
  }
}

// Создание статуса уведомления

static void createNotificationInStatus(LocalNotification localNotification) {

    String notificationChannelId = App.getContext().getString(R.string.default_notification_channel_id);
    String notificationChannelName = App.getContext().getString(R.string.default_notification_channel_name);
    String notificationChannelDescription = App.getContext().getString(R.string.default_notification_channel_description);

    NotificationCompat.Builder notificationBuilder;
    NotificationCompat.Builder notificationBuilderPublicVersion;

    notificationBuilder = new NotificationCompat.Builder(App.getContext(), notificationChannelId);
    notificationBuilderPublicVersion = new NotificationCompat.Builder(App.getContext(), notificationChannelId);

    notificationBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE | NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.DEFAULT_SOUND)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_stat_push_notif)
            .setTicker(localNotification.getTitle())
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setContentTitle(localNotification.getTitle())
            .setContentText(localNotification.getBody())
            .setStyle(new NotificationCompat.BigTextStyle().bigText(localNotification.getBody()))
            .setPublicVersion(notificationBuilderPublicVersion.setSmallIcon(R.drawable.ic_stat_push_notif).setContentTitle(localNotification.getTitle()).
                    setWhen(System.currentTimeMillis()).setContentText(localNotification.getBody()).build())
            .setGroup(NOTIFICATION_GROUP)
            .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
            .setAutoCancel(true);

    int notificationId = SharedPreferencesUtils.getInstance(App.getContext()).getIntValue(PREF_KEY_NOTIFICATION_ID, 0);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, notificationChannelName, NotificationManager.IMPORTANCE_HIGH);
        // Configure the notification channel.
        notificationChannel.setDescription(notificationChannelDescription);
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableVibration(true);
        notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
        notificationManager.createNotificationChannel(notificationChannel);
        notificationManager.notify(notificationId, notificationBuilder.build());
    } else {
        /* Kitkat and previous versions don't show notifications using NotificationManagerCompat */
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(notificationId, notificationBuilder.build());
        } else {
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(App.getContext());
            notificationManager.notify(notificationId, notificationBuilder.build());
        }
    }
    notificationId++;
    SharedPreferencesUtils.getInstance(App.getContext()).setValue(PREF_KEY_NOTIFICATION_ID, notificationId);
}
0 голосов
/ 02 июля 2019

Я не думаю, что есть общее решение для этого, так как ваше приложение основано на google-FCM, что означает, что устройство Android регулярно соединяется с google-internet-services.

Насколько я знаю, google-FCM заблокирован (= недоступен) в Китае

...