Some Oreo devices are not getting Push Notification
Asked Answered
L

6

15

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'
Lamina answered 17/10, 2018 at 7:29 Comment(0)
O
13

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

}
Ordinarily answered 23/10, 2018 at 7:56 Comment(4)
Thanks @Nilesh, Is it possible to launch this component on Infinx device? The infinix device i am testing on, contains Android One (Oreo 8.1) OS.Lamina
@TahaKirmani sorry to say i have no idea about Infinx device but have u added ` android:stopWithTask="false"` in your FirebaseMessagingService like this answer #51123697Ordinarily
I am getting the error " Caused by: java.lang.SecurityException: Permission Denial: starting Intent { cmp=com.coloros.safecenter/.startupapp.StartupAppListActivity } from ProcessRecord{54211b 26708:com.platute.app/u0a142} (pid=26708, uid=10142) requires oppo.permission.OPPO_COMPONENT_SAFE" even though I have addded oppo.permission.OPPO_COMPONENT_SAFE in the Android ManifestScroggins
But this is not working in all the vivo series and oppo series because its says "Activity not found" while trying to open setting screen.Wayne
P
6

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.

Pointer answered 19/10, 2018 at 14:19 Comment(4)
@K K: Thanks, but I am already using channels in push notificationsLamina
And still it is not working? R u receiving the notifications? Have u checked?Pointer
@K K, I am receiving notifications in samsung devices, but not on Chinese devices. Chinese devices do get notification if app is opened or in background.Lamina
This is the Issue with the custom OS, In fact, I face this issue in the OnePlus. Have you tried on a OnePlus device?Pointer
H
5

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

Hinton answered 22/10, 2018 at 9:6 Comment(0)
A
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

Asphyxiant answered 25/10, 2018 at 22:52 Comment(0)
C
3

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.

Cleanshaven answered 24/10, 2018 at 10:31 Comment(0)
L
1

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

Lineation answered 15/1, 2019 at 8:20 Comment(1)
Please accept/upvote the answer if this solves your issueLineation

© 2022 - 2024 — McMap. All rights reserved.