7

FCM push notification is working in following devices properly when the device is in the background, foreground and also when an app is close by swiping from a tray. Brandname (android-Version) Micromax (5.1) Motorola (7.1.1) Nokia (8.1.0) Samsung (8.0.0) Nexus (8.1.0) xiaomi (7.1.2)

But in case of oneplus, fcm notification is not working when an app is closed by swiping from a tray, but work properly when an app is in foreground and background. Device Version OnePlus 8.1.0

But when I manually off the battery optimization option for my app, then in all case fcm push notification work properly in Oneplus device

My androidManifest.xml is

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo.Notification"
    android:installLocation="auto">

    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <!-- [START fcm_default_icon] -->
        <!-- Set custom default icon. This is used when no icon is set for incoming notification messages. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/ic_launcher" />
        <!-- [END fcm_default_icon] -->
        <!-- [START fcm_default_channel] -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/default_notification_channel_id"/>
        <!-- [END fcm_default_channel] -->

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

        <activity
            android:name="com.demo.Notification.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

My MyFirebaseMessagingService.java

package com.demo.Notification;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.json.JSONObject;

public class MyFirebaseMessagingService extends FirebaseMessagingService
{
    private static final String NOTIFICATION_MESSAGE_KEY = "MESSAGE";
    private NotificationManager notificationManager;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage)
    {

        sendNotification(remoteMessage.getData().get(NOTIFICATION_MESSAGE_KEY));
    }

    private void sendNotification(String msg)
    {
        String notification_message_title = "";
        String notification_message_text = "";
        int notification_id = 1;
        String channel_id = getString(R.string.default_notification_channel_id);

        try
        {
            JSONObject jsonObject = new JSONObject(msg);

            if(jsonObject.has("notification_message_title"))
            {
                notification_message_title = jsonObject.getString("notification_message_title");
                notification_message_title = (notification_message_title != null) ? notification_message_title.trim() : "";
            }

            if(jsonObject.has("notification_message_text"))
            {
                notification_message_text = jsonObject.getString("notification_message_text");
                notification_message_text = (notification_message_text != null) ? notification_message_text.trim() : "";
            }

            if("".equals(notification_message_title))
            {
                return;
            }

            if("".equals(notification_message_text))
            {
                return;
            }

        }
        catch(Exception e)
        {
            return;
        }

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            setupChannels();
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this,channel_id);
        mBuilder.setAutoCancel(true);
        mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        mBuilder.setContentTitle(notification_message_title);
        mBuilder.setContentText(notification_message_text);
        mBuilder.setColor(Color.BLUE);
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);

        Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        mBuilder.setLargeIcon(largeIcon);

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


        Intent resultIntent = new Intent(this, MainActivity.class);
        resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        this,
                        notification_id,
                        resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            mBuilder.setChannelId(channel_id);
        }

        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
        notificationManagerCompat.notify(notification_id, mBuilder.build());

        //SEND Notification END
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setupChannels(){
        String channel_id = getString(R.string.default_notification_channel_id);
        CharSequence channelName = getString(R.string.default_notification_channel_name);

        NotificationChannel channel = new NotificationChannel(channel_id, channelName, NotificationManager.IMPORTANCE_MAX);
        channel.enableLights(true);
        channel.setLightColor(Color.BLUE);
        channel.enableVibration(true);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }
}

My app level build.gradel

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion "27.0.3"
    defaultConfig {
        applicationId "com.demo.Notification"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets { main { assets.srcDirs = ['src/main/assets', 'src/main/assets/'] } }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:27.1.1'    
    compile 'com.google.code.gson:gson:2.2.4'
    compile 'com.google.firebase:firebase-messaging:17.3.0'
}
apply plugin: 'com.google.gms.google-services'

My project level build.gradle

buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:4.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

And I am sending token to server in this way

public void registerDevice()
{
    FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(@NonNull Task<InstanceIdResult> task)
                {
                    String registrationId = task.getResult().getToken();
                    sendTokenToServer(registrationId);
                }
            });
}

Any small help will be appreciated

ashish pandey
  • 1,653
  • 1
  • 10
  • 15
  • Test case try `android:stopWithTask="false"` in `FirebaseMessagingService` in `manifest` file – AskNilesh Sep 05 '18 at 06:26
  • thanks for the response, but the same problem exists, by using your solution – ashish pandey Sep 05 '18 at 06:43
  • check this https://stackoverflow.com/a/51129304/7666442 – AskNilesh Sep 05 '18 at 06:44
  • I walkthrough to your code and also tried your code, but the same problem exists. – ashish pandey Sep 05 '18 at 07:09
  • I was facing the same issue. Following link helped me: https://stackoverflow.com/questions/46990995/on-android-8-1-api-27-notification-does-not-display – Yesha Oct 09 '18 at 12:27
  • @Yesha thanks for the link, but still, same problem exists. In the mean time i also find out that, even large organization app like flipkart, fasoos, myntra etc(Indian e-commerce company), have same problem. I am getting notification only from amazon app just because it is white listed in one plus 6 – ashish pandey Oct 13 '18 at 07:01

3 Answers3

2

this happens because of Doze Mode you can overcome this in fcm by setting the push notification message priority from backend side to be high message priority take a look at is documentation

Ramzy Hassan
  • 926
  • 8
  • 21
  • even changing the priority still, the same issue exists, it works when an app is in foreground and background but does not work when an app is swipe from the recent tab for oneplus6 mobile – ashish pandey Sep 05 '18 at 12:49
1

In these devices (like OnePlus,Huawie,OPPO) they are using custom version of os by base on android os may be when its on the battery optimisation it forcefully turn off the background service of FCM and we don't get any notification.

A. Wahab
  • 120
  • 1
  • 8
-1

Try this code

Uri defaultSoundUri = 
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
 NotificationCompat.Builder notificationBuilder = new 
NotificationCompat.Builder(this)
 .setSmallIcon(R.drawable.ic_notif_icon)
  .setContentTitle("testTitle")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setChannelId("testChannelId") // set channel id
.setContentIntent(pendingIntent);
Syed Danish Haider
  • 1,334
  • 11
  • 15