Notifications are showing in the background but when the app is in the foreground notifications are not showing. I applied many solutions but they do not work for me. Can anyone tell me where is my mistake? thanks in advance
Here is Manifest
<service
android:exported="false"
android:name=".services.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/cute" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/design_default_color_on_primary" />
Here is My ServicesClass
const val cannelId = "notification_channel"
const val channel_name = "com.dextrologix.dham.rfms.resident.services"
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.notification != null) {
genrateNotification(
remoteMessage.notification!!.title!!,
remoteMessage.notification!!.body!!
)
}
}
#SuppressLint("RemoteViewLayout")
fun getRemoteView(title: String, message: String): RemoteViews {
val remteViews = RemoteViews(
"com.dextrologix.dham.rfms.resident.services",
R.layout.pushnotification_layout
)
remteViews.setTextViewText(R.id.notification_title, title)
remteViews.setTextViewText(R.id.notification_message, message)
remteViews.setImageViewResource(R.id.notification_image, R.drawable.cute)
return remteViews
}
fun genrateNotification(title: String, message: String) {
var intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
var builder: NotificationCompat.Builder =
NotificationCompat.Builder(applicationContext, cannelId)
.setSmallIcon(R.drawable.person_icon)
.setAutoCancel(true)
.setVibrate(longArrayOf(1000, 1000, 1000, 1000))
.setOnlyAlertOnce(true)
.setContentIntent(pendingIntent)
builder = builder.setContent(getRemoteView(title, message))
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel =
NotificationChannel(cannelId, channel_name, NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(notificationChannel)
}
notificationManager.notify(0, builder.build())
}
}
It seems like you are missing notification channel. They are required for android notifications.
docs link
Related
Once I saw this error, I googled enough and realized it was a manifest meta data problem, so I asked the question after fixing it and doing a lot of work.
ex) manifest
default_notification_channel -> default_notification_channel_id
my log cat
2021-08-15 14:03:05.326 26315-27157/com.project W/FirebaseMessaging: Notification Channel requested (fcm_default_channel) has not been created by the app. Manifest configuration, or default, value will be used.
2021-08-15 14:03:05.327 26315-27157/com.project W/FirebaseMessaging: Notification Channel set in AndroidManifest.xml has not been created by the app. Default value will be used.
my manifest
<service
android:name=".ui.fcm.MyFirebaseMessagingService"
android:stopWithTask="false"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
and my fcm service class
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
Timber.d("Refreshed token: $token")
//TODO : Token save
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Timber.d("MyFirebaseMessagingService onMessageReceived 성공!!!!")
if (remoteMessage.notification != null) {
Timber.d("MyFirebaseMessagingService noti.body = ${remoteMessage.notification?.body}")
sendNotification(remoteMessage)
}
if (remoteMessage.data.isEmpty()) {
return
}
super.onMessageReceived(remoteMessage)
}
private fun sendNotification(remoteMessage: RemoteMessage) {
val uniId: Int = (System.currentTimeMillis() / 7).toInt()
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent =
PendingIntent.getActivity(this, uniId, intent, PendingIntent.FLAG_ONE_SHOT)
val channelId = getString(R.string.default_notification_channel_id)
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.data["body"].toString())
.setContentText(remoteMessage.data["title"].toString())
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel =
NotificationChannel(channelId, "Notice", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(uniId, notificationBuilder.build())
}
}
I'm asking this question because fcm doesn't work properly while I'm working on saving data to room. The push message is coming, but the data is not logged and I am not sure if the correct data is coming because such an error is coming out.
I haven't been able to solve this problem, can you help me yet?
fcm/send
{
"registration_ids": ["futj4oisZk5rvmU3mlX9Sq:APA91bGECOqPhLS95XOraN4NOhAuT9WAZ18vXM5dYtf8nSY-EUkgomTghFVvAaqL46q_-T6NMIMXQzegRlo3majiJDyntRS0qWmzihP-vZJ4RdJqBPqIeDueI3NxxxhUKItGJymVbjazv"],
"notification": {
"body": "VI VỆ SINH",
"title": "Thanh Toán",
"badge": "1",
"idata": "hello",
"sound": "sound.mp3",
"android_channel_id": "Skycic",
"click_action": "NotificationNavActivity"
},
"data": {
"solution": "dms",
"menu": "dealer",
"id": "ODLA8300002"
}
}
In my way, I have activity for intent-filter and FirebaseMessagingService
<activity android:name=".main.activity.NotificationNavActivity">
<intent-filter>
<action android:name="NotificationNavActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
private fun sendNotification(messageBody: RemoteMessage.Notification, solution: String, menu: String, id: String) {
val intent = Intent(this, NotificationNavActivity::class.java)
intent.putExtra("solution", solution)
intent.putExtra("menu", menu)
intent.putExtra("id", id)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT)
val channelId = resources.getString(R.string.default_notification_channel_id)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.icon_app)
.setStyle(NotificationCompat.BigTextStyle().bigText(messageBody.body))
.setContentTitle(messageBody.title)
.setContentText(messageBody.body?.trim())
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val audioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
val channel = NotificationChannel(channelId,
resources.getString(R.string.default_notification_channel_id),
NotificationManager.IMPORTANCE_DEFAULT)
channel.setSound(soundUri, audioAttributes)
channel.enableVibration(true)
channel.vibrationPattern = longArrayOf(1000, 1000, 1000, 1000, 1000)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
playNotificationSound()
}
NotificationNavActivity
class NotificationNavActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_notification_nav)
val solution = intent?.getStringExtra("solution") ?: ""
val menu = intent?.getStringExtra("menu") ?: ""
val id = intent?.getStringExtra("id") ?: ""
val notificationData = NotificationFBData(
solution = solution,
menu = menu,
id = id
)
val intent = Intent(this, MainActivity::class.java)
intent.putExtra(Constants.NOTIFICATION_FB, notificationData)
startActivity(intent)
finish()
}
}
Well, In my NotificationNavActivity, I will redirect to screens I want but I worry when the app in the foreground it will have many instances of NotificationNavActivity and others after each click notification.
Is there any other better way?
I'm using FCM for notification in android. When My app is in foreground, heads up notification is working well. But when I push message to my app in background or killed, heads up notification don't show up. I want to see heads up notification when my app is in background or killed. I tried my node adding this code android:{ priority: 'high' } But not working. How to show heads up notication?
node js
app.post('/api/push',upload.single(),(req,res)=>{
let pushMsg = req.body.pushMsg;
let groupName = req.body.groupName;
var condition = "'"+groupName+"' in topics";
var message = {
android:{
priority: 'high'
},
notification: {
title: 'Updated',
body: pushMsg
},
condition: condition
};
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
})
FirebaseCode in android
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.drawable.haiilogo)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
//.setContentIntent(pendingIntent)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.haii))
.setColor(resources.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 ="ScheduleChannel"
val channel = NotificationChannel(channelId,channelName,NotificationManager.IMPORTANCE_DEFAULT)
channel.enableLights(true)
channel.lightColor= 0x00FFFF
channel.setShowBadge(false)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0,notificationBuilder.build())
}
}
Manifest
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/>
<application>...
<service android:name=".firebase.FirebaseMessagingService"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
Ok, guys, idk why but notifications is not showing, on phone with API 29. On Api 21 for example everything is ok. Yes, I tried to read other posts on SO and found there nothing usefull, tried all advices from those posts too.
Min sdk 24, max sdk - 29 in gradle
receiver in manifest:
<receiver android:name=".ui.more_content.receivers.RemindersReceiver">
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED"/>
<action android:name="android.intent.action.PACKAGE_REMOVED"/>
<data android:scheme="package"/>
</intent-filter>
</receiver>
Receiver class:
class RemindersReceiver: BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
// Идентификатор уведомления
if(p1?.action.equals("android.intent.action.PACKAGE_ADDED")||p1?.action.equals("android.intent.action.PACKAGE_REMOVED")
||p1?.action.equals("android.intent.action.PACKAGE_UPDATED")) {
showNotificationWith("qwqwdqwqs", p0)
}
}
private fun showNotificationWith(message: String, context: Context?) {
val channelId = "com.example.notif.channelId"
val channelName = "App status"
val contentTitle = "Title"
val notificationManager =
context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val activityIntent = Intent()
val contentIntent: PendingIntent = PendingIntent.getActivity(
context,
0, activityIntent, PendingIntent.FLAG_CANCEL_CURRENT
)
val largeIcon: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.info)
val notificationBuilder = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.info)
.setContentTitle(contentTitle)
.setContentText("asdasdasdasdas")
.setStyle(
NotificationCompat.BigTextStyle()
.bigText(context.getString(R.string.long_dummy_text))
.setBigContentTitle("Big content title")
.setSummaryText("Summary is this Text")
)
.setLargeIcon(largeIcon)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setColor(Color.RED)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_HIGH
val notificationChannel = NotificationChannel(channelId, channelName, importance)
notificationBuilder.setChannelId(channelName)
notificationManager.createNotificationChannel(notificationChannel)
notificationManager.notify(
message.hashCode(), notificationBuilder
.setContentIntent(contentIntent).setAutoCancel(true).build()
)
} else {
notificationManager
.notify(
message.hashCode(), notificationBuilder
.setContentIntent(contentIntent).setAutoCancel(true).build()
)
}
}
}
Appreciate any help, thx in a forward
Those broadcasts have not been delivered to manifest-registered receivers since Android 8.0.
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);