I implemented Firebase and testing the Firebase notifications. When the app is in the foreground I don't have problems, I implemented a service that extends FirebaseMessagingService and handle the message and data in onMessageReceived
I have problems when the app is in background, I would like to send a notification that opens a specific activity and does what I schedule to do, not just opening the App.
I did as described on the Firebase guide, but I'm not able to start the specific activity.
Here the manifest:
<activity android:name=".BasicNotificationActivity">
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
And here the Firebase Console. What do I have to write in those fields to open my "BasicNotificationActivity"?
This is a duplicate of this question: Firebase FCM notifications click_action payload
But the answer that was accepted by the author of this question just states that it is not possible with Firebase Console, but it is - with an easy workaround. This answer by diidu to the same question explains the workaround I would use.
UPDATE:
To elaborate on his answer:
Add a helper class (or implement startActivity()
method somehow):
public class ClickActionHelper {
public static void startActivity(String className, Bundle extras, Context context){
Class cls;
try {
cls = Class.forName(className);
}catch(ClassNotFoundException e){
//means you made a wrong input in firebase console
}
Intent i = new Intent(context, cls);
i.putExtras(extras);
context.startActivity(i);
}
}
In the launcher-activity of your app, call a mehtod to check any new intents in onCreate()
and onNewIntent()
(onNewIntent()
is only called instead of onCreate()
if Activity is launched with single-top flag):
@Override
protected void onCreate(Bundle bundle) {
[...]
checkIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
[...]
checkIntent(intent);
}
public void checkIntent(Intent intent) {
if (intent.hasExtra("click_action")) {
ClickActionHelper.startActivity(intent.getStringExtra("click_action"), intent.getExtras(), this);
}
}
And in onMessageReceived()
:
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
if (data.containsKey("click_action")) {
ClickActionHelper.startActivity(data.get("click_action"), null, this);
}
}
To send a notification with firebase console, put a key-value-pair as custom data like this:
Key: click_action
Value: <fully qualified classname of your activity>
Now when a notification is received and clicked on, it will open your activity. If your app is in foreground, it will also immediately change to the activity - it would probably be good to ask the user if he wants to go to this activity or not (by showing a dialog in onMessageReceived()
).