Why click on FCM notification in tray not launched my app? - android

My notification data message is as below:
{data=
{"sender_username":null,
"image":null,
"is_background":false,
"payload":{"post_id":"1"},
"userId":2,
"title":"ABC",
"message":"Someone liked your post!",
"timestamp":"2018-06-02 10:46:50"
}
}
This message is received when app is in foreground,it received in onMessageReceived(RemoteMessage message).I also know that my this message is only received when app in foreground.
Problem
But when the app in background or closed,the notification is appear in notification tray.The problem is when I click on the notification,it doesn't launch my app,totally no response.
Here is my code:
AndroidManifest.xml
<!-- Firebase service -->
<service
android:name=".services.FirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service
android:name=".services.FirebaseInstanceIDService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
Here is how I handle the notification:
public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
// Check for empty push message
if (TextUtils.isEmpty(message))
return;
// notification icon
final int icon = R.drawable.logo;
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext);
final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + mContext.getPackageName() + "/raw/notification");
if (!TextUtils.isEmpty(imageUrl)) {
if (!imageUrl.equalsIgnoreCase(null) && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) {
Bitmap bitmap = getBitmapFromURL(imageUrl);
if (bitmap != null) {
showBigNotification(bitmap, mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
} else {
showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
}
}
} else {
showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
playNotificationSound();
}
}
private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(inboxStyle)
.setWhen(getTimeMilliSec(timeStamp))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(AppConfig.NOTIFICATION_ID, notification);
}
My code run well before in 'com.google.firebase:firebase-messaging:10.2.4',the problem happen when I upgrade to 'com.google.firebase:firebase-messaging:17.0.0'.
After I looking at the same code again and again for past 2 days,I still cant figure out,where the problem came from.Somebody please help..
If possible,please give some hint about what is the possible issue that will cause this problem.
Thank you.

I can give a better idea if you can tell me From where you are calling this showNotification message, and where is your FirebaseMessagingService() class ?
But as far as i understand, the intent you are passing as parameter should specify which activity you want to open, something like this:
val intent = Intent(this#MyFirebaseMessagingService, MainActivity::class.java)// here i want to open the MainActivity on notification click
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this#MyFirebaseMessagingService, 0, intent, PendingIntent.FLAG_ONE_SHOT)
I will get a clear view if you can show me your class where you are extending FirebaseMessagingService() class.
Hope it helps.

Related

Target Screen not open when app is not running Firebase Notification FCM?

The problem is that When the App is running then notification is working fine (notification goes to targeted screen ) However tha app state is onPause or closwd then notification on click not open the targeted screen How i can solve it here is my code --->
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String NOTIFICATION_CHANNEL_ID = "Sesame" ;
private static final String NOTIFICATION_NAME= "Sesame";
private static int count = 0;
private static final String TAG = MyFirebaseMessagingService.class.getName();
#Override
public void onMessageReceived(RemoteMessage message) {
super.onMessageReceived(message);
Map<String, String> data = message.getData();
String title = data.get("title");
String msg = data.get("message");
String deepLink = data.get("deepLink");
String slug = data.get("slug");
sendMyNotification(title,msg,deepLink,message);
}
private void sendMyNotification(String message, String body, String deeplink, RemoteMessage remoteMessage) {
Intent intent = new Intent(this,MainActivity.class);
if (remoteMessage.getData().size() >0){
if (deeplink.equals("deepLink")){
intent = new Intent(this, TermsConditionsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Log.i(TAG, "sendMyNotification: Terms ");
}}
intent.setPackage(null);
intent.addFlags(Intent.FLAG_FROM_BACKGROUND | Intent.FLAG_RECEIVER_NO_ABORT);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT |
PendingIntent.FLAG_ONE_SHOT |
PendingIntent.FLAG_IMMUTABLE);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,NOTIFICATION_NAME, importance);
mChannel.setDescription(message);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotifyManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, NOTIFICATION_NAME);
mBuilder.setContentTitle(message)
.setContentText(body)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setColor(Color.parseColor("#FFD600"))
.setContentIntent(pendingIntent)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(NotificationCompat.PRIORITY_HIGH);
mNotifyManager.notify(count, mBuilder.build());
count++;}}
In my Manifest.xml file -->
<service android:name=".notifications.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
</service>
And Target Activity as ->
<activity android:name=".activities.TermsConditionsActivity" >
<intent-filter>
<action android:name="deepLink"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</activity>
And in my Target Activity i subscribe the topic
FirebaseMessaging.getInstance().subscribeToTopic("topic");
Please help me..
Why you activity not getting open only when app is in BG :
Reference :
Firebase onMessageReceived not called when app in background
This is working as intended, notification messages are delivered to your onMessageReceived callback only when your app is in the foreground. If your app is in the background or closed then a notification message is shown in the notification center, and any data from that message is passed to the intent that is launched as a result of the user tapping on the notification.
You can specify a click_action to indicate the intent that should be launched when the notification is tapped by the user. The main activity is used if no click_action is specified.
When the intent is launched you can use the
getIntent().getExtras();
to retrieve a Set that would include any data sent along with the notification message.
For more on notification message see docs.
2: How to get call in onMessageReceived if app in BG
Refrence : Firebase onMessageReceived not called. (read this complete answer)
Your messages, that are sent from somewhere, need to have a data payload and no notification payload, or they won't arrive consistently inside of "onMessageReceived" in your MessagingService.

Tapping android push notification sometimes does not redirect to the app

On tapping the push notifications user is usually redirected to the app, but some users do not get redirected to the app on tapping the push notifications.
For them the notification is simply dismissed and the app is not launched.
It might be a case, where these users have not opened the app for a long time, but would that affect the redirection to app behavior? I have also tried to reproduce this by forcing the device in doze mode, but I still get redirected to the app.
Can someone please help me solve this issue, where the user sometimes is not redirected to the app on tapping of the push notification.
This is my AndroidManifest.xml
<service
android:name=".screens.fcm.MyFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
and this is my FirebaseMessagingService
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent intent = new Intent(this, HomeActivity.class);
String notificationType = (remoteMessage.getData().get("notification_type") != null) ?
messageBody.getData().get("notification_type") : "";
if ((notificationType.equalsIgnoreCase("main")))
intent.putExtra("type", "main");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
RemoteMessage.Notification notification = remoteMessage.getNotification();
String notificationTitle = notification != null ? notification.getTitle() : "";
String notificationMessage = notification != null ? notification.getBody() : "";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, "")
.setSmallIcon(R.drawable.notification)
.setContentTitle(notificationTitle)
.setContentText(notificationMessage)
.setAutoCancel(true)
.setGroup(GROUP_KEY_HOME_NOTIFICATIONS)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH);
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("",
"Channel1",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

Clicking on Notification in background not open my App?

I am a newbie in android development.
I create a background service for receive pushNotification (with our own socket service, not FCM).
And now my device receive message and show notification successfully. But when I click the notification, it not return to my app.
When I click notification, show the error below:
ActivityManager: Unable to start service Intent { cmp=com.my.app/package.name.AppActivity } U=0: not found
Here is my code:
public static void setNotification(Service service, String message) {
NotificationManager manager = (NotificationManager) service.getSystemService(NOTIFICATION_SERVICE);
String appName = service.getString(R.string.app_name);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(service)
.setContentTitle(appName)
.setContentText(message)
.setContentIntent(getDefaultIntent(service))
.setWhen(System.currentTimeMillis())
.setOngoing(false)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.drawable.icon)
.setLargeIcon(BitmapFactory.decodeResource(service.getResources(), R.drawable.icon))
.setSound(alarmSound);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(1, notification);
}
private static PendingIntent getDefaultIntent(Service service) {
Intent intent = new Intent(service, AppActivity.class);
PendingIntent pendingIntent = PendingIntent.getService(service, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
return pendingIntent;
}
}
MainActivity setting in AndroidManifest.xml
<activity android:name="package.name.AppActivity" android:configChanges="orientation|screenSize" android:label="#string/app_name" android:launchMode="singleTask" android:screenOrientation="landscape" android:theme= "#android:style/Theme.NoTitleBar.Fullscreen" android:enabled="true" android:exported="true">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
Please guide me what I am missing or doing wrong in this code. Many thanks.
I pass same id in padding intent and manager.notify(0, notification);
And use PendingIntent.getActivity instead of PendingIntent.getService
it works!
I got the problem you only cancel the current notification thats why Intent is not firing the activity Change your Pending intent
from
PendingIntent.FLAG_CANCEL_CURRENT);
to
PendingIntent.FLAG_UPDATE_CURRENT
| PendingIntent.FLAG_ONE_SHOT);

Stop receiveing notification FCM when apps is remove from Task Manager

I made apps that need to get a notification though the apps are closed. I'm using fcm to get the notification. But when the apps are removed from the recent task, I stop getting a notification. I had seen other article but I still can't get the answer to my problem.
I'm using firebase:
'com.google.firebase:firebase-messaging:11.0.2'
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
Log.e(TAG," remote :" +remoteMessage.toString() );
try {
JSONObject json = new JSONObject(remoteMessage.getData());
String title = json.get("title").toString();
String message = json.get("message").toString();
createNottification(title, message);
}
catch (Exception ex){}
if(remoteMessage.getNotification() != null)
Log.d(TAG, "Message Notification Body: "+remoteMessage.getNotification().getBody());
}
private void createNottification(String title,String message)
{
Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);;
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.mipmap.pmi_launcher)
.setSound(notificationSoundURI )
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
notificationManager.notify(Config.NOTIFICATION_ID, notification);
}
}
Manifest.xml
<!-- Firebase Notifications -->
<service android:name=".services.MyFirebaseMessagingService" android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".services.MyFirebaseInstanceIDService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
first pass PendingIntent and also pass unique notification ID for generate bunch or stack of notification. also set Flags for notification Intent.so just do this in this way. Hope it helps to you and also other users.
private void sendNotification(String message,String title) {
int id = (int) System.currentTimeMillis();
Intent notificationIntent = new Intent(this, SplashActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(message)
//.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image).setSummaryText(message))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
} else {
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notificationBuilder.build());
}

Open activity when GCM notification was clicked

I'm making a gcm application, and now I can receive the notification
But when I click the notification, it just open the app.
I need to open another activity instead of Mainactivity
is there any way to do this?
final Intent intent = new Intent(context, YourActivity.class);
intent.putExtra("key", "value");
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.set...;
final NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
Please read this for detail about creating a Notification http://developer.android.com/guide/topics/ui/notifiers/notifications.html.
Depend on http://developer.android.com/guide/topics/ui/notifiers/notifications.html#NotificationResponse, there are two general situations of starting Activity from your notification – Regular activity and Special activity.
Methods below are the example of start 2 type of Activity:
Regular activity
private static final int NOTIFICATION_ID = 602;
private static final int REQUEST_CODE_START_ACTIVITY = 610;
/**
* Create and show a simple notification containing the received GCM message.
*/
private void sendNotification(String title, String message, Intent intent) {
// Create a start PendingIntent
PendingIntent resultPendingIntent = null;
ComponentName componentName = intent.getComponent();
if (componentName != null) {
// The stack builder object will contain an artificial back
// stack for the started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself) <== This comment must be wrong!
stackBuilder.addParentStack(componentName);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(intent);
resultPendingIntent = stackBuilder.getPendingIntent(REQUEST_CODE_START_ACTIVITY, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
} else {
resultPendingIntent = PendingIntent.getActivity(this, REQUEST_CODE_START_ACTIVITY, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
}
// Notification properties
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
Usage :
Intent intent = new Intent(this, SignInActivity_.class);
sendNotification(TextUtils.isEmpty(title) ? getString(R.string.app_name) : title, message, intent);
The manifest XML should look like this
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SignInActivity_"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
Special activity
private static final int NOTIFICATION_ID = 602;
private static final int REQUEST_CODE_START_ACTIVITY = 610;
/**
* Create and show a simple notification containing the received GCM message.
*/
private void sendNotification(String title, String message, Intent intent) {
// Create a start PendingIntent
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, REQUEST_CODE_START_ACTIVITY, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
// Notification properties
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
}
Note:
Because I use setDefaults(DEFAULT_ALL), the vibrate permission is require <uses-permission android:name="android.permission.VIBRATE" />
Yes, it's possible. You must set the "exported" flag of the activity in the manifest.xml to true.
Hope it helps.
Use this:
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager nm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent=new Intent(context,YourActivity.class);
PendingIntent pending=PendingIntent.getActivity(context, 0, intent, 0);
Notification notification;
if (Build.VERSION.SDK_INT < 11) {
notification = new Notification(icon, "Title", when);
notification.setLatestEventInfo(
context,
"Title",
"Text",
pending);
} else {
notification = new Notification.Builder(context)
.setContentTitle("Title")
.setContentText(
"Text").setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pending).setWhen(when).setAutoCancel(true)
.build();
}
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
nm.notify(0, notification);

Categories

Resources