无法从FCM服务启动活动
问题描述:
我正在使用fcm在我的应用中发送通知。我想在用户点击通知时启动MsgViewActivity。现在,当应用程序处于前台,但是当应用程序未运行时,这工作得很好,只需将我带入主要活动即可。另外请注意,我正在使用数据消息,因此即使在后台也调用onMessageRecived。无法从FCM服务启动活动
这里是我的FirebaseMessagingService.class
public class FirebaseMessagingSer extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher);
Intent intent = new Intent(this, MsgViewActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
if(remoteMessage.getData().size()>0) {
String id = remoteMessage.getData().get("id");
Bundle bundle = new Bundle();
bundle.putString("id",id);
intent.putExtras(bundle);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder.setContentTitle("FCM NOTIFICATION");
notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setLargeIcon(bmp);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notificationBuilder.build());
}
}
答
从您的示例代码使用的是消息既notification: {..}
和data: {..}
有效载荷。
这意味着您的邮件被认为是notification-message
,因此方法onMessageReceived()
仅在应用程序处于前台时执行。 (这说明您的问题)
有两种解决方法:只
使用数据电文。请勿在通知中发送任何内容:{..}部分消息。您可以将主体和标题设置为数据有效负载中的附加键值。
您可以使用带参数click_action =“intent_to_activity2”的通知消息。
您还需要将意图过滤器添加到您的活动清单。