Некоторые устройства Oreo не получают Push Notification - программирование

Некоторые устройства Oreo не получают Push Notification

Samsung S8/S5/J2/Note3 получает Firebase Push Notification S8/S5/J2/Note3 Firebase Push Notification либо приложение убито, на заднем плане или переднем плане,

но Infinix Note 5 (Android One- Oreo) и Oppo F9(Oreo) не получают push-уведомления, если приложение убито, они отлично работают, если приложение находится в фоновом режиме или на переднем плане.

Я прошел через много статей, это и это, отмечает, что китайские телефоны имущих этой проблемы, и есть некоторые работы из стороны пользователя, чтобы сделать эти уведомления работы на своих телефонах.

но я хочу знать, возможно ли что-либо со стороны разработки, чтобы сделать уведомление о работе каждого устройства Android.

Я нацелен на API 27, и это мой код

public class FirebaseMessagingService  extends com.google.firebase.messaging.FirebaseMessagingService {


  @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        String from = remoteMessage.getFrom();
        Map data = remoteMessage.getData();

        JSONObject jsonObject = new JSONObject();
        Set<String> keys = remoteMessage.getData().keySet();
        for (String key : keys) {
            try {
                jsonObject.put(key, remoteMessage.getData().get(key));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        message= jsonObject.getString("message");

         sendNotification(message, urlToOpen);



    private void sendNotification(final String msg, final String urlToOpen) {


        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.notification_channel_general);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.notification_icon)
                        .setContentTitle("App Name")
                        .setContentText(msg)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setPriority(Notification.PRIORITY_MAX)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "App Channel",
                    NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }

    notificationManager.notify(0, notificationBuilder.build());

Gradle

compileSdkVersion 27
defaultConfig {
    applicationId "com.myapp.app"
    minSdkVersion 19
    targetSdkVersion 27
    versionCode 2
    versionName "1"
    multiDexEnabled true
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    vectorDrawables.useSupportLibrary = true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        // Disable fabric build ID generation for debug builds
        ext.enableCrashlytics = false
    }
}

implementation 'com.google.firebase:firebase-messaging:15.0.0'
implementation 'com.google.android.gms:play-services-location:15.0.0'
implementation 'com.google.android.gms:play-services-auth:15.0.0'
implementation 'com.google.android.gms:play-services-basement:16.0.1'
implementation 'com.google.android.gms:play-services-ads-identifier:16.0.0'
implementation 'com.google.android.gms:play-services-stats:16.0.1'
implementation 'com.google.android.gms:play-services-tasks:16.0.1'
implementation 'com.google.android.gms:play-services-ads-identifier:16.0.0'
implementation 'com.google.android.gms:play-services-ads-identifier:16.0.0'
implementation 'com.google.android.gms:play-services-maps:16.0.0'
4b9b3361

Ответ 1

Источник: включение фоновых служб и рабочих мест (или FCM) в китайских ПЗУ

Infinix Note 5 (Android One- Oreo) и Oppo F9 (Oreo) не получают push-уведомления, если приложение убито, они отлично работают, если приложение находится в фоновом режиме или на переднем плане.

Китайские ПЗУ, использующие (Oxygen OS, MIUI и т.д.), Когда приложения выкачиваются из последнего лотка приложения, приложение прекращается (аналогично Force Stop). И из-за этого каждая задача, выполняемая в фоновом режиме, как Сервисы, Джобс убивается с помощью приложения. Даже высокий приоритет FCM не видит дневного света в китайских ПЗУ

Проблемы в реальном времени:

1) Вы не можете выбрать местоположение пользователя. Таким образом, никакое приложение не будет работать должным образом, если это зависит от местоположения в реальном времени

2) Вы не можете получать уведомления о высоком приоритете FCM

3) Никакая конкретная задача времени /Job не выполнялась, если приложение не находится в лотке и еще много....

Решение

пользователю необходимо включить автоматический запуск в настройках приложения, чтобы сохранить фоновый сервис/работа. По умолчанию он отключен. Чтобы сделать это на некоторых устройствах, которые мы можем использовать,

Образец кода

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent();

        String manufacturer = android.os.Build.MANUFACTURER;

        switch (manufacturer) {

            case "xiaomi":
                intent.setComponent(new ComponentName("com.miui.securitycenter",
                        "com.miui.permcenter.autostart.AutoStartManagementActivity"));
                break;
            case "oppo":
                intent.setComponent(new ComponentName("com.coloros.safecenter",
                        "com.coloros.safecenter.permission.startup.StartupAppListActivity"));

                break;
            case "vivo":
                intent.setComponent(new ComponentName("com.vivo.permissionmanager",
                        "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
                break;
        }

      List<ResolveInfo> arrayList =  getPackageManager().queryIntentActivities(intent,
              PackageManager.MATCH_DEFAULT_ONLY);

        if (arrayList.size() > 0) {
            startActivity(intent);
        }
    }

}

Ответ 2

В Oreo они вводят одну новую концепцию каналообразования push-уведомления. Вы можете прочитать больше о канализировании здесь. Внедрите уведомление для Oreo и выше следующей группы отдельно. Вы можете найти следующий ответ, чтобы исправить проблему.

Я исправил проблему в xamarin.android, надеюсь, что это сработает для вас.

Ответ 3

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

Ответ 4

Я надеюсь, что следующий код будет работать для вас. Он работает на меня в каждом устройстве.

        Intent notificationIntent = new Intent(context, SplashScreenActivity.class);

        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

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

        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence nameChannel = context.getString(R.string.app_name);
            String descChannel = context.getString(R.string.app_name);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(context.getString(R.string.app_name), nameChannel, importance);
            channel.setDescription(descChannel);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            assert notificationManager != null;
            notificationManager.createNotificationChannel(channel);
        }

        PendingIntent pendingIntent = PendingIntent.getActivity((context), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        // Create Notification
        NotificationCompat.Builder notification = new NotificationCompat.Builder(context, context.getString(R.string.app_name))
                .setChannelId(context.getString(R.string.app_name))
                .setContentTitle(TextUtils.isEmpty(title) ? getString(R.string.app_name) : title)
                .setContentText(description)
                .setTicker(context.getString(R.string.app_name))
                .setSmallIcon(R.drawable.ic_stat_name)
                .setSound(notificationSound)
                .setLights(Color.RED, 3000, 3000)
                .setVibrate(new long[]{500, 500})
                .setWhen(System.currentTimeMillis())
                .setDefaults(Notification.DEFAULT_SOUND)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        if (result != null) {
            notification.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(result));
        }

        assert notificationManager != null;
        notificationManager.notify(100, notification.build());

Я только что создал канал Notification Channel, Check If для Oreo.

Дайте мне знать, если у вас возникнут проблемы. Я здесь, чтобы помочь вам.

Благодарю.

Ответ 5

Начиная с oreo появляется новая реализация Notification Channels (начата в Android 8.0 (API-уровень 26))

поэтому вам нужно создать канал, используя код ниже

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "News Channel";
            String description = "Default Notification News Channel";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = getAppContext().getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

и переопределить конструктор уведомлений, как показано ниже

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getAppContext(),CHANNEL_ID);

если у вас есть значение CHANNEL_ID, что вы хотите

String CHANNEL_ID = "DEFAULT_NEWS_CHANNEL";

это уже протестировано с устройством OnePlus3T, поэтому оно должно работать для вас