Firebase消息传递:来自onMessageReceived的活动不会打开

时间:2017-06-11 19:25:19

标签: android firebase android-activity firebase-cloud-messaging

Firebase通知功能完善。我收到通知,但我有问题。我想在点击通知后打开一个特定的活动。如果应用程序是开放的,它的工作完美。但是,如果应用程序关闭,则会打开MainActivity。我不知道为什么。有人可以帮助我。我该改变什么?谢谢!

这里是onMessageReceived的代码:

public class MessageService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Intent intent=new Intent(this,activity2.class); //To this activity it should also go when the app isn't open

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle("App");
    notificationBuilder.setContentText(remoteMessage.getNotification().getBody());
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSmallIcon(R.drawable.icon);
    notificationBuilder.setContentIntent(pendingIntent);
    NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0,notificationBuilder.build());


}
}

修改

WelcomeActivity(启动器活动):

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_welcome);
    if (getIntent().hasExtra("type")) {
        Intent intent=new Intent(this, activity2.class);
        intent.putExtra("type",getIntent().getStringExtra("type"));
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    } else {
        startActivity(new Intent(this, MainActivity.class));
    }
}

2 个答案:

答案 0 :(得分:0)

  

当您的应用在后台时发送的通知消息:   在这种情况下,通知将传递到设备的系统托盘。用户点按通知会默认打开应用启动器。

来自https://firebase.google.com/docs/cloud-messaging/android/receive

一种方法是添加“click_action”标志,该标志将告诉系统当用户点击通知时要打开哪个活动。见https://stackoverflow.com/a/37656244/3482621

另见https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support

答案 1 :(得分:0)

当应用程序关闭或处于后台时,通知中的数据会到达intent中的启动器活动。您可以检查oncreate(),如果您的意图有数据,则打开所需的活动,否则简单打开启动器活动或主要活动,无论您的启动器活动是什么。