PendingIntent не работает с уведомлением FCM
Я хочу открыть Детальную активность при уведомлении о клике. Здесь PendingIntent
а также Notification
установить класс. я добавил addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
также добавил PendingIntent.FLAG_UPDATE_CURRENT
, Я искал все темы на сайте, я нашел это решения, я попробовал все из них.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO(developer): Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
Log.d(TAG, "From: " + remoteMessage.getFrom());
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
ArrayList<String> notificationData = new ArrayList<String >(remoteMessage.getData().values());
String fortuneID = notificationData.get(0);
sendNotification(remoteMessage.getNotification().getBody(),fortuneID);
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
private void sendNotification(String messageBody,String notificationID) {
Intent configureIntent = new Intent(getApplicationContext(), FalDetayActivity.class);
configureIntent.putExtra("extra", "123123");
configureIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
configureIntent.setAction("dummy_unique_action_identifyer" + "123123");
int dummyuniqueInt = new Random().nextInt(543254);
PendingIntent pendingClearScreenIntent = PendingIntent.getBroadcast(getApplicationContext(), dummyuniqueInt, configureIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("myApp")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingClearScreenIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1 /* ID of notification */, notificationBuilder.build());
}
}
Здесь getBundle
часть MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String quote = getIntent().getStringExtra("extra");
...
}
Еще одна проблема, которую я хочу открыть FalDetailActivity
но всегда открыт MainActiviy
а также getIntent()
всегда возвращать ноль. Наверное, мой PendingIntent
не установлено, я не нашел ошибку, пожалуйста, проверьте этот код. Спасибо...
ОБНОВИТЬ
Я обновляю getBroadcast
в getActivity
и удалить что-то
Intent configureIntent = new Intent(getApplicationContext(), FalDetayActivity.class);
configureIntent.putExtra("extra", "123123");
configureIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingClearScreenIntent = PendingIntent.getActivity(getApplicationContext(), 0, configureIntent, PendingIntent.FLAG_UPDATE_CURRENT);
2 ответа
Наконец-то я нашел решение: https://firebase.google.com/docs/notifications/android/console-audience
Когда ваше приложение находится в фоновом режиме, Android направляет уведомления в системный трей. При нажатии на уведомление пользователя открывается панель запуска приложения по умолчанию.
Это включает в себя сообщения, которые содержат как уведомления, так и данные. В этих случаях уведомление доставляется в системный трей устройства, а полезная нагрузка данных доставляется в дополнениях к назначению вашего средства запуска.
Вы хотите начать действие с ожидающим намерением, а не отправлять трансляцию. + Изменить PendingIntent.getBroadcast(...)
в PendingIntent.getActivity(...)
,
Вместо того, чтобы использовать getApplicationContext()
попробуйте использовать контекст службы, т.е. заменить getApplicationContext()
с this
,
Поскольку вы запускаете действие из контекста службы, вам также необходимо добавить флаг намерения новой задачи -
configureIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Кроме того, используйте эти флаги для вашего ожидаемого намерения -
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT