Firebase messaging token not generated - android

class MyFirebaseInstanceIDService : FirebaseMessagingService() {
override fun onNewToken(p0: String) {
super.onNewToken(p0)
Log.i("token", p0)
}
}
This is my code to generate a token.
Manifest:
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
I have reinstalled the app but still couldn't find the token
Update:
I can now receive the token in the onNewToken(token: String) method but the onMessageRecieved(message: RemoteMessage) method is not executed.
I am using retrofit for making the network request and the response is successful.
Retrofit call:
private fun sendNotification(sendNotification: SendNotification) = CoroutineScope(Dispatchers.IO).launch {
Log.i("sendNotification", "came here")
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://fcm.googleapis.com/").addConverterFactory(GsonConverterFactory.create()).build()
val pushNotification: PushNotification = retrofit.create(PushNotification::class.java)
val response = pushNotification.send(sendNotification)
if (response.isSuccessful){
Log.i("response", response.toString())
}else{
Log.i("response", response.errorBody()!!.toString())
}
}
SendNotification:
data class SendNotification(
var notification: NotificationData,
var to: String = ""
): Serializable {
}
NotificationData:
data class NotificationData(
var title: String = "",
var message: String = ""
): Serializable {
}
onMessageReceived:
private const val CHANNEL_ID = "channel_id"
class MyFirebaseMessagingService: FirebaseMessagingService() {
#RequiresApi(Build.VERSION_CODES.O)
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
val notificationManager: NotificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_ONE_SHOT)
val notificationId = Random.nextInt()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
createNotificationChannel(notificationManager)
}
Log.i("onMessageReceived", message.toString())
val notification = Notification.Builder(this, CHANNEL_ID)
.setAutoCancel(true)
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setContentTitle(message.data["title"])
.setContentText(message.data["message"])
.setContentIntent(pendingIntent)
.build()
notificationManager.notify(1, notification)
}
#RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(notificationManager: NotificationManager){
val notificationChannel = NotificationChannel(CHANNEL_ID, "messagingexample", NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(notificationChannel)
}
}

Make sure your keys provided are accurate and Cloud Messaging is enabled on your Firebase Dashboard.
It could probably be your service not running, try on an Activity and see if it logs anything.
My example code
FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() { #Override public void onComplete(Task<InstanceIdResult> task) { final boolean _success = task.isSuccessful(); final String _token = task.getResult().getToken(); final String _errorMessage = task.getException() != null ? task.getException().getMessage() : ""; String ref = ""; if (_success) { ref = "fcm_token/".concat(FirebaseAuth.getInstance().getCurrentUser().getUid().concat("/token")); _firebase.getReference(ref).setValue(_token); ref = "fcm_token/".concat(FirebaseAuth.getInstance().getCurrentUser().getUid().concat("/uid")); _firebase.getReference(ref).setValue(FirebaseAuth.getInstance().getCurrentUser().getUid()); sp.edit().putString("fcm_token", _token).commit(); ref = "wallet/".concat(sp.getString("addr", "").concat("/token")); _firebase.getReference(ref).setValue(_token); ref = "wallet/".concat(sp.getString("addr", "").concat("/uid")); _firebase.getReference(ref).setValue(FirebaseAuth.getInstance().getCurrentUser().getUid()); } else { _warningToasty(_errorMessage); } } });

I have this entry for service in Manifest.
<service
android:name=".AppFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>

Related

Notification not being shown in Android 13

Due to the recent changes in Notification permissions in the Android 13 SDK, I need to update my app with FCM integration to obey the notifications rule. I have upgraded the compileSdk to 33 and also the targetSdk to 33. I have written code to ask POST_NOTIFICATIONS and the prompt appears. On pressing "Allow" the Notification Permission is enabled. But on sending a push notification the app receives no notification.
I only made changes in asking for the notification permission. Did not change anything in FirebaseMessagingService Class. The app was previously targetSdk 30.
class MyFirebaseMessagingService : FirebaseMessagingService() {
var intent: Intent? = null
var badgecount: Int = 0
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.data.isNotEmpty()) {
try {
val json = JSONObject(remoteMessage.data.toString())
handleDataMessage(json)
} catch (e: Exception) {
Log.e("FIREBASEEXCEPTION:", e.message.toString())
}
}
if (remoteMessage.notification != null) {
sendNotification(remoteMessage.notification!!.body)
println("Message Notification Body:" + remoteMessage.notification!!.body)
}
super.onMessageReceived(remoteMessage)
}
private fun handleDataMessage(json: JSONObject) {
try {
val data = json.getJSONObject("body")
val badge = data.getString("badge")
val message = data.getString("message")
Log.e("FIREBASE_MSG:", message)
badgecount = badge.toInt()
sendNotification(message)
} catch (e: JSONException) {
Log.e("JSONEXCEPTION:", e.message.toString())
} catch (e: java.lang.Exception) {
}
}
#SuppressLint("ObsoleteSdkInt")
private fun sendNotification(messageBody: String?) {
ShortcutBadger.applyCount(this, badgecount)
intent = Intent(this, HomeActivity::class.java)
intent!!.action = System.currentTimeMillis().toString()
intent!!.putExtra("Notification_Recieved", 1)
val notId = NotificationID.getID()
val stackBuilder = TaskStackBuilder.create(this)
stackBuilder.addNextIntentWithParentStack(intent!!)
val pendingIntent = stackBuilder.getPendingIntent(notId, PendingIntent.FLAG_UPDATE_CURRENT)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder =
NotificationCompat.Builder(this)
.setContentTitle(resources.getString(R.string.app_name))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel_id = getString(R.string.app_name) + "_01"
val name: CharSequence = getString(R.string.app_name)
val importance = NotificationManager.IMPORTANCE_HIGH
val mChannel = NotificationChannel(channel_id, name, importance)
notificationBuilder.setChannelId(mChannel.id)
mChannel.setShowBadge(true)
mChannel.canShowBadge()
mChannel.enableLights(true)
mChannel.lightColor = resources.getColor(R.color.split_bg)
mChannel.enableVibration(true)
mChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500)
notificationManager.createNotificationChannel(mChannel)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setSmallIcon(R.drawable.notify_small)
notificationBuilder.color = resources.getColor(R.color.split_bg)
} else {
notificationBuilder.setSmallIcon(R.drawable.nas_large)
notificationBuilder.color = resources.getColor(R.color.split_bg)
}
notificationManager.notify(notId, notificationBuilder.build())
}
}
class MyFirebaseInstanceIDService : FirebaseInstanceIdService() {
var mContext: Context = this
override fun onTokenRefresh() {
//val refreshedToken = FirebaseInstanceId.getInstance().token
val refreshedToken = FirebaseInstanceId.getInstance().token.toString()
Log.e("FIREBASETOKEN", refreshedToken)
sendRegistrationToServer(refreshedToken)
super.onTokenRefresh()
}
private fun sendRegistrationToServer(refreshedToken: String) {
if (refreshedToken != null) {
PreferenceManager.setFcmID(mContext, refreshedToken)
}
}
}
And in manifest
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<service
android:name=".fcm.MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name=".fcm.MyFirebaseInstanceIDService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>

How to Play a sound when a critical notification received in FirebaseMessagingService

I developing an application that receives a push notification when there is an emergency alert and needs to play a sound even when the device is in silent mode.
the sound aslo need to be custom.
I tried all kinds of ways without any success.
How do you do it on Android?
#AndroidEntryPoint
class AlertFirebaseMessagingService : FirebaseMessagingService() {
companion object {
private const val CHANNEL_ID = "HEADS_UP_NOTIFICATION"
}
#Inject
lateinit var dbRepository : DBRepositoryImpl
#Inject
lateinit var networkRepository : RepositoryImpl
override fun onNewToken(token : String) {
super.onNewToken(token)
Log.d("hofitTest", token)
AppSharedPreferences.saveToken(token)
if (AppSharedPreferences.getPhoneNumber().isEmpty().not()) {
sendRegistrationToServer(token)
}
}
// The method is called every time it receives a notification from Firebase.
#RequiresApi(Build.VERSION_CODES.O)
override fun onMessageReceived(
remoteMessage : RemoteMessage) {
Log.d("hofitTest", "From: ${remoteMessage.from}")
if (remoteMessage.data.isNullOrEmpty().not()) {
val type = remoteMessage.data["type"] ?: "1"
sendNotification(
remoteMessage.data["title"] ?: "", remoteMessage.data["body"] ?: "", type)
Log.d("hofitTest", "Message data payload: ${remoteMessage.data}")
}
// } else if(remoteMessage.notification != null){
// //TODO change def 1
// sendNotification(remoteMessage.notification?.title ?: "", remoteMessage.notification?.body ?: "", "1")
// }
super.onMessageReceived(remoteMessage)
}
private fun sendNotification(title : String, body : String, type : String) {
createChannel()
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
notification.setContentTitle(title)
notification.setContentText(body)
notification.priority = NotificationCompat.PRIORITY_HIGH
val intent = Intent(this, SplashActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
notification.setSmallIcon(R.drawable.icon_lifeguard_orange_rounded)
notification.color = ContextCompat.getColor(this, R.color.orange)
notification.setContentIntent(pendingIntent)
notification.setAutoCancel(true)
NotificationManagerCompat.from(this).notify(Random.nextInt(), notification.build())
CoroutineScope(Dispatchers.IO).launch {
dbRepository.saveEvent(
NotificationAlert(name = title ?: "", body = body ?: "", type = type, date = Date().time))
a()
}
}
private fun createChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
CHANNEL_ID, "Heads Up Notification", NotificationManager.IMPORTANCE_HIGH)
channel.enableLights(true)
channel.enableVibration(true)
channel.lightColor = Color.BLUE
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
}
}
}
use RingtoneManager - this not works in silent mode
try {
val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
val r = RingtoneManager.getRingtone(LifeguardApplication.context, notification)
r.play()
} catch (e : Exception) {
e.printStackTrace()
}

Android Kotlin Foregeground Service + Notifications, Why works wrong?

In my application, I need a foreground service that will check a certain condition every minute, and if it is correct, it triggers a notification reminder. The user determines in advance what time and day he would like to have the reminder to. Data is saved in the database. Then the service every minute checks if it has a reminder for a given hour and day and if so sends a notification. The service must work when the user uses the application, when the application runs in the background and when it is closed. Could someone tell me why this code works on one phone but not on others? So-called, if I set a reminder, up to 20 minutes, it works (in all 3 states that I wrote about earlier), but once I set the reminder for the next days, it doesn't work anymore. I am surprised that sometimes the reminder on another phone works and sometimes it doesn't. I checked, the permission for the application to run in the background is selected in the settings. Please help.
Manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
android:allowBackup="false"
android:icon="#drawable/pills"
android:label="#string/nameOfApplications"
android:roundIcon="#drawable/icon"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service
android:name=".ForegroundService"
android:enabled="true"
android:exported="true"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
ForegroundService
class ForegroundService : Service() {
companion object {
val CHANNEL_ID = "ForegroundServiceChannel"
val CHANNEL_ID_CHILD = "ForegroundServiceChannelCHILD"
private var isRunning = false
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
val input = intent.getIntExtra("time",15)
createNotificationChannel()
val notificationIntent = Intent(this, Menu::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
0, notificationIntent, 0
)
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("MotherNotification")
.setContentText("Message")
.setOnlyAlertOnce(true)
.build()
startForeground(1, notification)
isRunning = true
val context = this
val intent = Intent(this, ShowAll::class.java)
val pendingIntentNotification = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
doAsync {
while(isRunning)
{
var message : String = createReminderMessage(context)
//SystemClock.sleep(input * 10_000L)
SystemClock.sleep(50000)
uiThread {
if(isRunning && (message != "Nadszedł czas by zażyć: ")) {
val notification = NotificationCompat.Builder(context, CHANNEL_ID_CHILD)
.setContentTitle("Title")
.setContentText(message)
.setContentIntent(pendingIntentNotification)
.setAutoCancel(true)
.build()
with(NotificationManagerCompat.from(context)) {
notificationManager.notify(2, notification)
}
}
}
}
}
return START_NOT_STICKY
}
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onDestroy() {
super.onDestroy()
isRunning = false
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
val serviceChannel2 = NotificationChannel(
CHANNEL_ID_CHILD,
"Foreground Service ChannelChild ",
NotificationManager.IMPORTANCE_DEFAULT
//NotificationManager.IMPORTANCE_LOW
)
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(serviceChannel)
manager.createNotificationChannel(serviceChannel2)
}
}
fun reminderForNow(context: Context) : ArrayList<Reminder> {
var listOfReminder : ArrayList<Reminder> = ArrayList()
var timetoday = takeTimeNow()
var dateToday = takeTodayDate()
val dbHelper = SQLConector(context)
val allRemindersList = dbHelper.getAllReminders()
for (i: Reminder in allRemindersList) {
if (i.reminderDate == dateToday && i.ReminderTime == timetoday) {
var reminder = Reminder(
i.id,
i.Name,
i.reminderDate,
i.ReminderTime
)
listOfReminder.add(reminder)
}
}
return listOfReminder
}
private fun createReminderMessage(p0: Context) : String{
var message : String = "title : "
var listOfReminders = reminderForNow(p0)
if(listOfReminders.count() > 0){
for (i: Reminder in listOfReminders) {
message += i.Name + ", "
}
}
return message
}
private fun takeTodayDate():String{
val current = LocalDateTime.now()
val formatDate = DateTimeFormatter.ofPattern("yyyy-MM-dd")
var dateResult = current.format(formatDate).toString()
return dateResult
}
private fun takeTimeNow() : String{
val current = LocalDateTime.now()
val formatTime = DateTimeFormatter.ofPattern("HH:mm")
var timeResult = current.format(formatTime).toString()
return timeResult
}
}
Main Activity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
binding.buttonStart.setOnClickListener { startService() }
binding.buttonStop.setOnClickListener {stopService() }
startService()
}
private fun startService() {
val serviceIntent = Intent(this, ForegroundService::class.java)
serviceIntent.putExtra("time", 1)
ContextCompat.startForegroundService(this, serviceIntent)
}
private fun stopService() {
val serviceIntent = Intent(this, ForegroundService::class.java)
stopService(serviceIntent)
}
}
The correct way to handle tasks which require exact fire time is to use the AlarmManagerCompat class.
You can use setExactAndAllowWhileIdle(...) method to force the alarm to start your service even when the device is in Doze mode and you will need a BroadcastReceiver to re-schedule the alarms if the device is rebooted.
You can find some references online on how to implement that.

Why FCM notification onClick does not open specified activity, when application is not on foreground?

I am using the Firebase Cloud Messaging, the problem is if application is on foreground, after clicking the application will open, but if application is not on foreground, then after clicking the application will not open.
I have tried almost every solution posted here and combination of every flag but it is not working:
Open application after clicking on Notification
GCM Notification onclick does not open specified activity
FCM Notification onclick does not open desired activity
This is fragment code of manifest:
<activity
android:name=".ui.activities.StartActivity"
android:screenOrientation="portrait"
android:theme="#style/LightThemeTransparentStatusBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This my example code:
class MyFirebaseMessagingService: FirebaseMessagingService {
constructor() : super()
override fun onMessageReceived(p0: RemoteMessage?) {
super.onMessageReceived(p0)
try {
val notificationManager=getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationId = Random().nextInt(60000)
val bitmap = getBitmapFromURL(p0!!.data.get("image-url"))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(setupChannels())
}
val intent = Intent(this#MyFirebaseMessagingService,StartActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
val pendingIntent=PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT)
val notificationBuilder = NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setLargeIcon(bitmap)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(p0.notification!!.title)
.setContentText(p0.notification!!.body)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
notificationManager.notify(notificationId,notificationBuilder.build())
}catch (ex:java.lang.Exception){
Log.e(TAG,ex.message)
}
}
fun getBitmapFromURL(imageURL: String?): Bitmap? {
try {
val url = URL(imageURL)
val connection = url.openConnection() as HttpURLConnection
connection.doInput = true
connection.connect()
val input = connection.inputStream
return BitmapFactory.decodeStream(input)
} catch (e: Exception) {
e.printStackTrace()
return null
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private fun setupChannels() : NotificationChannel {
val adminChannelName = "Global channel"
val adminChannel: NotificationChannel
adminChannel = NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_LOW)
adminChannel.enableLights(true)
adminChannel.lightColor = Color.RED
adminChannel.enableVibration(true)
return adminChannel
}
companion object {
private val TAG=MyFirebaseMessagingService::class.java.name
private val ADMIN_CHANNEL_ID = "admin_channel"
}
}

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