Android app is not receiving FCM notification when closed - android

I am checking Firebase Cloud Messaging to send notification. Have implemented it already and its receiving notification when app is in open state. But if I close app, its no longer gives notification. Is there any solution for this.
Code:
WebRequest wRequest;
wRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
wRequest.Method = "post";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));
wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));
string postData = "{\"registration_ids\":[\"" + regIds + "\"], \"data\": "+ value +"}";
Byte[] bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;
Stream stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();
WebResponse wResponse = wRequest.GetResponse();
Messaging service-
public class MessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
sendNotification(data);
}
public void showMessage(Map<String, String> serverData) {
Intent i = new Intent(this,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle(serverData.get("Title"))
.setContentText(serverData.get("Message"))
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(Integer.parseInt(serverData.get("ItemId")),builder.build());
}
private void sendNotification(Map<String, String> serverData) {
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_UPDATE_CURRENT);
long[] pattern = {500,500,500,500,500};
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle(serverData.get("Title"))
.setContentText(serverData.get("Message"))
.setAutoCancel(true)
.setVibrate(pattern)
.setLights(Color.BLUE,1,1)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Integer.parseInt(serverData.get("ItemId")), notificationBuilder.build());
}
}
Main activity-
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseMessaging.getInstance().subscribeToTopic("test");
FirebaseInstanceId.getInstance().getToken();
}
}
Manifest-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.com.firebasenotify">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".InstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
</application>
</manifest>

There was no issue with the code. I was using Mi note 4, and somehow it does not show notification in Mi4 when app is closed. I tested with other android device and its working fine.
Thanks to Tim Castelijns and Frank van Puffelen for participating in the conversation.

There's good solution and explanation about that issue here. You need to set high priority for notification to tell android react immediately, otherwise it takes couple of minutes to display received notification.

I used Legacy Server Key instead of Server Key it had worked for me.

adding time_to_live key in your POST Payload will solve this problem.The value of this parameter must be a duration from 0 to 2,419,200 seconds, and it corresponds to the maximum period of time for which FCM stores and attempts to deliver the message. "time_to_live" : 3 Refer Firebase Docs

As per FCM docs onMessageReceived() won't be called when app is in the background. You should send a notification object on order to show it up in the system tray and when user clicks it the launcher activity will be open with data as extras with the intent. For payloads you should use data object. see docs and Receive Messages in an Android App

Related

Clicking the Push Notification Firebase is not working

it's been weeks since i have this problem. i can already generate the FCM token and subscribe topics.
the problem that i am having is when i click the notification, nothing is happening it is not even going to the application and i still can't get the body and title of the notification. i know that the notification do not have a relationship with the actual application that i have, i already followed the documentation on handling the receive messages but still nothing is happening.
here is the link that i followed. https://firebase.google.com/docs/cloud-messaging/android/receive
Here is the code that i have.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
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());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use WorkManager.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(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.
}
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);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
and here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.eperformax.eplife">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyFirebaseMessagingService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
i already saw some related question here but nothing solves my problem. i just followed the documentation and still this is happening.
Can anyone help me this is really stressing me out. Any help would be really appreciated.

How to open any Activity using notification when app is not running in Background?

This is my Firbase Service code i just want to open an Another Acivity when app is closed or not running in background i done Everything but it wont work please help
private void createNotification(String messageBody, String title, RemoteMessage message)
{
Intent intent = new Intent(this,NotificationScreen.class);
intent.putExtra("type",message.getData().get("json"));
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultIntent = PendingIntent.getActivity( this ,0,intent,PendingIntent.FLAG_ONE_SHOT);
Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
.setContentTitle(title)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),R.drawable.icon))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(notificationSoundURI)
.setContentIntent(resultIntent);
mNotificationBuilder.setSmallIcon(getNotificationIcon(mNotificationBuilder));
//Log.i("data",map.values().toString());
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mNotificationBuilder.build());
}
private int getNotificationIcon(NotificationCompat.Builder notificationBuilder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int color = 0x008000;
notificationBuilder.setColor(color);
return R.drawable.icon;
}
return R.drawable.icon;
}
Already applied xml code
<activity android:name=".NotificationScreen"
>
<intent-filter>
<action android:name="NotificationScreen" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Please help unable to understand ..
For Android, you could simply set the value of click_action parameter in your notification payload equal to the intent filter of the corresponding activity that you want to open. As mentioned in the docs (emphasis mine):
The action associated with a user click on the notification.
If specified, an activity with a matching intent filter is launched when a user clicks on the notification.
So for example you have this payload:
{
"to": <TOKEN>,
"notification": {
...
"click_action" : "OPEN_ME"
...
}
}
Then you have an Activity in your manifest that has the corresponding intent-filter name (similar to your post):
<activity android:name=".NotificationScreen">
<intent-filter>
<action android:name="OPEN_ME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
It should open that specific activity.

Open activity after FCM notification click in Android

I know there are multiple posts like this, but I have tried many solutions and nothing works for me.
I am using a Firebase Cloud Messaging to send notifications. The notification arrives, but it opens the main activity, not the one that I want.
I try and try, but keep failing with starting appropriate activity. Tried different Intent or PendingIntent settings, tried click_action, nothing works for me.
I think that it is not even entering my FirebaseMessagingService, but I did everything like in the Firebase instruction.
manifest:
<service
android:name="com.packagename.FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity android:name="com.packagename.NotificationActivity">
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</activity>
FirebaseMessagingService:
public class FirebaseMessagingService extends FirebaseMessagingService {
private static String TAG = "Firebase";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
}
if(remoteMessage.getNotification()!=null){
Log.d(TAG,"Message body : "+remoteMessage.getNotification().getBody());
sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle());
}
}
private void sendNotification(String body, String title) {
Intent notificationIntent = new Intent(this, NotificationActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("notification", body);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notification =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification)
.setContentTitle(getString(R.string.app_name))
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(body)
.setBigContentTitle(title))
.setContentText(body)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_SOUND);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,notification.build());
}
}
Logs after click:
D/StatusBar: Clicked on content of 0|com.mypackagename|0|GCM-Notification:89893881|10177 , PendingIntent{cc15013: android.os.BinderProxy#e3031fc} , Intent { act=com.google.firebase.MESSAGING_EVENT cmp=com.mypackagename/com.google.firebase.iid.FirebaseInstanceIdInternalReceiver (has extras) }
If app in background, notifications directs to the system tray.
After click notification it will redirect to launcher activity which is given in manifest file.
From launcher activity we can call any activity but first it will goto launcher activity.
In Launcher activity we can get notification message contents .
AndroidManifest.xml
<activity
android:name=".view.SplashActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
SplashActivity.Java
public class SplashActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Bundle bundle = getIntent().getExtras();
if (bundle != null && bundle.get("data")!=null) {
//here can get notification message
String datas = bundle.get("data").toString();
}
}
}

Firebase push notifiaction not working when app is closed on some devices

I'm trying to send push notification from my app server to my app using Google cloud Messaging the app working well on Android Emulator but some devices not getting notification
here is FCMMessagingService.java
public class FCMMessagingService extends FirebaseMessagingService {
String title;String message;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if(remoteMessage.getNotification() != null){
title = remoteMessage.getNotification().getTitle();
message = remoteMessage.getNotification().getBody();
Log.d("Message body", remoteMessage.getNotification().getBody().toString());
}
Map<String, String> data = remoteMessage.getData();
title = data.get("company");
message = data.get("message");
Log.d("Message body", remoteMessage.getData().toString());
Intent intent = new Intent(this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(title);
builder.setContentText(message);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setAutoCancel(true);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
super.onMessageReceived(remoteMessage);
}
}
here is Manifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FcmInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"></action>
</intent-filter>
</service>
<service
android:name=".FCMMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</application>
If you getting the notification when your app is in foreground the it's ok you just use a data payload instead of notification payload you can use both together but data payload works when app in background or even close. I recommend you for only use the data payload because it's work 100% time. One of my app didn't get notification when app is closed but I used both payload then I just changed it to only data payload and it worked fine.

Android CGM start Activity after receiving Push Notification

After a Push Notification is received, I want to open an Àctivity when the Notification is pressed.
Here are my Services:
public class GCMIntentService extends GcmListenerService {
#Override
public void onMessageReceived(String from, Bundle data) {
String title = data.getString("title");
String message = data.getString("message");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setTicker(message)
.setAutoCancel(true);
mBuilder.setDefaults(Notification.DEFAULT_LIGHTS);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
Intent myIntent = new Intent(this, MyActivity.class);
PendingIntent intent2 = PendingIntent.getBroadcast(this, 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(intent2);
notificationManager.notify(1, mBuilder.build());
}
public class GCMIDListenerService extends InstanceIDListenerService {
#Override
public void onTokenRefresh() {
InstanceID instanceID = InstanceID.getInstance(this);
String token;
try {
token = instanceID.getToken(Resources.getSystem().getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
} catch (IOException e) {
e.printStackTrace();
}
//TODO:send token to the server
}
}
I just did everything following the Google documentation. I implemented that feature for another project sometime ago but it was a bit different, I used my own 'BroadcastReceiver' instead of the 'com.google.android.gms.gcm.GcmReceiver' provides by Google.
Here is my Manifest:
<application>
...
<!-- GCM Push Notifications Config -->
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="gcm" />
</intent-filter>
</receiver>
<service
android:name=".push.GCMIntentService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name=".push.GCMIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
</application>
Any ideas? Am I missing something?
Here some documentation I have follow:
Google official documentation
CGM tutorial By Dustin Rothwell
And of course I have researched a lot here at stackoverflow.
Thanks!
You have done one minor mistake. You are writing this code for opening activity.
PendingIntent intent2 = PendingIntent.getBroadcast(this, 1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(intent2);
As you want to open activity you need to create pending intent using getActivity method instead of getBroadcast method.
Hope this will help.

Categories

Resources