Уведомления Firebase не работают должным образом - PullRequest
0 голосов
/ 05 июля 2018

Нужна помощь в уведомлениях Firebase.

В моем приложении я использую FCM для отправки push-уведомлений пользователям моего приложения.

Используя Почтальон, я отправляю уведомления о данных в свое приложение. Посмотрев в Интернете, я выполнил обработку уведомлений о данных в своем приложении, и теперь я могу отображать разные данные или открывать различные действия на основе параметров, отправленных через уведомление.

Но когда я пытаюсь сделать то же самое, используя консоль Firebase с уведомлениями о данных, это просто открывает приложение с помощью программы запуска.

Здесь происходит что-то странное, но я не могу понять.

С ПОСТМАНОМ: Отправка уведомления с помощью Postman, когда приложение находится на переднем плане, вызывает targetActivity, НО, когда я пытаюсь сделать то же самое с приложением в фоновом режиме, я получаю уведомление, но, щелкая уведомление, просто уходите из трея и ничего не делаете.

с консолью Firebase Отправка уведомления через FCM Concole просто открывает активность запуска, а не targetActivity. Не имеет значения, находится ли приложение на переднем или заднем плане.

Вот мой код

ЗАПРОС ПОСТМАНА:

{
"to" : "cwDBStUSeB-MY-Firebase-Token-JOLscpe_6OWQoWnounUhw_trlY5Qw8w",

 "notification" : {
        "click_action" : ".SurveySlider", // i'm not using this 
        "body" : "Complete the survey and get bonus points.", 
        "title" : "Survey", 
         }, 
 "data": {  "transactionID" : "123456",
    "openActivity" : "Surveys",
    "message" : "This is message from data set."

 }
}

onMessageПолучено в моем приложении для Android

 {
        Intent intent = new Intent(this, BaseDrawerActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        intent.putExtra("transactionID", remoteMessage.getData().get("transactionID"));
        intent.putExtra("targetActivity", remoteMessage.getData().get("openActivity"));

//        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
//            manager.createNotificationChannel(channel);
//        }

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(BaseDrawerActivity.class);

        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(intent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
       // builder.setContentIntent(resultPendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);



        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        String channelId = "Default";
        NotificationCompat.Builder builder = new  NotificationCompat.Builder(this, channelId)
                .setSmallIcon(R.drawable.ic_logo_circle)
                .setContentTitle(remoteMessage.getNotification().getTitle())
                .setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);

        int id = new AtomicInteger(0).incrementAndGet();
        manager.notify(id, builder.build());
}

BaseDrawerActivity для обработки различных целевых операций на основе данных уведомлений.

       Bundle bundle = getIntent().getExtras();
        if (bundle != null) {

            if (bundle.containsKey("targetActivity")) {
                String target = bundle.getString("targetActivity");    
                if (target.equalsIgnoreCase("Transactions")) {

                    MyActivity _myActivity = new MyActivity();
                    Bundle args = new Bundle();
                    args.putString("transactiontype", "all");
                    _myActivity.setArguments(args);
                    _fragmentTransaction = getSupportFragmentManager().beginTransaction().replace(R.id.content_base_drawer, _myActivity);
                    current = R.id.nav_Activity;
                    _fragmentTransaction.commit();


                } else if (target.equalsIgnoreCase("Surveys")) {
                    if (bundle.containsKey("transactionID")) {
                        String TID = bundle.getString("transactionID");
                        startActivity(new Intent(BaseDrawerActivity.this, SurveySlider.class).putExtra("Transaction_ID", TID));
                    } else {
                        Toast.makeText(getApplicationContext(), getText(R.string.transactionIDmissing), Toast.LENGTH_SHORT).show();
                    }
                }else{
                    navigationView.getMenu().performIdentifierAction(R.id.nav_OverView, 0);
                    current = R.id.nav_OverView;
                    navigationView.getMenu().getItem(0).setChecked(true);
                }

            }else{

                    navigationView.getMenu().performIdentifierAction(R.id.nav_OverView, 0);
                current = R.id.nav_OverView;
                navigationView.getMenu().getItem(0).setChecked(true);

            }

        }
        else
            Log.d(TAG, "Bundle is NULL");
}

Пожалуйста, помогите мне.

PS Мое приложение основано на Navigationdrawer с фрагментами. Поэтому, если кто-то может помочь мне эффективно обрабатывать TargetActivites (фрагменты) в зависимости от цели в полезной нагрузке Notification, сделайте это.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...