Open specific activity when notification clicked in background - android

There are two types of messages in FCM (Firebase Cloud Messaging):
Display Messages: These messages trigger the onMessageReceived() callback only when your app is in foreground
Data Messages:
Theses messages trigger the onMessageReceived() callback even if your app is in foreground/background/killed
When the notification is received in foreground i am able to open the specific activity on notification press but when the notification is received in background i can t handle the notification press(it launches automatically the main activity)
I did some search and found :
I added these intent-filter to my notification activity:
<activity android:name="com.mahdi.tiger.alahedclubnewtesting.activity.News_description"
android:exported="true">
<intent-filter>
<action android:name="com.mahdi.tiger.alahedclubnewtesting.activity.News_description"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</activity>
but it doesn t work..
I found also :
When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default.
So what should i do ? i want when the notification is received in background to handle the click and open my specific activity.
This is the code i am using:
public class myFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FirebaseMessageService";
Bitmap bitmap;
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
//
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
String title=remoteMessage.getNotification().getTitle();
String body=remoteMessage.getNotification().getBody();
String action=remoteMessage.getNotification().getClickAction();
sendNotification2(title,body,action);
}
//The message which i send will have keys named [message, image, AnotherActivity] and corresponding values.
//You can change as per the requirement.
String text = remoteMessage.getData().get("title");
//message will contain the Push Message
String message = remoteMessage.getData().get("message");
//imageUri will contain URL of the image to be displayed with Notification
//If the key AnotherActivity has value as True then when the user taps on notification, in the app AnotherActivity will be opened.
//If the key AnotherActivity has value as False then when the user taps on notification, in the app MainActivity will be opened.
String TrueOrFlase = remoteMessage.getData().get("AnotherActivity");
//To get a Bitmap image from the URL received
sendNotification(message, text,TrueOrFlase);
}
/**
* Create and show a simple notification containing the received FCM message.
*/
private void sendNotification(String messageBody,String text, String TrueOrFalse) {
Intent intent = new Intent(this, Slider_description.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("AnotherActivity", TrueOrFalse);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ahed_me)
.setContentTitle(text)
.setAutoCancel(true)
.setContentText(messageBody)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
NOTE: i am using Firebase console to send notification.
Thanks a lot.

After a bit of testing I found this.
https://github.com/firebase/quickstart-android/blob/master/messaging/app/src/main/java/com/google/firebase/quickstart/fcm/MyFirebaseMessagingService.java
The interesting part for you.
There are two types of messages data messages and notification
messages. Data messages are handled here in onMessageReceived whether
the app is in the foreground or background. Data messages are the type
traditionally used with GCM. Notification messages are only received
here in onMessageReceived when the app is in the foreground. When the
app is in the background an automatically generated notification is
displayed. When the user taps on the notification they are returned to
the app. Messages containing both notification and data payloads are
treated as notification messages. The Firebase console always sends
notificationmessages.
For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
If you want full control on the notification you need to send data message. You can not use the firebase console to do it from my understanding.

Related

OnMessageReceived not fired if application in background

I've been developing android apps for a while now and all of them have FCM integrated in them and functioning properly.
I have this app that the onMessageReceived isn't fired unless the app is opened, if the app is closed and I receive a notification it opens from splash and follows the normal flow (it doesn't go to the Notifications activity).
N.B: all the testing I've done was from the Firebase Console
I really don't know why, any help would be appreciated.
Here's my code:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.wtf("RECEIVED","NOTIFICATION");
// TODO(developer): Handle FCM messages here.
Log.wtf(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.wtf(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.wtf(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
sendNotification("Notification");
}
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.icon)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Using Firebase, you can send two type of notifications message basically.
1. Notification messages : sometimes thought of as "display messages."
2. Data/Payload messages : which are handled by the client app.
both above Notification has different behaviour, depending upon if your app is in foreground or background.
1.Notification msg + Background : delivered to the notification tray
2.Notification msg + Foreground : onMessageReceived() on Android
3.Data msg + Background : apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
4.Data msg + Foreground : your app receives a message object with both payloads available.
For more clarification check this.
For sending Data/payload message using FCM console use Advance option and insert key and value.

How to get data from arrived notification in android before its been shown

I want to check notification data JSON object before its been shown to user
is that possible ?? and if it is possible how to do it
thanks for the help
Firstly parse and analyze json received in fcm service class and then display notification as required.
You can use this Service if you are using FCM.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
// TODO(developer): Handle FCM messages here.
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
sendNotification("String From Data Payload");
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
remoteMessage contains the message which is received by the service. After receiving the message you can handle your data payload by using remoteData.getData() which is stored as a Map. You can use remote.getData().get("json_key") to get particular value for your json_key sent inside data payload.
After getting the data you can use the method sendNotification as follows:
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
in onMessageReceived of your fcm service check the json before passing it to notification

How to apply notification tap action to specific activity in android?

Android: How to bind Notification action to activity Dynamically in Android Manifest file?
Specially for fire-base integration.
Please give suggestion.Thank you
Recive Custom Message in Notification And According to KeyWork True Or false Or Your Specific Word go to Activity
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FirebaseMessageService";
Bitmap bitmap;
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
//
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
//The message which i send will have keys named [message, image, AnotherActivity] and corresponding values.
//You can change as per the requirement.
//message will contain the Push Message
String message = remoteMessage.getData().get("message");
//imageUri will contain URL of the image to be displayed with Notification
String imageUri = remoteMessage.getData().get("image");
//If the key AnotherActivity has value as True then when the user taps on notification, in the app AnotherActivity will be opened.
//If the key AnotherActivity has value as False then when the user taps on notification, in the app MainActivity will be opened.
String TrueOrFlase = remoteMessage.getData().get("AnotherActivity");
//To get a Bitmap image from the URL received
bitmap = getBitmapfromUrl(imageUri);
sendNotification(message, bitmap, TrueOrFlase);
}
/**
* Create and show a simple notification containing the received FCM message.
*/
private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("AnotherActivity", TrueOrFalse);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.drawable.firebase_icon)
.setContentTitle(messageBody)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
This is AnotherActivity
// If a notification message is tapped, any data accompanying the notification
// message is available in the intent extras. In this project the launcher
// intent is fired when the notification is tapped, so any accompanying data would
// be handled here. If you want a different intent fired, set the click_action
// field of the notification message to the desired intent. The launcher intent
// is used when no click_action is specified.
//
// Handle possible data accompanying notification message.
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
if (key.equals("AnotherActivity") && value.equals("True")) {
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("value", value);
startActivity(intent);
finish();
}
}
}
This is The Data
{ "data": {
"image": "https://ibin.co/2t1lLdpfS06F.png",
"message": "Firebase Push Message Using API"
"AnotherActivity": "True"
},
"to" : "f25gYF3***********************HLI"
}
To achieve the functionality of opening an activity, upon receiving of notification, that activity should be given intent-filter in manifest, to listen for an action.
In the Notification, along with the payload, the action which the activity listens for, should be sent. In the Receiver, an Intent with such an action can be fired, which opens the activity, Even if app is in backgroud or closed.

Notification Icon not visible (Gcm Push notification) when app is in background in android?

I am implementing GCM service in my android app and i am getting notification also.But we get problem when my app is closed or in background.
When app is in foreground then everything is working fine, I am getting notification with all text and icon but when my app is in background, we get notification text and title but icon is not visible. I searched about this and reached the conclusion that notification is handled by device notification tray when your app is in background.
Here is my code to receive notification:
public class GCMPushReceiverService extends GcmListenerService {
//This method will be called on every new message received
#Override
public void onMessageReceived(String from, Bundle data) {
//Getting the message from the bundle
String message = data.getString("message");
Log.d("data",data.toString());
//Displaying a notiffication with the message
String body = null;
String title = null;
try{
String data1 = data.toString();
String json = (data1.split("notification=Bundle\\[")[1]).split("\\]")[0];
body = (json.split("body\\=")[1]).split("\\,")[0];
// title = (((json.split("body\\=")[1]).split("\\,")[1]).split("title\\=")[1]).split("\\,")[0];
title = (((json.split("body\\=")[1]).split("vibrate")[0]).split("title=")[1]).split(",")[0];
Log.d("json",json);
JSONObject notificationJSON = new JSONObject(json);
//String notificationJSONString = data.getString("notification");
//then you can parse the notificationJSONString into a JSON object
// JSONObject notificationJSON = new JSONObject(notificationJSONString );
// body = notificationJSON.getString("body");
//title = notificationJSON.getString("title");
Log.d("body",body);
Log.d("title",title);
}catch (Exception e){
e.printStackTrace();
}
// sendNotification(message);
sendNotification(body, title);
}
//This method is generating a notification and displaying the notification
private void sendNotification(String message,String titles) {
Intent intent = new Intent(this, NavigationDrawerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("firsttab","notify");
int requestCode = 0;
int number = 0;
PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
// .setSmallIcon(R.mipmap.philips_launcher)
.setSmallIcon(getNotificationIcon())
.setContentTitle(titles)
.setContentText(message)
.setAutoCancel(true)
.setSound(sound)
.setNumber(++number)
.setColor(Color.parseColor("#0089C4"))
// .setStyle(inboxStyle)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setStyle(new NotificationCompat.BigTextStyle().bigText(titles))
.setContentIntent(pendingIntent);
/* if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setSmallIcon(R.drawable.icon_transperent);
} else {
builder.setSmallIcon(R.drawable.icon);
}*/
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, noBuilder.build()); //0 = ID of notification
}
private int getNotificationIcon() {
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.notification_icon : R.drawable.not_icon;
}
}
My question is how to handled notification when my app is in background? And how to show notification icon when app is in background? When I clicked on notification it open launcherActivity but I want to open some otherActivity.
Based from this thread, when app is in the background, it needs server side to make a action. The data part will automatically saved in a intent and send to the activity contains that action in the content filter. Stated in this related SO question that notification messages automatically generate notifications based on the properties passed in the "notification" object of your downstream message request, however onMessageReceived is not called in this case. Check this tutorial. When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
You can also set the priority to high when sending the message. It allows the GCM service to wake a sleeping device when possible and open a network connection to your app server.
You can check on these related links:
Push notification when app is in background
GcmListenerService is not called while application stoped. Android GCM
Android - Sending Push Notifications via GCM with app in foreground/background
Hope this helps!
It looks like you are sending a notification message, notification messages are delivered to onMessageReceived callback when the app is in the foreground like you are seeing. However when the app is in the foreground notification messages are NOT passed to onMessageReceived, the notification payload of the message is used to automatically display a notification. If there is an accompanying data payload that payload will be available in the extras of the launched intent when the user taps the notification.
If you want complete control of how messages are handled then you should use data messages, which are always delivered to the onMessageReceived callback.
See more on the different ways the two types of FCM messages are handled here.
Note:
- that if you are using the Firebase console to send the messages, it only supports notification messages at this time. Even if you add custom data, it will still be treated as a notification message on the client side.
- If you are using the REST API to send the notification message you can specify the click_action field to determine which Activity will be launched when the user clicks on the notification.
If you are using FCM, Add this in your app Manifest:
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_stat_ic_notification" />
<!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
Only then the custom color & icon will be shown in the notification when the app is in background.

Can't Expand Firebase Notifications

I've made an app using Firebase Auth and Messaging, I keep sending notifications to app through Firebase Console, the problem is I can't expand the notification if it is big. How do I do it? Help Me
public class FirebaseNots extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
/**
* Called when message is received.
*
* #param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
// TODO(developer): Handle FCM messages here.
// Not getting messages here? See why this may be:
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Image Please Take A Look
Thanks
You need add a BigTextStyle to your notification if you want it to be expandable to show multiple lines:
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle()
.bigText(messageBody));
This behavior is fixed in the next release of FCM which will be release very soon.
Keep an eye on https://firebase.google.com/support/releases for the next android release and update the version of the library in you app :)
Notifications from the Firebase console do not yet support BigStyle notifications. This is a known issue and they are working on a fix, as a workaround send your notifications using the REST API using data messages, then when the message is received generate the notification yourself like #ianhanniballake is suggesting.

Categories

Resources