android android -4 years ago 111
Android Question

Firebase Messaging: Activity from onMessageReceived doesn't open

Firebase Notification works perfect. I get the notifications, but I have a problem. I want to open a specific activity after clicking on the notification. If the app is open, it works perfect. But if the app is closed, the MainActivity opens. I don't know why. Can somebody help me. What must I change? Thanks!

Here's the code of 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());


}
}





EDIT

WelcomeActivity (launcher activity):

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));
}
}

Answer Source

when the application is closed or is in background the data from the notification arrives at your launcher activity in the intent. You can put a check in oncreate() that if your intent has data then open desired activity otherwise simple opens launcher activity or main activity whatever be your launcher activity.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download