2016-12-23 2 views
0

Я пробовал почти каждое решение, размещенное здесь, и комбинацию каждого флага, но он не работает.FCM Уведомление onclick не открывает желаемую активность

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

1) Когда я нахожусь в заявке Уведомление FCM открывает мою желаемую деятельность. Данные передаются в основной вид деятельности onNewIntent. Он отлично работает, когда приложение является приоритетным.

2) Когда в фоновом режиме (нажатие кнопки «домой») после нажатия на уведомление, он запускает новый экземпляр моего приложения, хотя я указал android:launchMode="singleTop" в файле манифеста в свою основную деятельность, но я не знаю, что здесь происходит. Желаемая активность я хочу открыть здесь RateEventActivity

странное дело происходит здесь в том, что NotificationActivity и ProfileActivity работают отлично, даже если приложение работает в фоновом режиме, но RateEventActivity производит все проблемы, как я описал выше. Большинство кода приложения написано кем-то другим, я работаю над модулем RateEevent, поэтому я не знаю, чего я здесь не вижу?

Intents теряются где-то (не передается mainActivty при создании), когда я нажав уведомление из фонового режима в RateEventActivity сценария.

Я также пробовал передать уникальный идентификатор моему ожидающему намерению, но не повезло. Я положил много времени и усилий, чтобы решить эту проблему, но не суметь каждый раз, когда

вот мой FCM код

private void createNotification(RemoteMessage remoteMessage) { 
    RemoteMessage.Notification notification = remoteMessage.getNotification(); 
    NotificationManager mNotificationManager = (NotificationManager) 
      this.getSystemService(Context.NOTIFICATION_SERVICE); 

    Log.v("Notification Title", remoteMessage.getNotification().getTitle()); 

    Intent intent = new Intent(this, MainActivity.class); 
    //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
    if (remoteMessage.getData().containsKey("notificationUser")) { 
     intent.putExtra("notificationUser", remoteMessage.getData().get("notificationUser")); 
    } else if (remoteMessage.getData().containsKey("notificationId")) { 
     intent.putExtra("notificationId", remoteMessage.getData().get("notificationId")); 
    } else if (remoteMessage.getData().containsKey("event")) { 
     if (remoteMessage.getNotification().getTitle().equalsIgnoreCase("Event Feedback")) { 


      Log.v("Notification Event", remoteMessage.getData().get("event")); 
      intent.putExtra("eventId", remoteMessage.getData().get("event")); 
     } 


    } 


    //PendingIntent.FLAG_UPDATE_CURRENT 
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0 , intent, 
      PendingIntent.FLAG_UPDATE_CURRENT); 

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

    NotificationCompat.Builder mBuilder = 
      new NotificationCompat.Builder(this) 
        .setSmallIcon(R.drawable.ic_notification) 
        .setLargeIcon(largeIcon) 
        .setContentTitle(notification.getTitle()) 
        .setStyle(new NotificationCompat.BigTextStyle() 
          .bigText(notification.getBody())) 
        .setContentText(notification.getBody()) 
        .setAutoCancel(true); 

    mBuilder.setContentIntent(contentIntent); 
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); 
} 

Основная деятельность Код onCreate Метод

if (getIntent().hasExtra("notificationId")) { 
     Intent intent = new Intent(this, NotificationActivity.class); 
     intent.putExtra("notificationId", getIntent().getStringExtra("notificationId")); 
     startActivity(intent); 
    } else if (getIntent().hasExtra("user")) { 
     Intent intent = new Intent(this, ProfileActivity.class); 
     intent.putExtra("userId", getIntent().getStringExtra("user")); 
     startActivity(intent); 
    } else if (getIntent().hasExtra("eventId")) { 
     Intent intent = new Intent(this, RateEventActivity.class); 
     intent.putExtra("eventId", getIntent().getStringExtra("eventId")); 
     startActivity(intent); 
    } 

Мой манифеста Файл

<activity 
     android:name=".activities.MainActivity" 
     android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" 
     android:launchMode="singleTop" 
     android:screenOrientation="portrait" 
     android:theme="@style/HomeTheme" /> 

<activity 
     android:name=".activities.ProfileActivity" 
     android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" 
     android:label="Profile" 
     android:screenOrientation="portrait" /> 

<activity 
     android:name=".activities.NotificationActivity" 
     android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" 
     android:label="Notifications" 
     android:screenOrientation="portrait" /> 

<activity 
     android:name=".activities.RateEventActivity" 
     android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" 
     android:label="Rate Users" 
     android:screenOrientation="portrait" 
     /> 
+0

Вы получаете этот журнал 'Log.v (« Событие уведомления », remoteMessage.getData(). Get (« event »));' ?? –

+0

да, я получаю данные от push-уведомления. – user2991828

ответ

1

Если вы хотите открыть приложение и выполнить определенное действие [в фоновом режиме], установите click_action в полезной нагрузке уведомления и сопоставьте его с фильтром намерения в действии, который вы хотите запустить. Например, установите click_action в OPEN_ACTIVITY_1, чтобы вызвать пристальный фильтр, как следующее:

Как предложено в реакции родной-FCM документы, задать бэкенд для отправки данных JSON в форме, как это,

{ 

    "to":"some_device_token", 

    "content_available": true, 
    "notification": { 
    "title": "hello", 
    "body": "yo", 
    "click_action": "OPEN_ACTIVITY_1" // for intent filter in your activity 
    }, 

"data": { 
"extra":"juice" 
} 
} 

и в файле MainFest добавить пристальный фильтр для вашей деятельности, как показано ниже

<intent-filter> 
    <action android:name="OPEN_ACTIVITY_1" /> 
    <category android:name="android.intent.category.DEFAULT" /> 
</intent-filter> 

при нажатии на уведомление, он будет открыть приложение и перейти непосредственно к деятельности, которые вы определяете в click_action, в данном случае «OPEN_ACTIVTY_1».И в этой деятельности вы можете получить данные по:

Bundle b = getIntent().getExtras();// add these lines of code to get data from notification 
String someData = b.getString("someData"); 

заканчивало ниже ссылки для более помогает:

Firebase FCM notifications click_action payload

Firebase onMessageReceived not called when app in background

Firebase console: How to specify click_action for notifications

0

я получил этот вопрос долго тому назад. позвольте мне проверить код проекта.

Ahh его здесь.

Try с установкой флагов

Intent intent = new Intent(this, MainActivity.class));  
// set intent so it does not start a new activity 
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
     Intent.FLAG_ACTIVITY_SINGLE_TOP); 

и изменить свой PendingIntent, как показано ниже

PendingIntent contentIntent = PendingIntent.getActivity(this, , 
       intent, 0); 

Также удалить

android:launchMode="singleTop" 

из вашего MainActivity из манифеста файла

попробуйте это, и пусть он работает.

Смежные вопросы