Android — добавление намерения к уведомлению

Я новичок в разработке Android и до сих пор не очень хорошо понимаю Intent. Здесь я использую Firebase для создания уведомлений, я добавляю намерение к моему уведомлению, но когда мое приложение находится на переднем плане, и я нажимаю на уведомление, ничего не происходит (когда приложение убито или в фоновом режиме оно работает хорошо).

Странно то, что в тот момент, когда он работал, когда я нажал на уведомление, была вызвана функция «onNewIntent» моего класса «MainActivity», но теперь ничего больше не происходит, и я думаю, что ничего не изменил в коде.

Вот как я создаю свое намерение:

Notifications notifs = new Notifications(this);
String title = remoteMessage.getData().get("title");
String body = remoteMessage.getData().get("body");
String url = remoteMessage.getData().get("url");

Intent intentNotif = new Intent(this, MainActivity.class);
intentNotif.setAction(Intent.ACTION_MAIN);
intentNotif.addCategory(Intent.CATEGORY_LAUNCHER);
intentNotif.putExtra("url", url);
intentNotif.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//intentNotif.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

notifs.showNotif (title, body, true, intentNotif);

Вот как я добавляю намерение в уведомление:

this.builderGeneric.setContentIntent(PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT));

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

РЕДАКТИРОВАТЬ : Вот как я создаю уведомление, если оно полезно:

Notifications(Context context) {
  this.context = context;

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    this.notifManager = context.getSystemService(NotificationManager.class);
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_LOW);
    channel.setDescription(CHANNEL_DESCRIPTION);
    channel.enableLights(false);
    channel.enableVibration(false);
    channel.setSound(null, null);
    if (this.notifManager != null) {
      this.notifManager.createNotificationChannel(channel);
    }
  } else {
    this.notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  }

  this.builderGeneric = new Notification.Builder(context)
      .setVisibility(Notification.VISIBILITY_PUBLIC)
      .setWhen(System.currentTimeMillis())
      .setSmallIcon(R.mipmap.ic_launcher_round);

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    this.builderGeneric.setChannelId(this.CHANNEL_ID);
  }
  if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
    this.builderGeneric.setSmallIcon(R.mipmap.ic_launcher_foreground);
  }
}

public void showNotif (String title, String text, boolean cancelable, Intent intent) {
  this.builderGeneric.setContentTitle(title)
      .setContentText(text)
      .setOngoing(!cancelable)
      .setContentIntent(PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT));

  Notification notifGeneric = this.builderGeneric.build();

  this.notifManager.notify(1, notifGeneric);
}

Обновлено еще раз: Вот мой манифест:

<application
  android:allowBackup = "true"
  android:fullBackupContent = "@xml/backup_descriptor"
  android:icon = "@mipmap/ic_launcher"
  android:label = "@string/app_name"
  android:launchMode = "standard"
  android:roundIcon = "@mipmap/ic_launcher_round"
  android:supportsRtl = "true"
  android:theme = "@style/AppTheme">

  <activity
    android:name = ".MainActivity"
    android:configChanges = "orientation|screenSize">
    <intent-filter>
      <action android:name = "android.intent.action.MAIN" />
      <category android:name = "android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
      <action android:name = "android.intent.action.VIEW" />
      <category android:name = "android.intent.category.DEFAULT" />
      <category android:name = "android.intent.category.BROWSABLE" />
    </intent-filter>
  </activity>

  <receiver
    android:name = ".NetworkChangeReceiver"
    android:label = "NetworkChangeReceiver">
    <intent-filter
      android:name = ".NetworkIntentFilter"
      android:label = "NetworkIntentFilter">
      <action
        android:name = "android.net.conn.CONNECTIVITY_CHANGE"
        tools:ignore = "BatteryLife" />
      <action android:name = "android.net.wifi.WIFI_STATE_CHANGED" />
    </intent-filter>
  </receiver>

  <service android:name = ".MyFirebaseService"
    android:exported = "false">
    <intent-filter>
      <action android:name = "com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
  </service>

</application>

Что вы ожидаете, когда пользователи нажимают на уведомление?

Son Truong 27.02.2019 10:07

И вот он снова работает, я по-прежнему ничего не менял в коде... очень странно.

Yrtiop 27.02.2019 10:10

Когда пользователь нажимает на уведомление, я просто хочу, чтобы вызывалась функция «onNewIntent» моего класса «MainActivity».

Yrtiop 27.02.2019 10:11

Какой у вас режим запуска MainActivity?

Khoa Tran 27.02.2019 11:15

Это стандартно, я добавил свой манифест, если вам это нужно

Yrtiop 27.02.2019 11:22
1
5
70
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Хорошо, сначала попробуйте удалить

intentNotif.setAction(Intent.ACTION_MAIN);
intentNotif.addCategory(Intent.CATEGORY_LAUNCHER);

Затем добавьте android:launchMode = "singleTask" (также удалив android:launchMode = "standard") внутри тега активности в AndroidManifest.xml.

Затем попробуйте еще раз, имейте в виду, что с launchMode является singleTask, и если вы нажмете на свое уведомление, когда ваша MainActivity открыта -> будет запущен onNewIntent (поскольку Android не создаст еще один экземпляр этого действия), в противном случае onCreate будет вызываться.

И если это сработает, я хотел бы порекомендовать вам прочитать больше о LaundMode здесь

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

Yrtiop 27.02.2019 11:49

Другие вопросы по теме