Kotlin - can't send local notification

Joined
Nov 1, 2022
Messages
2
Reaction score
0
Hello all
I would like to send a local notification in the kotlin app. The debugger doesn't build the channel and the notification.

The app has the permission to display notifications
Following is the code:

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
NotificationChannels()


setContent {
Column() {
Toolbar()
Spacer(modifier = Modifier.height(250.dp))
val service = RememberMeNotificationService(applicationContext)
Button(onClick = { service.showNotification() }) {
Text(text = stringResource(R.string.remember_me_now))
}
}
}
}

NotificationChannels.kt

class NotificationChannels: Application() {
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}

private fun createNotificationChannel() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
RememberMeNotificationService.REMEMBER_ME_CHANNEL_ID,
resources.getString(R.string.notification_channel_name),
NotificationManager.IMPORTANCE_HIGH
)
channel.description = "Test description"

val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
Toast.makeText(this, "Notification channel created", Toast.LENGTH_LONG).show();
}
}
}

RememberMeNotificationService.kt

class RememberMeNotificationService(
private val context: Context
) {
private val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

fun showNotification() {
val activityIntent = Intent(context, MainActivity::class.java)
val activityPendingIntent = PendingIntent.getActivity(
context,
1,
activityIntent,
PendingIntent.FLAG_IMMUTABLE
)

val description = R.string.new_message
val notification = NotificationCompat.Builder(context, REMEMBER_ME_CHANNEL_ID)
.setSmallIcon(R.drawable.en)
.setContentTitle(R.string.notification_title.toString())
.setContentText(description.toString())
.setContentIntent(activityPendingIntent)
.build()
notificationManager.notify(1, notification)
}



companion object {
const val REMEMBER_ME_CHANNEL_ID = "remember_me_channel"
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,790
Messages
2,569,637
Members
45,346
Latest member
EstebanCoa

Latest Threads

Top