0

I have implemented FCM (Firebase Notification) and everything is working fine on all devices except Samsung Galaxy S8 and One-Plus 3

When application running in foreground/background everything is working perfectly

But when I Remove the application from Task Manager (Swipe-Tray) or finish the application using backPress() devices stop receiving notification,

My complete code of service and manifest.

MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "From: " + remoteMessage.getFrom());
        if (!remoteMessage.getData().containsKey("subtitle")) {
            if (remoteMessage.getData().size() > 0) {
                Log.d(TAG, "Message data payload: " + remoteMessage.getData());
                String title = remoteMessage.getData().get("title");
                String message = remoteMessage.getData().get("text");
                String rideId = remoteMessage.getData().get("ride_id");
                String rideName = remoteMessage.getData().get("ride_name");
                String ridePic = remoteMessage.getData().get("ride_pic");

                MessageDTO messageDTO = new MessageDTO();
                messageDTO.setRideId(Integer.parseInt(rideId));
                messageDTO.setRideName(rideName);
                messageDTO.setRidePic(ridePic);
                messageDTO.setMessage(message);
                // Don't show notification if chat activity is open.
                if (!AppController.isChatActivityOpen()) {
                    sendNotification(title, messageDTO);
                } else {
                    //EventBus.getDefault().post(new PushNotificationEvent(title, message, username, uid, fcmToken));
                }
            }
        }
        // Check if message contains a data payload.
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     */
    private boolean sendNotification(String title, MessageDTO messageDTO) {
        int id = (int) System.currentTimeMillis();
        Intent intent = new Intent(this, GroupChatActivity.class);
        intent.putExtra("SelectedChannel", messageDTO);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(title)
                .setContentText(messageDTO.getMessage())
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(id, notificationBuilder.build());
        int returnValue = 0;

        return returnValue == 1 ? true : false;

    }

}

AndroidManifest.xml

<service
    android:name="main.cyclesoon.com.chat.fcm.MyFirebaseMessagingService" android:stopWithTask="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</service>

My server side code :

public class FcmNotificationBuilder {
    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    private static final String TAG = "FcmNotificationBuilder";
    private static final String SERVER_API_KEY = "server_key";
    private static final String CONTENT_TYPE = "Content-Type";
    private static final String APPLICATION_JSON = "application/json";
    private static final String AUTHORIZATION = "Authorization";
    private static final String AUTH_KEY = "key=" + SERVER_API_KEY;
    private static final String FCM_URL = "https://fcm.googleapis.com/fcm/send";
    // json related keys
    //private static final String KEY_TO = "to";
    private static final String KEY_TO = "registration_ids";

    private static final String KEY_TITLE = "title";
    private static final String KEY_TEXT = "text";
    //private static final String KEY_DATA = "data";
    private static final String KEY_DATA = "notification";
    private static final String KEY_RIDE_ID = "ride_id";
    private static final String KEY_RIDE_NAME = "ride_name";
    private static final String KEY_RIDE_PIC = "ride_pic";

    private String mTitle;
    private String mMessage;
    private JSONArray mReceiverFirebaseToken;
    private String mRideId;
    private String mRideName;
    private String mRidePic;

    private FcmNotificationBuilder() {
    }

    public static FcmNotificationBuilder initialize() {
        return new FcmNotificationBuilder();
    }

    public FcmNotificationBuilder title(String title) {
        mTitle = title;
        return this;
    }

    public FcmNotificationBuilder message(String message) {
        mMessage = message;
        return this;
    }

    public FcmNotificationBuilder setRideInfo(String rideId, String rideName, String ridePic) {
        mRideId = rideId;
        mRideName = rideName;
        mRidePic = ridePic;
        return this;
    }

    public FcmNotificationBuilder receiverFirebaseToken(JSONArray receiverFirebaseToken) {
        mReceiverFirebaseToken = receiverFirebaseToken;
        return this;
    }

    public void send() {
        RequestBody requestBody = null;
        try {
            requestBody = RequestBody.create(MEDIA_TYPE_JSON, getValidJsonBody().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Request request = new Request.Builder()
                .addHeader(CONTENT_TYPE, APPLICATION_JSON)
                .addHeader(AUTHORIZATION, AUTH_KEY)
                .url(FCM_URL)
                .post(requestBody)
                .build();

        Call call = new OkHttpClient().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
               Log.d(TAG, "onGetAllUsersFailure: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: " + response.body().string());
            }
        });
    }

    private JSONObject getValidJsonBody() throws JSONException {
        JSONObject jsonObjectBody = new JSONObject();
        ///JSONArray jsonArray = new JSONArray();
        //jsonArray.put(mReceiverFirebaseToken);
        //jsonArray.put("fPMLS022iPE:APA91bEBJjgUDN-mSPtZjS4EtWT_DGnTmajc8gaWJUjULjodPrq9OUvhSHc3Lkk1Mxx8Z_b6g6NpJhKqe0WxZETz6vpnAxL2UnYU5qZYM2u0YEZdF0JgX0bD0jViqi6guKmwE_rss2CK");
        //jsonObjectBody.put(KEY_TO, mReceiverFirebaseToken);
        jsonObjectBody.put(KEY_TO, mReceiverFirebaseToken);
        JSONObject jsonObjectData = new JSONObject();
        jsonObjectData.put(KEY_TITLE, mTitle);
        jsonObjectData.put(KEY_TEXT, mMessage);
        jsonObjectData.put(KEY_RIDE_ID, mRideId);
        jsonObjectData.put(KEY_RIDE_NAME, mRideName);
        jsonObjectData.put(KEY_RIDE_PIC, mRidePic);
        jsonObjectBody.put(KEY_DATA, jsonObjectData);

        return jsonObjectBody;
    }
}
KENdi
  • 7,576
  • 2
  • 16
  • 31
akhilesh0707
  • 6,709
  • 5
  • 44
  • 51
  • What is the Android version of these devices? Does `AppController.isChatActivityOpen()` has a particular implementation and/or a version dependent implementation? – N0un Jul 25 '17 at 07:23
  • Yes this happens ! If you remove your app from task manager then this FCM service class is also killed ! Same thing happens with Mi phones ! – rushank shah Jul 25 '17 at 07:23
  • I explained different kind of Firebase messages here: https://stackoverflow.com/a/45015683/6523232 . You can see for each messages where it is triggered. What kind of Firebase messages are you using? – N0un Jul 25 '17 at 07:31
  • @N0un Nougat 7.0 `AppController.isChatActivityOpen()` is only to check activity is visible or not – akhilesh0707 Jul 25 '17 at 07:31
  • @AkhileshPatil In my previous comment I send you an answer that explain how Firebase messages are different. I use data messages and it works even if my app is killed manually from task manager. – N0un Jul 25 '17 at 07:34
  • @N0un thanks, let me try – akhilesh0707 Jul 25 '17 at 07:35
  • @N0un I tried data tag as well as notification tag but none of this working. – akhilesh0707 Jul 25 '17 at 08:48
  • @AkhileshPatil Ok, could you try to put a `sendNotification("title", "body");` call as the first instruction of the `onMessageReceived` function and test with data message again? – N0un Jul 25 '17 at 08:52
  • @N0un i have comment out all the code inside `onMessageReceived` and put `sendNotification("title", "body")`; but not working – akhilesh0707 Jul 25 '17 at 08:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/150062/discussion-between-n0un-and-akhilesh-patil). – N0un Jul 25 '17 at 08:57
  • 1
    Possible duplicate of [Android app not receiving Firebase Notification when app is stopped from multi-task tray](https://stackoverflow.com/questions/39504805/android-app-not-receiving-firebase-notification-when-app-is-stopped-from-multi-t) – AL. Jul 25 '17 at 13:14
  • Did you manage to solve this problem ? – Gagan Gupta Nov 28 '17 at 10:01
  • Yes, check the answer and ref the link – akhilesh0707 Nov 28 '17 at 10:05

1 Answers1

2

FCM sends notification in two forms inside data tag and another one in notification tag. When the app is open the data is triggered and when the app is cleared from the background, FCM tries to handle the notification on its own using notification tag. What you can do is by asking the server guy only to send with data as a key and not notification. Then you can handle the notification.

For more information read this link

Terril Thomas
  • 1,486
  • 13
  • 32
  • If server guy send notification with data as a key and if application is killed from task manager then it wont work ! – rushank shah Jul 25 '17 at 07:27
  • @rushankshah Yes it works (by experience). Please read the referenced link. Furthermore, I made an answer that explain the different kind of Firebase messages here: https://stackoverflow.com/a/45015683/6523232 – N0un Jul 25 '17 at 07:28
  • No it not works on Mi, huawei and many chinese devices ! Even sometime it wont work on Lenovo phones ! All these phones has inbuilt task killer option in recent app . So when i press task killer button then all application and its services will be killed and will not get any notification. – rushank shah Jul 25 '17 at 07:32
  • @rushankshah Ok, I didn't know that (I easily can expect that). But I think there is an other issue here because of the Samsung Galaxy S8. I had some problem with Samsung but Android's Services are a important part of the system and it is weird that Samsung fails with it for latest phone. – N0un Jul 25 '17 at 07:37
  • @N0un i am not saying that your explanation is wrong on FCM ! That's 100% correct but it wont work with many chinese devices ! – rushank shah Jul 25 '17 at 07:42
  • @rushankshah Yes I understand, thanks ^^ Just I expect that it should works on S8 isn't it? – N0un Jul 25 '17 at 07:51
  • @N0un yes it should ! – rushank shah Jul 25 '17 at 07:52