how to android fcm default channel in app? - android

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?

Related

FCM Notification are not showing in foreground in android

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

FirebaseMessagingService doesn't restart after device reboot or after app is killed from system tray

I am using FirebaseMessagingService to send push notifications to my Pocophone X3 NFC. However, I will send a notification token and erase the notification token from my Firestore database first when logging in and logging out happens. This is to ensure that the notification is sent to the correct user.
To do the above, I have the following code.
#AndroidEntryPoint
class MessagingService :
FirebaseMessagingService(),
FirebaseAuth.AuthStateListener {
#Inject
lateinit var notificationRepository: NotificationRepository
override fun onCreate() {
super.onCreate()
FirebaseAuth.getInstance().addAuthStateListener(this)
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
val title = remoteMessage.notification?.title
val message = remoteMessage.notification?.body
if (message != null && title != null) {
sendPushNotification(title, message)
}
}
override fun onNewToken(token: String) {
saveTokenToSharedPreferences(token)
authRepository.getUser()?.let {
val uid = it.uid
sendTokenToFirestore(uid, token)
}
}
override fun onAuthStateChanged(auth: FirebaseAuth) {
auth.currentUser?.let {
val uid = it.uid
val savedRegistrationToken =
PreferenceManager.getDefaultSharedPreferences(this)
.getString(getString(R.string.fcm_token_shared_pref_key), "")
savedRegistrationToken?.let { token -> sendTokenToFirestore(uid, token) }
}
}
private fun sendPushNotification(title: String, messageBody: String) {
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT)
val channelId = getString(R.string.general_notification_channel_id)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.mlearn_logo)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channel = NotificationChannel(
channelId,
getString(R.string.general_notification_channel_name),
NotificationManager.IMPORTANCE_DEFAULT
)
notificationManager.createNotificationChannel(channel)
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build())
}
private fun saveTokenToSharedPreferences(token: String) {
val sharedPref = PreferenceManager.getDefaultSharedPreferences(this)
with (sharedPref.edit()) {
putString(getString(R.string.fcm_token_shared_pref_key), token)
apply()
}
}
private fun sendTokenToFirestore(uid: String, token: String) {
GlobalScope.launch(Dispatchers.IO) {
notificationRepository.sendNotificationToken(uid, token)
}
}
companion object {
const val REQUEST_CODE = 0
const val NOTIFICATION_ID = 0
}
}
I also registered the service to the manifest like so.
<service
android:name=".service.MessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
The code is working fine when I install the app for the first time and if I don't do any device restarts or app killing. However, when I either
turn off my phone and turn it back on; or
kill the app from my recent apps list
the FirebaseMessagingService code will no longer run. As a result, when I do log in using a new account, the new account does not have the notification token associated with it because the service isn't running.
How do I make FirebaseMessagingService keep running even on app kills and phone turning off and turning on (i.e. restarts)? Note that the app installed is not signed yet.
add this to your service
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
also, it takes some time to receive FCM messages after restart, that doesnt mean your service isnt running. If you start receiving messages after like 5 mins of restart that means your service is working fine, it just takes some time for new tokens to register
if all else fails, check out this project's implementation of FCM, its solid, restarts automatically and saves tokens to firebase
https://github.com/yahyakhan234/PharmaGO2-master

Firebase Cloud Messaging Android using Kotlin

I am trying to send cloud messages (push notifications) from the firebase console to my app. I have seen similar questions on here but nothing worked for me.
I followed the documentation, watched the tutorial, searched online, and StackOverflow and nothing seems to work for me. MainActivity, I am getting the token and trying to use it to send a test message.
FirebaseInstanceId.getInstance().instanceId
.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "getInstanceId failed", task.exception)
return#OnCompleteListener
}
// Get new Instance ID token
val token = task.result?.token
// Log and toast
val msg = getString(R.string.msg_token_fmt, token)
Log.d(TAG, msg)
})
MyFirebaseMessagingService similar to the code from the documenttaion
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun 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]
Log.e(TAG, "From: ${remoteMessage.from}")
// Check if message contains a data payload.
if (remoteMessage.data.isNotEmpty()) {
Log.d(TAG, "Message data payload: ${remoteMessage.data}")
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.
remoteMessage.notification?.let {
Log.d(TAG, "Message Notification Body: ${it.body}")
sendNotification(it.body.toString())
}
// 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]
// [START on_new_token]
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
override fun onNewToken(token: String) {
Log.d(TAG, "Refreshed token: $token")
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(token)
}
// [END on_new_token]
/**
* Schedule async work using WorkManager.
*/
private fun scheduleJob() {
// [START dispatch_job]
val work = OneTimeWorkRequest.Builder(MyWorkerActivity::class.java).build()
WorkManager.getInstance().beginWith(work).enqueue()
// [END dispatch_job]
}
/**
* Handle time allotted to BroadcastReceivers.
*/
private fun handleNow() {
Log.d(TAG, "Short lived task is done.")
}
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* #param token The new token.
*/
private fun sendRegistrationToServer(token: String?) {
// TODO: Implement this method to send token to your app server.
Log.d(TAG, "sendRegistrationTokenToServer($token)")
}
/**
* Create and show a simple notification containing the received FCM message.
*
* #param messageBody FCM message body received.
*/
private fun sendNotification(messageBody: String) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT)
val channelId = getString(R.string.default_notification_channel_id)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_sample_notification)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.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 channel = NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
}
companion object {
private const val TAG = "MyFirebaseMsgService"
}
}
And inside my AndroidManifest file I have this
<!-- [START firebase_service] -->
<service
android:name=".ui.services.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_service] -->
I saw a similar question that had an answer to downgrading the firebase messaging dependency, I also tried that with no luck. I will post more If I have to. Any help will be much appreciated, thanks.
First just make sure that testing notification works,inside onNewToken place just log the token and try to send it manually, make sure that your software accept/receive notification while on background.( open up Settings and go to Apps & Notifications. Within that screen, tap on See all X apps (where X is the number of apps you have installed) then select yours and make sure that "background activity" is on.
Try this out also,It works for me.I hope it could help
dependency : implementation 'com.google.firebase:firebase-messaging:20.2.0'
class MyFirebaseMessagingService : FirebaseMessagingService() {
val TAG = "FirebaseMessagingService"
#SuppressLint("LongLogTag")
override fun onMessageReceived(remoteMessage: RemoteMessage) {
Log.d(TAG, "msg received: ${remoteMessage.from}")
if (remoteMessage.notification != null) {
showNotification(remoteMessage.notification?.title, remoteMessage.notification?.body)
}
}
override fun onNewToken(token: String) {
Log.d("TAG", "Refreshed token: $token")
}
private fun showNotification(title: String?, body: String?) {
val intent = Intent(this, MainActivity::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())
}
}
Turns out I had to retype my Service in order for it to work. I have to remember not to copy and paste any more. Going to leave it here for anybody who faces this problem in the future. Happy coding!
class FCMService : FirebaseMessagingService() {
val TAG = "FCMService"
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
Log.d(TAG,"From: ${remoteMessage.from}")
if (remoteMessage.data.isNotEmpty()) {
Log.d(TAG, "Message data payload: ${remoteMessage.data}")
if (true) {
scheduleJob()
}else {
handleNow()
}
}
remoteMessage.notification?.let {
Log.d(TAG, "Message notification body: ${it.body}")
sendNotification(it.body.toString())
}
}
private fun sendNotification(messageBody: String) {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0,
intent,
PendingIntent.FLAG_ONE_SHOT)
val channelId = getString(R.string.default_notification_channel_id)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(
this, channelId
)
.setSmallIcon(R.drawable.ic_stat_sample_notification)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(false)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0, notificationBuilder.build())
}
override fun onNewToken(token: String) {
//super.onNewToken(token)
Log.d(TAG, token)
}
private fun handleNow() {
Log.d(TAG, "Short lived task done")
}
private fun scheduleJob() {
TODO("Not yet implemented")
}
}
<service
android:name=".ui.services.FCMService"
android:enabled="false"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>

how to show heads up notification when app in background or killed?

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>

E/FirebaseInstanceId: Token retrieval failed: PHONE_REGISTRATION_ERROR in Android Kitkat and below

Edit : I forgot to tell, i already try to make a breakpoint on the onRefreshToken and make a Log in that function, but when i start the apps, none of them is running (the breakpoint doesn't start, and the Log doesnt showing in AS's console log). So IMO its pure that the service itself doesn't start.
I make a code where my apps gonna show a notification if there is a data incoming in onMessageReceived. Its can run well, no problem at all, until i try it in Android Jelly Bean.
The notification doesn't showing (i am sure the notification is sent, because the other non JellyBean device is show the notification at the same time.) and then i trying it in KitKat Device, the result is same.
I then try to debug it and no error showing in Android Studio ( I bet because the device got Chinese rom and doesn't have Google play service built in).
Later i change my method and try it in Emulator, and the E/FirebaseInstanceId: Token retrieval failed: PHONE_REGISTRATION_ERROR is showing. I already try it in emulator that have KitKat and JellyBean image installed, the result is same, the same message appear.
This is my code:
AndroidManifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.appname">
///Some activity and meta data here
<service
android:name=".fcm.MyFirebaseInstanceIdService"
android:enabled="true"
android:exported="true"
tools:ignore="ExportedService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service
android:name=".fcm.MyFirebaseMessagingService"
android:enabled="true"
android:exported="true"
tools:ignore="ExportedService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
</manifest>
MyFirebaseInstanceIdService
class MyFirebaseInstanceIdService : FirebaseInstanceIdService() {
val TAG = "PushNotifService"
lateinit var name: String
override fun onTokenRefresh() {
val token = FirebaseInstanceId.getInstance().token
}
}
MyFirebaseMessagingService
class MyFirebaseMessagingService : FirebaseMessagingService() {
private val session = SessionManagement(this)
#SuppressLint("LongLogTag")
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.data != null){
val data = remoteMessage.data
val title = data["title"]
val body = data["body"]
showNotification(title, body)
}
}
#SuppressLint("LongLogTag")
override fun onNewToken(token: String?) {
session.updateFCMToken(token)
}
fun subscribeTopic(topic: String?){
//the topic in here is a param send by other activity when the apps lunch
FirebaseMessaging.getInstance().subscribeToTopic(topic).addOnCompleteListener { task ->
if (!task.isSuccessful) {
} else {
}
}
}
//This sendMessageTrainer() is called and run from other activity
fun sendMessageTrainer(){
val contentType = "application/json"
val authorizationKey = ServerHelper.FCMServerKey
val data = "{\"to\": \"/topics/sometopic\",\"data\": {\"title\":\"Request Update\",\"body\":\"New Request.\"}}"
Fuel.post(ServerHelper.FCMServer).header("Content-Type" to contentType, "Authorization" to "key=$authorizationKey").body(data).responseJson{
_, _, result ->
result.failure {
sendMessageTrainer()
}
result.success {
}
}
}
//showNotification() is run if there is a new data/notification from onMessageReceived
private fun showNotification(title: String?, body: String?) {
val intent = Intent(this, LauncherActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
val channelName = getString(R.string.app_name)
val channelID = "default"
val alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notifyID = 1
val notification = NotificationCompat.Builder(this, channelID)
.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(alarmSound)
.setContentIntent(pendingIntent)
.build()
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
val importance = NotificationManager.IMPORTANCE_HIGH
val mChannel = NotificationChannel(channelID, channelName, importance)
val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.createNotificationChannel(mChannel)
mNotificationManager.notify(notifyID , notification)
}
Build.VERSION.SDK_INT <= Build.VERSION_CODES.N -> {
val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.notify(notifyID, notification)
}
}
}
}
Thanks and regards,
vl14b

Categories

Resources