在Firebase onMessageReceived(RemoteMessage remoteMessage)
中,當您的應用程序位於Foreground時,將調用此方法。因此,點擊通知後,您可以打開另一個活動,例如NotiicationActivity
。Firebase onMessageReceived(RemoteMessage remoteMessage)不在應用程序處於後臺時調用
但是如果你的應用程序在後臺,那麼這個方法將不會被調用,並且在點擊通知時只會打開一個啓動器活動。
那麼,即使我們的應用程序在後臺,如何在點擊通知時打開NotificationActivity
。
我的代碼是這樣的:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
sendNotification(remoteMessage.getNotification().getBody());
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("key", messageBody);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Bitmap icon2 = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Sample")
.setContentText(messageBody)
.setAutoCancel(true)
.setLargeIcon(icon2)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(new Random().nextInt() /* ID of notification */, notificationBuilder.build());
}
}
閱讀這樣的回答:sloved問題[這裏是鏈接](http://stackoverflow.com/questions/ 40626233/firebase-onmessagereceived-not-called-when-app-is-inactive/40626866#40626866) –