Android FCM Notification Cannot Be Clicked Second Time - android

I Have problem with my notification.
First way - I open my app, then I push notification from FCM first time, I click the notif, my code executed, I push again for second time, I click my notif, my code still execute, I try more more time is worked well.
Second way - My app still close, I push notif from FCM first time, then I Click the notif, so my app will open and my code executed, then I push notif again for second time, my code NOT executed, I try more more time still NOT working.
until I swipe my app, and try again, the problem still happen.
this is my code
class MyFirebaseMessagingService : FirebaseMessagingService() {
var userInformation = AccountTableDao()
val sp: SharedPreferences by lazy { SharedPreference.instance }
val gad: GetAccountData by lazy { AccountDatabase.instance }
override fun onNewToken(token: String) {
super.onNewToken(token)
Log.d("firebase", "INSTANCE ID ===> $token")
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
remoteMessage?.let {
sendNotification(it.data)
}
}
private fun sendNotification(messageData: Map<String, String>) {
var status = messageData.get("status")
val uuid = messageData.get("uuid")
val restaurantId = messageData.get("restaurantId")
val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val titleText = messageData.get("title").toString()
val contentText = messageData.get("body").toString()
val intent = Intent(applicationContext, RestaurantMenuActivity::class.java)
intent.putExtra(Argument.NOTIF_UUID, uuid)
intent.putExtra(Argument.NOTIF_RESTAURANT_ID, restaurantId)
intent.putExtra(Argument.NOTIF_STATUS, status)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val pendingIntent = PendingIntent.getActivity(applicationContext,System.currentTimeMillis().toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val notificationChannel = NotificationChannel("appety", "appety_notification", NotificationManager.IMPORTANCE_HIGH)
notificationManager .createNotificationChannel(notificationChannel)
notificationManager.notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, "1")
.setChannelId(System.currentTimeMillis().toString())
.setContentTitle(titleText)
.setStyle(NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_check_black_24dp)
.setLargeIcon( BitmapFactory.decodeResource(applicationContext.resources, R.drawable.logo_appety))
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(ContextCompat.getColor(applicationContext, R.color.colorBonAppety))
.build())
}
else{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationManager .notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, System.currentTimeMillis().toString())
.setContentTitle(titleText)
.setStyle (NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setSmallIcon(R.drawable.ic_check_black_24dp)
.setLargeIcon( BitmapFactory.decodeResource(applicationContext.resources, R.drawable.logo_appety))
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(ContextCompat.getColor(applicationContext, R.color.colorBonAppety))
.build())
} else {
notificationManager .notify(System.currentTimeMillis().toInt(), NotificationCompat.Builder(this, "1")
.setContentTitle(titleText)
.setStyle (NotificationCompat.BigTextStyle().bigText(contentText))
.setContentText(contentText)
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.build())
}
}
}
companion object {
private val TAG = "token"
}
}
and manifest
<service
android:name=".service.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Why Pending Intent not working and how to fix that.
Sorry for my english and regard.

You should try setAutoCancel() method when creating the notification.
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder summary = new NotificationCompat.Builder(this);
summary.setAutoCancel(true);
And if you passing an intent to the notification, then use this
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);

Related

Broadcast receiver being called fine, but not showing notification

I have implemented a broadcast receiver to ask the user to restart the app if it is killed. I have confirmed that the broadcast receiver is being called fine, and it runs the below line but for some reason, I am not getting any notification.
Here is the code,
class ForegroundLocationServicesRestarter : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
if (intent != null) {
if (intent.action != ForegroundLocationService.ACTION_RESTART_LOCATION_UPDATES) {
return
}
}
val notificationChannelId = "restartDeliveryApp"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(notificationChannelId, "location_notif_chan", NotificationManager.IMPORTANCE_MAX)
val manager = context.getSystemService(LifecycleService.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(notificationChannel)
}
val fullScreenIntent = Intent(context, DeliveryManActivity::class.java)
fullScreenIntent.putExtra("RESTART_TRIGGERED", true)
val fullScreenPendingIntent = PendingIntent.getActivity(
context, 0,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT
)
NotificationCompat.Builder(context, notificationChannelId)
.setSmallIcon(R.drawable.ic_truck_red)
.setContentTitle(context.getString(R.string.restarter_title))
.setContentText(context.getString(R.string.restarter_message))
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setFullScreenIntent(fullScreenPendingIntent, true)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.build()
}
}
The notification channel is unique, the app has notification permission and also, full intent permission in the manifest. Any help is highly appreciated.
Plus there is already one service notification, does that impact this in any way?
was not pushing notifications into the system to display! Just need to do this!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(notificationChannelId, "location_notif_chan", NotificationManager.IMPORTANCE_MAX)
val manager = context.getSystemService(LifecycleService.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(notificationChannel)
}
val dmIntent = Intent(context, DeliveryManActivity::class.java)
dmIntent.putExtra("RESTART_TRIGGERED", true)
val dmPendingIntent = PendingIntent.getActivity(
context, 0, dmIntent, PendingIntent.FLAG_UPDATE_CURRENT
)
// Prepare a notification with vibration, sound and lights
val builder = NotificationCompat.Builder(context, notificationChannelId)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_truck_red)
.setContentTitle(context.getString(R.string.restarter_title))
.setContentText(context.getString(R.string.restarter_message))
.setLights(Color.RED, 1000, 1000)
.setVibrate(longArrayOf(0, 400, 250, 400))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(dmPendingIntent)
Pushy.setNotificationChannel(builder, context)
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(7, builder.build()) // same notification id to override

How to dismiss all desired notifications on Android?

I'm creating a chat app that sends and receives notifications through Firebase Cloud Functions. Let's suppose I have 2 friends, and each friend sends me 5 messages(5 notifications). When I open a chat in my chat list, I want all notifications for that chat to be dismissed and the others not.
Currently I can only dimiss 1 notification. If I get more than one notification the notificationManager.cancel(notificationId) doesn't work. I don't want to use notificationManager.cancelAll() as I just want to dismiss some notifications.
override fun onMessageReceived(remoteMessage: RemoteMessage) {
remoteMessage.notification.let { notification ->
val type = remoteMessage.data[NOTIFICATION_TYPE]
val notificationChannelId = getNotificationChannelId(type)
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val intent = Intent(this, HomeActivity::class.java)
val notificationIntent = setIntent(remoteMessage.data)
val stackBuilder: TaskStackBuilder = TaskStackBuilder.create(this)
stackBuilder.addParentStack(HomeActivity::class.java)
stackBuilder.addNextIntent(intent)
stackBuilder.addNextIntent(notificationIntent)
val pendingIntent: PendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationBuilder = NotificationCompat.Builder(this, notificationChannelId)
.setContentTitle(notification?.title ?: "")
.setContentText(notification?.body ?: "")
.setStyle(
NotificationCompat.BigTextStyle()
.bigText(notification?.body ?: "")
)
.setSmallIcon(R.drawable.ic_stat)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSound(soundUri)
.setColor(ContextCompat.getColor(applicationContext, R.color.colorNotification))
.setVibrate(vibrationPattern)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
notify(remoteMessage.data, notificationManager, notificationBuilder)
}
}
private fun notify(
data: Map<String, String>,
notificationManager: NotificationManager,
notificationBuilder: NotificationCompat.Builder
) {
when (data[NOTIFICATION_TYPE]) {
CHAT_MSG -> {
if (data[NotificationUtils.CHAT_ID] != ChatActivity.currentChat) {
notificationManager.notify(
CHAT_MSG_NOTIFICATION_ID,
notificationBuilder.build()
)
}
}
FRIEND_REQUEST -> {
notificationManager.notify(
FRIEND_REQUEST_NOTIFICATION_ID,
notificationBuilder.build()
)
}
}
}
OnStart():
fun dismissNotifications(notificationId: Int) {
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(notificationId)
}
My thoughts is:
Save all notificationIds in map where:
key is userName/userId in message.
value is List of notificationId
When you need to clear all notifications you just ask you map and clear all that notificationIds for that userName/userId

How can I set notification header when receiving push message?

I'm dev-ing notification when receiving a push message in android. So I wrote same way like this url. but I can not see the notification header box. how can I fix this code? I can see the small icon on status bar but cannot see the head up box
manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
FirebaseService
class FirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
Log.d("TAG", "Refreshed token: $token")
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d("TAG", "From: " + remoteMessage.from!!)
val messageBody = remoteMessage.notification?.body
val messageTitle = remoteMessage.notification?.title
val intent = Intent(this, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT)
val channelId ="1000"
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val inboxStyle = NotificationCompat.InboxStyle()
val notificationBuilder = NotificationCompat.Builder(this,channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setOngoing(true)
.setSound(defaultSoundUri)
//.setContentIntent(pendingIntent)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.haii))
.setColor(getResources().getColor(R.color.colorPrimary))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setStyle(inboxStyle)
.setFullScreenIntent(pendingIntent,true)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
val channelName ="Channel Name"
val channel = NotificationChannel(channelId,channelName,NotificationManager.IMPORTANCE_HIGH)
channel.enableLights(true)
channel.lightColor= 0x00FFFF
channel.setShowBadge(false)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0,notificationBuilder.build())
}
}

Notification Not Showing In Android Studio

I'm using Kotlin and Android Studio to try and push a Notification in a test app. I followed the instructions in the Android Developers site on How to create a Notification (https://developer.android.com/training/notify-user/build-notification) but I seem to be doing something wrong as my Notification is not showing anywhere. Here's my code:
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
val builder = NotificationCompat.Builder(this.context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
val mNotificationManager = message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
with(mNotificationManager) {
notify(123, builder.build())
I really don't know what I'm missing so I would be grateful for any help.
According to your code, you are not creating a Notification channel.
Notification channel is necessary from Android Oreo and above
So if you are running the app Android O and above devices without a notification channel, your notification won't show up.
Create Notification Channel
fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "all_notifications" // You should create a String resource for this instead of storing in a variable
val mChannel = NotificationChannel(
channelId,
"General Notifications",
NotificationManager.IMPORTANCE_DEFAULT
)
mChannel.description = "This is default channel used for all other notifications"
val notificationManager =
mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
}
Then create a notification using the same channelId while creating a notification.
createNotificationChannel()
val channelId = "all_notifications" // Use same Channel ID
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
val builder = NotificationCompat.Builder(this.context, channelId) // Create notification with channel Id
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
val mNotificationManager =
message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
with(mNotificationManager) {
notify(123, builder.build())
Hope it helps.
try something like
val intent = Intent(context, Profile::class.java)
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0)
val mNotificationManager =
message.context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//Don't forget this check
val channel = NotificationChannel (
channelId,
"my_notification",
NotificationManager.IMPORTANCE_HIGH
)
channel.enableLights(true)
channel.lightColor = Color.GREEN
channel.enableVibration(false)
val builder = NotificationCompat.Builder(this.context, "channel_id")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_MAX)
builder.setContentIntent(pendingIntent).setAutoCancel(true)
mNotificationManager.createNotificationChannel(channel)//Notice this
mNotificationManager.notify(123, builder.build())
}
else {
//Create Notifcation for below Oreo
}
Does your Logcat say something like:
E/NotificationManager: notifyAsUser: tag=null, id=123, user=UserHandle{0}
Also have a look at your line:
val intent = Intent(context, Profile::class.java)
IF all else fails create a test Actvity with hello world.
And then make the line look like:
val intent = Intent(context, testActivity::class.java)
Remember to add the activity to your Manifest
The following line
val pendingIntent = PendingIntent.getActivity(this.context, 0, intent, 0);
should not have a semi colon. Kotin doesn't need this.
Is Profile your Class or System Class?
Try out this method and you can pass message and title dynamically :
private fun showNotification(title: String?, body: String?) {
val intent = Intent(this, Profile::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT)
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(0, notificationBuilder.build())
}

Why my notification not work in background when my app is kill and close in android

When my app is open, notification works perfectly but when in background it doesn't work .I want the notification to be displayed even when my app is killed or closed in my phone. But it is not working. Here is my code :-
1) MyFirebaseMessagingService.kt :-
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
showNotification(remoteMessage!!)
Log.e("fcm", "HElloo Call")
}
#SuppressLint("WrongConstant")
private fun showNotification(message: RemoteMessage) {
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val i = Intent(this, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT)
val androidChannel = NotificationChannel("1",
"sdccscsc", NotificationManager.IMPORTANCE_DEFAULT)
androidChannel.enableLights(true)
androidChannel.enableVibration(true)
androidChannel.lightColor = Color.GREEN
androidChannel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val builder = NotificationCompat.Builder(this, "1")
.setAutoCancel(true)
.setContentTitle(message.data["title"])
.setContentText(message.data["message"])
.setSmallIcon(R.drawable.main_logo)
.setDefaults(Notification.DEFAULT_ALL)
.setContentIntent(pendingIntent)
manager.createNotificationChannel(androidChannel)
}
val i = Intent(this, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT)
val builder = NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentTitle(message.data["title"])
.setContentText(message.data["message"])
.setSmallIcon(R.drawable.main_logo)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(Notification.DEFAULT_ALL)
.setContentIntent(pendingIntent)
manager.notify(0, builder.build())
}
Check your logcat if you are receiving the notification. IS your notification being displayed in the system tray?
There are two types of Message types
Notification message
FCM automatically displays the message to end-user devices on behalf of the client app. Notification messages have a predefined set of user-visible keys and an optional data payload of custom key-value pairs.
Data message
Client app is responsible for processing data messages. Data messages have only custom key-value pairs.
as per my comment
You need to send notification data in Data messages
SAMPLE FORMAT
{
"message":{
"token":"your token",
"data":{
"key1" : "value1",
"key2" : "value2",
"key3" : "value4",
}
}
}
EDIT
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
Intent intent = new Intent(this, YourActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
intent.putExtra("ID",object.getString("data"));
} catch (JSONException e) {
e.printStackTrace();
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "Your_channel";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Your Notifications", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("Description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setColor(ContextCompat.getColor(this, R.color.colorDarkBlue))
.setContentTitle(getString(R.string.app_name))
.setContentText(remoteMessage.getNotification().getBody())
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_notification)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_MAX);
notificationManager.notify(1000, notificationBuilder.build());
notificationManager.cancelAll();

Categories

Resources