Parameters in a function call? [KOTLIN] - android

I've spent some time now trying to get a notification with the battery temperature in it.
At the moment I have managed to make the notification appear. Only when I want to run the code below I get an error with the showNotification() part.
This error indicates:
No value passed for parameter 'context' No value passed for parameter
'intent'
But how do I know what parameters to add to showNotification()?
Anyone who can help me with this?
class MyWorker(context: Context, workerParameters: WorkerParameters) :
Worker(context, workerParameters) {
companion object {
const val CHANNEL_ID = "channel_id"
const val NOTIFICATION_ID = 1
}
override fun doWork(): Result {
Log.d("success",
"doWork: Success function called")
showNotification(HERE DO I GET THE PARAMETER MESSAGE)
return Result.success()
}
private fun showNotification(context: Context, intent: Intent) {
if (intent?.action == "android.intent.action.BATTERY_CHANGED") {
val temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) / 10.0
Toast.makeText(context, "${temp}" + "°C", Toast.LENGTH_SHORT).show()
}
val intent = Intent(applicationContext, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent = PendingIntent.getActivity(
applicationContext,
0, intent, 0
)
val notification = NotificationCompat.Builder(
applicationContext,
CHANNEL_ID
)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("New Task")
.setContentText("Subscribe on the channel")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelName = "Channel Name"
val channelDescription = "Channel Description"
val channelImportance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(CHANNEL_ID, channelName, channelImportance).apply {
description = channelDescription
}
val notificationManager = applicationContext.getSystemService(
Context.NOTIFICATION_SERVICE
) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
with(NotificationManagerCompat.from(applicationContext)) {
notify(NOTIFICATION_ID, notification.build())
}
}
}
There is the MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// simpleWork()
myWorkManager()
}
private fun myWorkManager() {
val constraints = Constraints.Builder()
.setRequiresCharging(false)
.setRequiredNetworkType(NetworkType.NOT_REQUIRED)
.setRequiresCharging(false)
.setRequiresBatteryNotLow(true)
.build()
val myRequest = PeriodicWorkRequest.Builder(
MyWorker::class.java,
15,
TimeUnit.MINUTES
).setConstraints(constraints)
.build()
WorkManager.getInstance(this)
.enqueueUniquePeriodicWork(
"my_id",
ExistingPeriodicWorkPolicy.KEEP,
myRequest
)
}
private fun simpleWork() {
val mRequest: WorkRequest = OneTimeWorkRequestBuilder<MyWorker>()
.build()
WorkManager.getInstance(this)
.enqueue(mRequest)
}
}

You can pass arguments when you create the Request for your WorkManager like this and pass the arguments.
val builder = Data.Builder()
val intent = Intent() // for example, you get your intent here
val data = workDataOf("mydata" to intent)
builder.putAll(data)
val request = OneTimeWorkRequestBuilder<YourWorker>()
.setInputData(builder.build())
.build()
and then receive arguments via
override fun doWork(): Result {
var intent: Intent? = null
intent = inputData.keyValueMap["mydata"] as Intent
if(intent != null) {
showNotification(context, intent)
}
return Result.success()
}
Do tell if that worked for you, you already have the context inside your Worker.

Related

Can we still launch a foreground service with extended Service class or we should move to workmanager?

I am getting issue regarding foreground service is that some time foreground being killed by os so should i resolve Service class issue or move to workmanager . i have completed the application and only getting a single os issue suggestion required thanks .
// this is the service class
class SmsService : Service() {
private var wakeLock: PowerManager.WakeLock? = null
private lateinit var smsScheduler : SmsScdeduler
private var isServiceStarted = false
private var notificationBuilder : NotificationCompat.Builder?=null
private var serviceScope = CoroutineScope(Dispatchers.Main)
private var notificationManager : NotificationManager?=null
fun isServiceRunning():Boolean{
return isServiceStarted }
companion object{
const val MESSAGE_ID: String ="messageId"
const val USER_ID:String ="userId"
const val DELIVERED: String ="sb.app.messageschedular.sms_schedulers.DELIVERYKEY"
const val ADD_SERVICE = "sb.spp.message_scheduler.add"
const val DELETE_SERVICE ="sb.spp.message_scheduler.delete"
const val Add_kEY ="ADD_KEY"
const val SENT ="sb.app.messageschedular.sms_schedulers.SENT"
private const val channelId = "default_notification_channel_id"
private const val NOTIFICATION_ID =1995L
}
/************* Delivery BroaddCast ENd **************/
override fun onCreate() {
super.onCreate()
smsScheduler = SmsScdeduler.getInstance(this )
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(sb.app.messageschedular.R.mipmap.ic_launcher)
.setContentTitle("Message Scheduled")
// .setContentIntent(pendingIntent)
.setAutoCancel(true)
}
#RequiresApi(Build.VERSION_CODES.O)
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
showNotification(NOTIFICATION_ID)
wakeLock =
(getSystemService(Context.POWER_SERVICE) as PowerManager).run {
newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "EndlessService::lock").apply {
acquire()
}
}
println("intent ${intent }")
isServiceStarted =true
if(intent!=null) {
val action = intent?.action
val sms = intent?.getParcelableExtra<Sms>(Add_kEY)
schedule(sms!!)
}else{
serviceScope.launch(Dispatchers.IO) {
smsScheduler.reSchedule()
}
}
return START_STICKY }
#RequiresApi(Build.VERSION_CODES.O)
private fun showNotification(messageid:Long ) {
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId, "test1", NotificationManager.IMPORTANCE_DEFAULT)
channel.description = "test otificaiton"
notificationManager?.createNotificationChannel(channel)
}
this.startForeground(messageid.toInt() ,notificationBuilder!!.build())
}
override fun onBind(intent: Intent?): IBinder? {
return LocalBinder() }
inner class LocalBinder : Binder(){
fun getService(): SmsService = this#SmsService
}
override fun onDestroy() {
super.onDestroy()
isServiceStarted =false
if( serviceScope.isActive){
println("Service Scope is cancelled ")
serviceScope.cancel() }
}
}
fun finish() {
println("service finished ")
println("Stop self")
println("Stop foreground service")
stopForeground(true )
println("service state false ")
isServiceStarted =false
stopSelf()
}
}
// calling service
fun scheduleService(sms: Sms) {
if(!mService.isServiceRunning()){
val intent = Intent(this , SmsService::class.java)
intent.action = SmsService.ADD_SERVICE
intent.putExtra(SmsService.Add_kEY, sms)
ContextCompat.startForegroundService(this.applicationContext,intent)
}
/// Permission of Service
<service android:name=".service.SmsService"
android:foregroundServiceType="dataSync"
/>

android - Tapping notifications in the foreground does not respond with Firebase Cloud Messaging

I am using Firebase Cloud Messaging to implement notifications in android app.
I'm new to android. Please help me.
Problem
When I receive a notification in the foreground state, there is unexpected movement.
Expectation: Nothing is done at the timing when the notification is received. I want to process the notification when I tap it.
Actual: BroadcastReceiver's onReceive is called at the timing when the notification is received. It doesn't respond when I tap it ("test onCreate" is not displayed in logcat).
Note: This app is entirely operated by a fragment on MainActivity.
Files
PushNotificationListenerService.kt
class PushNotificationListenerService: FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
val channelId = message.notification?.channelId.toString()
val title: String = message.notification?.title.toString()
val text: String = message.notification?.body.toString()
sendNotification(
title,
text,
channelId
)
var broadcast = Intent()
broadcast.action = "FCM_RECEIVE_FOREGROUND"
sendBroadcast(broadcast)
}
private fun sendNotification(
title: String,
text: String,
receivedChannelId: String,
) {
val intent = Intent(this, HomeFragment::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent =
PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
.apply {
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
}
val notificationBuilder = NotificationCompat.Builder(this, receivedChannelId)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_menu_logo)
.setContentIntent(pendingIntent)
.setPriority(PRIORITY_MAX)
.setCategory(CATEGORY_CALL)
.setAutoCancel(true)
.setSound(null)
.setVibrate(null)
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val uuid = UUID.randomUUID().hashCode()
notificationManager.notify(uuid, notificationBuilder.build())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(receivedChannelId)
}
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var navController: NavController
private var mReceiver: BroadcastReceiver? = null
private val mIntentFilter = IntentFilter("FCM_RECEIVE_FOREGROUND")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.d("test onCreate")
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.lifecycleOwner = this
mReceiver = (object: BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
Timber.d("test onReceive called")
if (p1 == null) { return }
}
})
setupChannels()
}
override fun onResume() {
super.onResume()
registerReceiver(mReceiver, mIntentFilter)
}
override fun onPause() {
if (mReceiver != null) {
unregisterReceiver(mReceiver)
mReceiver = null
}
super.onPause()
}
private fun setupChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val attribute = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
var uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val channel = NotificationChannel(
"channelId",
"channelName",
NotificationManager.IMPORTANCE_HIGH
).apply {
vibrationPattern = createVibrate()
lightColor = Color.BLUE
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
setSound(uri, attribute)
}
manager.createNotificationChannel(channel)
}
}
}
payload on notification from Firebase Cloud Messaging
const fcmTokenMessage: admin.messaging.TokenMessage = {
android: {
data: {},
notification: {
body: "message",
title: "title",
defaultSound: true,
channelId: "channelId",
sound: 'default',
priority: 'high',
notificationCount: fcmPushData.notificationCount
}
},
token: fcmPushData.fcmPushToken
};
Versions
build.gradle
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:4.2.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.32"
classpath "org.jetbrains.kotlin:kotlin-serialization:1.4.32"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.5"
classpath 'com.google.gms:google-services:4.3.8'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.7.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
That's all. I apologize for the inconvenience, and thank you for your cooperation.
Resolved.
The problem was that Fragment was specified as the Intent, and when Activity was specified, it worked.

Is it possible to identity notification details (or notification id) inside boardcastReceiver?

I have multiple notifications send by different receivers(vendors). I implement a reply action button to reply to messages. Currently, I store notification details locally(shared preferences). Now, the reply action button working for single receiver notifications. Is it possible to identity notification details(or notification id) inside boardcastReceiver?
Is it possible to get from here?
override fun onReceive(context: Context, intent: Intent?) {
val remoteInput: Bundle? = RemoteInput.getResultsFromIntent(intent)
val contentString = remoteInput.getCharSequence("NotificationReply").toString()
Full Code
MessagingService
class MyFirebaseMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (remoteMessage.data.isNotEmpty()) {
sendNotification(NotificationModel.from(remoteMessage.data))
}
}
private fun sendNotification(notificationModel: NotificationModel) {
val channelId = getString(R.string.default_notification_channel_id)
val intent = Intent(this, MainActivity::class.java)
val sharedPreferences: SharedPreferences = this.getSharedPreferences("yellochatspfile", Context.MODE_PRIVATE)
val editor: SharedPreferences.Editor = sharedPreferences.edit()
editor.putString("message_data", notificationModel.messageData)
editor.apply()
editor.commit()
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
PendingIntent.getBroadcast(
this,
MainActivity.REQUEST_CODE_APPROVE,
Intent(this, NotificationReceiver::class.java)
.putExtra(MainActivity.KEY_INTENT_APPROVE, MainActivity.REQUEST_CODE_APPROVE),
PendingIntent.FLAG_UPDATE_CURRENT
)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.yc_logo)
.setContentTitle(notificationModel.title)
.setContentText(notificationModel.body)
.setGroup(notificationModel.groupKey)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.yc_logo))
.setSound(defaultSoundUri)
.setPriority(2)
.setPriority(1)
.setDefaults(2)
.setContentIntent(pendingIntent)
val replyLabel = "Enter your reply here"
val remoteInput: RemoteInput = RemoteInput.Builder(MainActivity.NOTIFICATION_REPLY)
.setLabel(replyLabel)
.build()
val action: NotificationCompat.Action =
NotificationCompat.Action.Builder(android.R.mipmap.sym_def_app_icon,
"Reply", pendingIntent)
.addRemoteInput(remoteInput)
.build()
notificationBuilder.addAction(action)
var notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.cancel(MainActivity.TAG_VALIDATION, 1)
MainActivity.NOTIFICATION_ID = r.nextInt()
notificationManager.notify(MainActivity.TAG_NORMAL, MainActivity.NOTIFICATION_ID, notificationBuilder.build())
}
}
BroadcastReceiver
class NotificationReceiver : BroadcastReceiver() {
val db = Firebase.firestore
override fun onReceive(context: Context, intent: Intent?) {
val remoteInput: Bundle? = RemoteInput.getResultsFromIntent(intent)
if (remoteInput != null) {
val contentString = remoteInput.getCharSequence("NotificationReply").toString()
val sharedPreferences: SharedPreferences = context.getSharedPreferences("yellochatspfile", Context.MODE_PRIVATE)
val messageData = sharedPreferences.getString("message_data", "")
if (messageData != null && messageData != "") {
// some logics to send message
}else{
notificationProcess(sharedPreferences, false, context)
}
}else{
notificationProcess(sharedPreferences, false, context)
}
}
}
private fun notificationProcess(sharedPreferences: SharedPreferences, isSuccess: Boolean, context: Context) {
}
}
I used putExtra to share data with broadcastReceiver
MessagingService
val i = Intent(this, NotificationReceiver::class.java)
i.putExtra("MESSAGE_DATA", notificationModel.messageData)
PendingIntent.getBroadcast(
this,
MainActivity.REQUEST_CODE_APPROVE,
i,
PendingIntent.FLAG_UPDATE_CURRENT
)
BroadcastReceiver
val messageData = intent?.getStringExtra("MESSAGE_DATA")
println("messageData is : $messageData")

Notification not handling intent when click when app is closed

I have a class that extends Firebase Messaging service:
internal class The8AppGCMListenerService : FirebaseMessagingService() {
override fun onNewToken(token: String) {
super.onNewToken(token)
//save token
}
override fun onMessageReceived(message: RemoteMessage) {
val from = message.from
val data = message.data
sendNotification(data)
}
private fun sendNotification(data: Map<String, String>) {
if (Interactors.preferences.notificationsEnabled == true) {
Timber.d(data.toString())
val msg = data[KEY_MSG]
val url = data[KEY_URL]
sendNotification(msg, type, url)
}
}
private fun sendNotification(message: String?, url: String?) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelId = "Main"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(channelId, "My Notifications", NotificationManager.IMPORTANCE_HIGH)
notificationChannel.description = "Channel description"
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.vibrationPattern = longArrayOf(0, 1000, 500, 1000)
notificationChannel.enableVibration(true)
notificationManager.createNotificationChannel(notificationChannel)
}
val pendingIntent = getNotificationIntent(url)//Build intent with data received from notifcation
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
notificationBuilder.setSmallIcon(R.drawable.ic_notification)
notificationBuilder.setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.notif))
notificationBuilder.setContentTitle(getString(R.string.app_name))
notificationBuilder.setContentText(message)
notificationBuilder.setAutoCancel(true)
notificationBuilder.setSound(defaultSoundUri)
notificationBuilder.setContentIntent(pendingIntent)
notificationManager.notify(0, notificationBuilder.build())
}
private fun getNotificationIntent(Long, url: String?): PendingIntent {
val useState = UseState(UseState.COME_FROM_NOTIFICATION)
val intent = getNotificationIntent(this, type, useState, offerId, url)
return PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
companion object {
private const val KEY_MSG = "Text"
private const val KEY_URL = "pushUrl"
internal fun getNotificationIntent(context: Context, useState: UseState, url: String?): Intent =
openSponsorTree(context,useState,ASponsorTree.TAB_FEED,url)
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).apply {
if (The8CloudSdk.isSdkReady()) {
RxBus.post(SponsorHubEvents.UpdateNotifications())
SDKInternal.notifyBadgeListener()
}
}
private fun openSponsorTree(context: Context, useState: UseState, startTab: Int, url: String?): Intent {
val intent = ASponsorTree.newInstance(context, useState, startTab,url=url)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
return intent
}
}
}
I've declared it in the manifest like so:
<service android:name="com.weare8.android.network.gcm.The8AppGCMListenerService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_notification" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/app_dark_blue" />
And imported these firebase packages:
implementation('com.google.firebase:firebase-core:18.0.2')
implementation platform('com.google.firebase:firebase-bom:26.4.0')
implementation 'com.google.firebase:firebase-messaging-ktx'
implementation 'com.google.firebase:firebase-analytics-ktx'
However, when the notification is clicked when the app is in the background all it does is open the app and does not parse the data returned from message.data in onMessageReceived(). I can confirm this when I attempt to get the URL passed into the ASponsorTree activity and it is null.
How do I pass data into the app when bringing it from the background via a notification?
Edit: newInstance() method of ASponsorTree activity:
companion object {
const val KEY_URL = "pushUrl"
fun newInstance(
context: Context,
useState: UseState,
startTab: Int = TAB_FEED,
url:String?,
noPost: String? = null
): Intent {
val intent = Intent(context, ASponsorTree::class.java).putExtra(KEY_URL,url)
return intent
}
}
I retrieved it in that activity's oncreate with
val pushUrl = intent.getStringExtra(KEY_URL)
which evaluates to null.
I learned that onMessageReceived() is not called from the background unless the a data message is used, and that the receiving activity must be tagged with a click action in the manifest.

How to read Device Token to allow Cloud Messaging with Postman (Kotlin)

I'm trying to make a simple notification service sent from server via postman work, I think I set everything in the right way within the activities.
FirebaseNotificationActivity :
class FirebasePushNotificationActivity : BaseActivity<FirebasePushNotificationContract.FirebasePushNotificationView, FirebasePushNotificationContract.FirebasePushNotificationPresenter>(),
FirebasePushNotificationContract.FirebasePushNotificationView {
private val TAG = "MyFirebaseToken"
override val layoutResId: Int
get() = R.layout.activity_firebase_push_notification
override fun createPresenter(): FirebasePushNotificationContract.FirebasePushNotificationPresenter {
return FirebasePushNotificationContract.FirebasePushNotificationPresenter()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_firebase_push_notification)
initView()
}
private fun initView() {
//This method will use for fetching Token
Thread(Runnable {
try {
Log.i(TAG, FirebaseInstanceId.getInstance().getToken(getString(R.string.SENDER_ID), "FCM"))
} catch (e: IOException) {
e.printStackTrace()
}
}).start()
}
}
MyFirebaseMessagingService
class MyFirebaseMessagingService: FirebaseMessagingService() {
private val TAG = "MyFirebaseToken"
private lateinit var notificationManager: NotificationManager
private val ADMIN_CHANNEL_ID = "Android4Dev"
override fun onNewToken(token: String?) {
super.onNewToken(token)
Log.i(TAG, token)
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
super.onMessageReceived(remoteMessage)
remoteMessage?.let { message ->
Log.i(TAG, message.getData().get("message"))
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//Setting up Notification channels for android O and above
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
setupNotificationChannels()
}
val notificationId = Random().nextInt(60000)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher) //a resource for your custom small icon
.setContentTitle(message.data["title"]) //the "title" value you sent in your notification
.setContentText(message.data["message"]) //ditto
.setAutoCancel(true) //dismisses the notification on click
.setSound(defaultSoundUri)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(notificationId /* ID of notification */, notificationBuilder.build())
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
private fun setupNotificationChannels() {
val adminChannelName = getString(R.string.notifications_admin_channel_name)
val adminChannelDescription = getString(R.string.notifications_admin_channel_description)
val adminChannel: NotificationChannel
adminChannel = NotificationChannel(ADMIN_CHANNEL_ID, adminChannelName, NotificationManager.IMPORTANCE_LOW)
adminChannel.description = adminChannelDescription
adminChannel.enableLights(true)
adminChannel.lightColor = Color.RED
adminChannel.enableVibration(true)
notificationManager.createNotificationChannel(adminChannel)
}
}
The problem is that following the guide I have not well understood what to insert in the field "to :" within the definition of the notification in Postman, or rather, I understand that it is necessary to insert the token of the device but I do not know how to get it.
{
"to":
"Add your device token",
"data": {
"title": "Android4Dev",
"message": "Learn Firebase PushNotification From Android4Dev Blog"
}
}
Problem solved, I added in my main activity this :
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this#SplashActivity,
OnSuccessListener<InstanceIdResult> { instanceIdResult ->
val newToken = instanceIdResult.token
Log.e("newToken", newToken)
})

Categories

Resources