Метод onMessageReceived не вызывается, когда приложение не открыто - PullRequest
0 голосов
/ 19 марта 2020

Я реализовал FCM в своем приложении, и мне нужно передать некоторые данные из службы Firebase в Activity. Я реализовал следующий код, который прекрасно работает, когда приложение находится на переднем плане (открыто). Когда приложение убито или находится в фоновом режиме, метод onMessageReceived не вызывается, и действие средства запуска загружается при нажатии на уведомление pu sh. Также, когда приложение открыто, сообщение pu sh остается пустым. Просьба сообщить, что я сделал не так. К вашему сведению, из бэкэнда они отправляют данные, а не уведомления.

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

    public FirebaseMessagingService() {
    }

    private static final String TAG = com.google.firebase.messaging.FirebaseMessagingService.class.getSimpleName();
    public static String CHAT_PUSH_NOTIFICATION_INTENT = "chatPushNotificationIntent";
    private PreferencesManager preferencesManager;

    @Override
    public void onNewToken(String s) {
        super.onNewToken(s);
        Log.e("push token >>", s);
        String reliableIdentifier = FirebaseInstanceId.getInstance().getId();

        FCMPreferencesManager pref = FCMPreferencesManager.getInstance(this);
        if (pref != null) {
            pref.setStringValue(FCMPreferencesManager.FCM_KEY_VALUE, s);
            pref.setStringValue(FCMPreferencesManager.DEVICE_ID, reliableIdentifier);
        }


    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        try {
            preferencesManager = PreferencesManager.getInstance(this);
            int userId = preferencesManager.getIntValue(PreferencesManager.LOGIN_USER_ID);
            Log.e("onMessage received >>", "inside service");
            Log.e("userId >>", userId + "");
            if (userId > 0) {
                Log.e("remote message >>", remoteMessage.getNotification().getBody() + "");
                if (remoteMessage.getData().size() > 0) {
                    Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
                    try {
                        JSONObject json = new JSONObject(remoteMessage.getData().toString());
                        handleDataMessage(json);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void classApprovedNotification(int jobId, String stage) {
        if (!Utils.isAppIsInBackground(getApplicationContext())) {
            Intent pushNotification = new Intent(Constants.PUSH_NOTIFICATION_INTENT);
            pushNotification.putExtra("jobId", jobId);
            pushNotification.putExtra("stage", stage);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
        }
    }


    private void handleDataMessage(JSONObject json) {
        try {
            Log.e("total json >> ", json.toString());
            JSONObject data = json.optJSONObject("data");
            Log.e("data >> ", data.toString());
            String title = data.optString("title");
            String message = data.optString("message");
            Log.e("title >>", title);
            Log.e("message >>", message);
            localNotification(data, title, message, false);
        } catch (Exception e) {
            Log.e(TAG, "Json Exception: " + e.getMessage());
        }
    }

    private void localNotification(JSONObject data, String title, String message, boolean isSendBird) {

        int type = 0, groupId = 0, classId = 0, jobId = 0;
        String stage = "";
        int notificationId = (int) System.currentTimeMillis();
        int userId = preferencesManager.getIntValue(PreferencesManager.LOGIN_USER_ID);
        String className = "", fileName = "";
        if (data != null) {

            jobId = data.optInt("job_id");
            stage = data.optString("stage", "");


        }


        Log.e("jobId in service >>", jobId + "");
        Log.e("stage in service >>", stage);
        Intent intent = new Intent(FirebaseMessagingService.this, VendorHomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra("jobId", jobId);
        intent.putExtra("stage","stage");
        int requestID = (int) System.currentTimeMillis();
        final PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        this,
                        requestID,
                        intent,
                        PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
                );

        String channelId = "";
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.fyxt_logo)
                        .setContentTitle(title)
                        .setContentText(message)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(resultPendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
       /* NotificationManagerCompat notificationManager =
                NotificationManagerCompat.from(this);*/
        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);

            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(notificationId /* ID of notification */, notificationBuilder.build());
        try {
            PowerManager.WakeLock screenLock = null;
            if ((getSystemService(POWER_SERVICE)) != null) {
                screenLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(
                        PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "OOTUSER:WAKE");
                screenLock.acquire(10 * 60 * 1000L /*10 minutes*/);
                screenLock.release();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        classApprovedNotification(jobId, stage);
    }


}

В моей деятельности у меня есть следующий код.

 private BroadcastReceiver notificationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            jobIdFromNotification = intent.getIntExtra("jobId", 0);
            stageFromNotification = intent.getStringExtra("stage");
            Log.e("jobIdFromNotification >>", jobIdFromNotification + "");
            Log.e("stageFromNotification >>", stageFromNotification);
            prefManager.setIntValue(PreferencesManager.JOB_ID_IN_PREF, jobIdFromNotification);
            prefManager.setStringValue(PreferencesManager.JOB_STAGE_IN_PREF, stageFromNotification);
            classApprovedViewUpdate();
        }
    };

    private void classApprovedViewUpdate() {
        if (jobIdFromNotification > 0) {
            fragmentInteractionCallback = (BaseFragment.FragmentInteractionCallback) this;
            Log.e("inside push receiver update ", "sfs");
            if (stageFromNotification.trim().equalsIgnoreCase(Constants.STAGE_TICKET_APPROVAL)) {
                sendActionToActivity(ACTION_CREATE_MAINTENANCE_REQUEST, currentTab, true, fragmentInteractionCallback);
            } 
        }
    }

Редактировать: данные полезной нагрузки:

{
"data": {
"type": 0,
"job_id": 123,
"stage": "STAGE_TICKET_APPROVAL",
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...