Some Oreo devices are not getting Push Notification

旧城冷巷雨未停 提交于 2019-11-26 20:00:44

问题


Samsung S8/S5/J2/Note3 are getting Firebase Push Notification successfully either app is killed, in background or foreground,

but Infinix Note 5 (Android One- Oreo) and Oppo F9(Oreo) are not getting push notification if app is killed, they work fine if app is in background or foreground.

I went through a lot of articles, this and this, mentions that Chinese phones haves this problem, and there are some work around from user side to make these notification work on their phones.

but i want to know if anything is possible from development side to make notification work on each and every android device.

I am targeting API 27, and this is my code

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'

回答1:


Source : Enable background services and Jobs (or FCM) in Chinese ROMs

Infinix Note 5 (Android One- Oreo) and Oppo F9(Oreo) are not getting push notification if app is killed, they work fine if app is in background or foreground.

Chinese ROMs using (Oxygen OS, MIUI etc) when the apps are swiped from the recent app tray your app gets terminated ( similar to Force Stop). And due to this every task running in the background like Services, Jobs gets killed with the app. Even High priority FCM doesn’t see the daylight in Chinese ROMs

Real time problems :

1) You can’t fetch location of the user. So, no app would work properly if it depends on real-time location

2) You can’t recevie the FCM high priority notifications

3) No time specific task/Job would execute if app is not in the tray and many more ….

Solution

user needs to enable auto start in settings for app to keep background service/Job running.By default it is off.To do this in some of the devices we can use,

Sample code

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:


In the Oreo, they introduce one new concept of channelization of push notification. You can read more about channelization here. Implement the notification for Oreo and above the bellow ore separately. You can refer the following answer to fix the issue.

I have fixed the issue in xamarin.android, hope this will work for you.




回答3:


This is the issue with all the chinese devices.Once you have killed the app...it is removed from memory and not all active ...but in case of the other device makers this is not the case ..they will not remove the app completely from the memory. I too faced this issue with xiaomi devices ....they have an option to lock the app ,which keeps app in memory even if its killed to clear ram memory




回答4:


Since oreo there is new Notification Channels implementation (started in Android 8.0 (API level 26))

so you have to create the channel using below code

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);
        }

and override notification builder as below

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

assuming you have CHANNEL_ID value something you want

String CHANNEL_ID = "DEFAULT_NEWS_CHANNEL";

this is already tested with OnePlus3T device so it should work for you




回答5:


I hope the following code will work for you. Its working for me in every devices.

        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());

I just have created Notification Channel, Check If condition for Oreo.

Let me know if you get any problem. I am here to help you.

Thanks.




回答6:


I had same issue and after searching and working around, I have found that user need to enable autostart and battery optimization permission manually for more details refer this link



来源:https://stackoverflow.com/questions/52849445/some-oreo-devices-are-not-getting-push-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!