title: Android background notifications with Firebase Cloud Messaging not received
body: <p>I've searched a lot about notifications when the app is in the background or closed. I'm using Firebase Cloud Messaging by the way. It won't work for me. I've used the Android setup and when the app is in the foreground or the phone is not locked the notification is received.</p>
  
  <ul>
  <li>When installed the token is printed correctly and subscribed to the topic.</li>
  <li>When I send a notification when the app is <strong>active in the foreground</strong> (so screen is unlocked and app is shown) I receive the notification and title as stated in the <code>onMessageReceived</code>.</li>
  <li>When I send a notification when the app is <strong>not shown</strong> but is still in recent apps and screen is <strong>unlocked</strong> I receive the notification with title and message as stated in <code>notification payload</code>.</li>
  <li>When I send a notification when the app is <strong>not shown</strong> but is still in recent apps and screen is <strong>locked</strong> nothing is received.</li>
  <li>When I send a notification when app is <strong>*closed and removed from recent apps</strong> nothing is received.</li>
  </ul>
  
  <p>How can I change this so the app will always receive the notifications, even when closed or the phone is locked?</p>
  
  <p>Ps. I read about the Doze modus with protected apps, even when I put my app with the protected ones I receive nothing. I'm testing on a Huawei P8 Lite.</p>
  
  <p><strong>AndroidManifest</strong></p>
  
  <pre><code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt;
  &lt;uses-permission android:name="android.permission.CALL_PHONE" /&gt;
  &lt;uses-permission android:name="android.permission.WRITE_SETTINGS"/&gt;
  &lt;uses-permission android:name="android.permission.VIBRATE" /&gt;
  &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;
  
  &lt;application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:supportsRtl="true"
      android:theme="@style/AppTheme" &gt;
      &lt;activity android:name=".activities.MainActivity"
          android:configChanges="orientation"
          android:screenOrientation="portrait"&gt;
          &lt;intent-filter&gt;
              &lt;action android:name="android.intent.action.MAIN" /&gt;
  
              &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
          &lt;/intent-filter&gt;
      &lt;/activity&gt;
      &lt;service
          android:name=".services.MyAppFirebaseMessagingService"
          android:enabled="true"
          android:exported="true"&gt;
          &lt;intent-filter&gt;
              &lt;action android:name="com.google.firebase.MESSAGING_EVENT"/&gt;
          &lt;/intent-filter&gt;
      &lt;/service&gt;
      &lt;service
          android:name=".services.FirebaseIDService"
          android:enabled="true"
          android:exported="true"&gt;
          &lt;intent-filter&gt;
              &lt;action android:name="com.google.firebase.INSTANCE_ID_EVENT"/&gt;
          &lt;/intent-filter&gt;
      &lt;/service&gt;
      &lt;receiver android:name=".services.NotificationReceiver" /&gt;
  &lt;/application&gt;
  </code></pre>
  
  <p><strong>Gradle</strong></p>
  
  <pre><code>dependencies {
      compile fileTree(dir: 'libs', include: ['*.jar'])
      testCompile 'junit:junit:4.12'
      compile 'com.google.firebase:firebase-core:9.2.0'
      compile 'com.google.firebase:firebase-messaging:9.2.0'
  }
  
  apply plugin: 'com.google.gms.google-services'
  </code></pre>
  
  <p><strong>FirebaseMessagingService</strong></p>
  
  <pre><code>public class MyAppFirebaseMessagingService extends FirebaseMessagingService {
      private static final String TAG = "FCM Service";
  
      @Override
      public void onMessageReceived(RemoteMessage remoteMessage) {
          // TODO: Handle FCM messages here.
          // If the application is in the foreground handle both data and notification messages here.
          // Also if you intend on generating your own notifications as a result of a received FCM
          // message, here is where that should be initiated.
          Log.d(TAG, "From: " + remoteMessage.getFrom());
          Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
  
          showNotification(getApplicationContext());
      }
  
      public static void showNotification(Context context){
          Intent intent = new Intent(context, MainActivity.class);
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
          PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent,
              PendingIntent.FLAG_ONE_SHOT);
  
          Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
          NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
              .setSmallIcon(R.drawable.ic_launcher)
              .setContentTitle("FCM Message")
              .setContentText("FCM Body")
              .setAutoCancel(true)
              .setSound(defaultSoundUri)
              .setPriority(Notification.PRIORITY_MAX)
              .setContentIntent(pendingIntent);
  
          NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  
          notificationManager.notify(0, notificationBuilder.build());
      }
  }
  </code></pre>
  
  <p><strong>FirebaseInstanceIDService</strong></p>
  
  <pre><code>public class FirebaseIDService extends FirebaseInstanceIdService {
  
      private static final String TAG = "FirebaseIDService";
  
      @Override
      public void onTokenRefresh() {
          // Get updated InstanceID token.
          String refreshedToken = FirebaseInstanceId.getInstance().getToken();
          Log.d(TAG, "Refreshed token: " + refreshedToken);
  
          System.out.println("Devicetoken: " + refreshedToken);
  
          FirebaseMessaging.getInstance().subscribeToTopic("/topics/myapp");
  
          // TODO: Implement this method to send any registration to your app's servers.
          sendRegistrationToServer(refreshedToken);
       }
  
      /**
       * Persist token to third-party servers.
       *
       * Modify this method to associate the user's FCM InstanceID token with any server-side account
       * maintained by your application.
       *
       * @param token The new token.
       */
      private void sendRegistrationToServer(String token) {
           // Add custom implementation, as needed.
      }
  }
  </code></pre>
  
  <p><strong>Notification payload</strong></p>
  
  <pre><code>{
      "to": "/topics/mytopic",
      "priority": "high",
      "notification": {
          "sound": "default",
          "badge": "1",
          "body": "the body text",
          "title": "title text"
       },
       "data": {
           "id": "id",
           "channel": "channel"
       }
  }
  </code></pre>
  
  <p><strong>EDIT - Add code for WakeFulBroadcastReceiver</strong></p>
  
  <pre><code>public class NotificationReceiver extends WakefulBroadcastReceiver {
  
      @Override
      public void onReceive(Context context, Intent intent) {
  
          // cancel any further alarms
          AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
          PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
          alarmMgr.cancel(alarmIntent);
          completeWakefulIntent(intent);
  
          // start the GcmTaskService
          MyAppFirebaseMessagingService.showNotification(context);
      }
  }
  </code></pre>
  
  <p><strong>UPDATE PAYLOAD</strong></p>
  
  <p>If I change my payload to the suggested way in the comments like this it is still not working. Maybe it has something to do with the Huawei P8 Lite that I'm testing on with Android 6.0.1 installed.</p>
  
  <pre><code>{
      "to": "/topics/mytopic",
      "priority": "high",
      "data": {
          "sound": "default",
          "badge": "1",
          "body": "the body text",
          "title": "title text"
      }
  }
  </code></pre>
  
  <p><strong>UPDATE 2.0</strong></p>
  
  <p>I've tested on multiple devices and versions. On devices with Android 5 it was working fine, also without app open and screen locked. Only device it wasn't working was my own Huawei P8 Lite. Still can't figure out why it's not working on that one.</p>