Firebase FCM notifications click_action payload
As far as I can tell, at this point it is not possible to set click_action in the console.
While not a strict answer to how to get the click_action set in the console, you can use curl as an alternative:
curl --header "Authorization: key=<YOUR_KEY_GOES_HERE>" --header Content-Type:"application/json" https://fcm.googleapis.com/fcm/send -d "{\"to\":\"/topics/news\",\"notification\": {\"title\": \"Click Action Message\",\"text\": \"Sample message\",\"click_action\":\"OPEN_ACTIVITY_1\"}}"
This is an easy way to test click_action mapping. It requires an intent filter like the one specified in the FCM docs:
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
This also makes use of topics to set the audience. In order for this to work you will need to subscribe to a topic called "news".
FirebaseMessaging.getInstance().subscribeToTopic("news");
Even though it takes several hours to see a newly-created topic in the console, you may still send messages to it through the FCM apis.
Also, keep in mind, this will only work if the app is in the background. If it is in the foreground you will need to implement an extension of FirebaseMessagingService. In the onMessageReceived method, you will need to manually navigate to your click_action target:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//This will give you the topic string from curl request (/topics/news)
Log.d(TAG, "From: " + remoteMessage.getFrom());
//This will give you the Text property in the curl request(Sample Message):
Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
//This is where you get your click_action
Log.d(TAG, "Notification Click Action: " + remoteMessage.getNotification().getClickAction());
//put code here to navigate based on click_action
}
As I said, at this time I cannot find a way to access notification payload properties through the console, but I thought this work around might be helpful.
This falls into workaround category, containing some extra information too:
Since the notifications are handled differently depending on the state of the app (foreground/background/not launched) I've seen the best way to implement a helper class where the selected activity is launched based on the custom data sent in the notification message.
- when the app is on foreground use the helper class in onMessageReceived
- when the app is on background use the helper class for handling the intent in main activity's onNewIntent (check for specific custom data)
- when the app is not running use the helper class for handling the intent in main activity's onCreate (call getIntent for the intent).
This way you do not need the click_action or intent filter specific to it. Also you write the code just once and can reasonably easily start any activity.
So the minimum custom data would look something like this:
Key: run_activity
Value: com.mypackage.myactivity
And the code for handling it:
if (intent.hasExtra("run_activity")) {
handleFirebaseNotificationIntent(intent);
}
private void handleFirebaseNotificationIntent(Intent intent){
String className = intent.getStringExtra("run_activity");
startSelectedActivity(className, intent.getExtras());
}
private void startSelectedActivity(String className, Bundle extras){
Class cls;
try {
cls = Class.forName(className);
}catch(ClassNotFoundException e){
...
}
Intent i = new Intent(context, cls);
if (i != null) {
i.putExtras(extras);
this.startActivity(i);
}
}
That is the code for the last two cases, startSelectedActivity would be called also from onMessageReceived (first case).
The limitation is that all the data in the intent extras are strings, so you may need to handle that somehow in the activity itself. Also, this is simplified, you probably don't what to change the Activity/View on an app that is on the foreground without warning your user.
If your app is in background, Firebase will not trigger onMessageReceived(). Why.....? I have no idea. In this situation, I do not see any point in implementing FirebaseMessagingService.
According to docs, if you want to process background message arrival, you have to send 'click_action' with your message. But it is not possible if you send message from Firebase console, only via Firebase API. It means you will have to build your own "console" in order to enable marketing people to use it. So, this makes Firebase console also quite useless!
There is really good, promising, idea behind this new tool, but executed badly.
I suppose we will have to wait for new versions and improvements/fixes!
You can handle all your actions in function of your message in onMessageReceived() in your service extending FirebaseMessagingService. In order to do that, you must send a message containing exclusively data, using for example Advanced REST client in Chrome. Then you send a POST to https://fcm.googleapis.com/fcm/send using in "Raw headers":
Content-Type: application/json Authorization: key=YOUR_PERSONAL_FIREBASE_WEB_API_KEY
And a json message in the field "Raw payload".
Warning, if there is the field "notification" in your json, your message will never be received when app in background in onMessageReceived(), even if there is a data field ! For example, doing that, message work just if app in foreground:
{
"condition": " 'Symulti' in topics || 'SymultiLite' in topics",
"priority" : "normal",
"time_to_live" : 0,
"notification" : {
"body" : "new Symulti update !",
"title" : "new Symulti update !",
"icon" : "ic_notif_symulti"
},
"data" : {
"id" : 1,
"text" : "new Symulti update !"
}
}
In order to receive your message in all cases in onMessageReceived(), simply remove the "notification" field from your json !
Example:
{
"condition": " 'Symulti' in topics || 'SymultiLite' in topics",
"priority" : "normal",
"time_to_live" : 0,,
"data" : {
"id" : 1,
"text" : "new Symulti update !",
"link" : "href://www.symulti.com"
}
}
and in your FirebaseMessagingService :
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String message = "";
obj = remoteMessage.getData().get("text");
if (obj != null) {
try {
message = obj.toString();
} catch (Exception e) {
message = "";
e.printStackTrace();
}
}
String link = "";
obj = remoteMessage.getData().get("link");
if (obj != null) {
try {
link = (String) obj;
} catch (Exception e) {
link = "";
e.printStackTrace();
}
}
Intent intent;
PendingIntent pendingIntent;
if (link.equals("")) { // Simply run your activity
intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
} else { // open a link
String url = "";
if (!link.equals("")) {
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(link));
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
}
pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = null;
try {
notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notif_symulti) // don't need to pass icon with your message if it's already in your app !
.setContentTitle(URLDecoder.decode(getString(R.string.app_name), "UTF-8"))
.setContentText(URLDecoder.decode(message, "UTF-8"))
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (notificationBuilder != null) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notificationBuilder.build());
} else {
Log.d(TAG, "error NotificationManager");
}
}
}
}
Enjoy !