Как открыть определенную активность из push-уведомлений в Android & FCM? - PullRequest
1 голос
/ 14 июня 2019

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

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

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    processNotification()
}

private fun processNotification() {
    val notificationCategory = intent?.extras?.getString("category") ?: return
    if (notificationCategory == "new_message") {
        startMessagingActivity()
        finish()
    }
}

Этот метод мне кажется грязным и не удобным. Можно ли указать действие, которое будет открываться при нажатии на push-уведомление?

РЕДАКТИРОВАТЬ Шаги для решения:

  1. Добавить фильтр намерений к деятельности, которую вы хотите открыть:

    <activity android:name=".messages.chatroom.ChatRoomActivity">
        <intent-filter>
            <action android:name="*your-action-name*"/>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
    </activity>
    
  2. Добавьте поле 'click_action = " your-action-name "' к вашему сообщению FCM.

Android автоматически открывает действие с действием, аналогичным click_action

Ответы [ 2 ]

0 голосов
/ 14 июня 2019

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

 type = remoteMessage.getData().get("type");
if(type.equals("1")) { // here you can just detremine the activity you want to open
              Intent intent;
              PendingIntent pendingIntent;
              NotificationCompat.Builder builder;
              if (notifManager == null) {
                  notifManager = (NotificationManager) getSystemService
                          (Context.NOTIFICATION_SERVICE);
              }

              intent = new Intent (this, Admin_page.class); // here chose the activity
              if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                  int importance = NotificationManager.IMPORTANCE_HIGH;
                  if (mChannel == null) {
                      NotificationChannel mChannel = new NotificationChannel
                              ("0", title, importance);
                      mChannel.setDescription (body);
                      mChannel.enableVibration (true);
                      mChannel.setVibrationPattern (new long[]
                              {100, 200, 300, 400, 500, 400, 300, 200, 400});
                      notifManager.createNotificationChannel (mChannel);
                  }
                  builder = new NotificationCompat.Builder (this, "0");

                  intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP |
                          Intent.FLAG_ACTIVITY_SINGLE_TOP);
                  pendingIntent = PendingIntent.getActivity (this, 0, intent, 0);
                  builder.setContentTitle (title)  // flare_icon_30
                          .setSmallIcon(R.drawable.logo_app).setTicker(title).setWhen(0)
                          .setContentText (body)  // required
                          .setDefaults (Notification.DEFAULT_ALL)
                          .setAutoCancel (true)
                          .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.logo_app))
                          .setContentIntent (pendingIntent)
                          .setSound (RingtoneManager.getDefaultUri
                                  (RingtoneManager.TYPE_NOTIFICATION))
                          .setVibrate (new long[]{100, 200, 300, 400,
                                  500, 400, 300, 200, 400});
              } else {

                  builder = new NotificationCompat.Builder (this);

                  intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP |
                          Intent.FLAG_ACTIVITY_SINGLE_TOP);
                  pendingIntent = PendingIntent.getActivity (this, 0, intent, 0);
                  builder.setContentTitle (title)
                          .setSmallIcon(R.drawable.logo_app).setTicker(title).setWhen(0)
                          .setContentText (body)  // required
                          .setDefaults (Notification.DEFAULT_ALL)
                          .setAutoCancel (true)
                          .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.logo_app))

                          .setContentIntent (pendingIntent)
                          .setSound (RingtoneManager.getDefaultUri
                                  (RingtoneManager.TYPE_NOTIFICATION))
                          .setVibrate (new long[]{100, 200, 300, 400, 500,
                                  400, 300, 200, 400})
                          .setPriority (Notification.PRIORITY_HIGH);
              } // else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
              Notification notification = builder.build ();
              notifManager.notify((int)date.getTime(), notification);
          }

надеюсь, что работа для вас

0 голосов
/ 14 июня 2019

Вам нужно будет использовать Android Deep Linking.

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

Для активности чата в манифесте должны быть объявлены хост и схема, ниже приведены инструкции и код для Deep Linking:

https://developer.android.com/training/app-links/deep-linking

Удачного кодирования.

...