Android Oreo battery optimization causes delays in FCM

Viewed 3195

I have implemented the FCM exactly like documentation of if says:

I have a service like this public class TCMessagingService extends FirebaseMessagingService

And I have declared it in manifest like so:

<service android:name=".services.TCMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
</service>

I target and compile with SDK level 25, and my firebase version is 10.2.1.

Now the problem is that on Android 8.0 sometimes I have huge delays when I receive push notifications. it can come after a few minutes. But this is not always so, sometimes things work just like expected, push notifications came very quickly.

I tried to update the FCM version to the last one but that did not help.

But when in the settings I turn off the battery optimization for my app everything works fine. But this is not a solution. What can I do to make FCM work as expected on Android 8.0?

3 Answers

Actually I found the solution.

In order to fix delays on Android 8 push notifications you need to set the minimum compileSdkVersion 25 and

classpath 'com.google.gms:google-services:3.1.0' 

in project level gradle file.

This fixes the issue, hope it can help someone

You must:

  • Update compile version to 26
  • Update Build tools to 26.0.2
  • Minimum google service version : 11.0.4

  • Add this dependency:

    compile 'com.firebase:firebase-jobdispatcher:0.5.2'

  • Update firebase plugin to:

    classpath 'com.google.gms:google-services:3.1.0'

  • Add google repository in your project gradle

    allprojects { repositories { google() jcenter() } }

  • In your java cod the notification manager is created in another way in Android O:

          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
             NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
             String id = "id_product";
             // The user-visible name of the channel.
             CharSequence name = "Product";
             // The user-visible description of the channel.
             String description = "Notifications regarding our products";
             int importance = NotificationManager.IMPORTANCE_MAX;
             NotificationChannel mChannel = new NotificationChannel(id, name, importance);
             // Configure the notification channel.
             mChannel.setDescription(description);
             mChannel.enableLights(true);
             // Sets the notification light color for notifications posted to this
             // channel, if the device supports this feature.
             mChannel.setLightColor(Color.RED);
             notificationManager.createNotificationChannel(mChannel);
          }
    

You can find the full code in this link.

Related