Pro Android with Kotlin


Download 5.42 Mb.
Pdf ko'rish
bet129/223
Sana04.11.2023
Hajmi5.42 Mb.
#1746807
1   ...   125   126   127   128   129   130   131   132   ...   223
Bog'liq
@de android telegram Pro Android with Kotlin Developing Modern Mobile

146
CHAPTER 8: APIs
.setContentTitle("Title")
.setContentText("Content Content Content Content ...")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// add the default tap action
.setContentIntent(tapIntent)
.setAutoCancel(true)
// add a custom action button
.addAction( ... an icon resource id ...,
"Go",
actionPendingIntent)
buildChannel(NOTIFICATION_CHANNEL_ID)
val notificationManager =
NotificationManagerCompat.from(this)
notificationManager.notify(
NOTIFICATION_ID, builder.build())
The function buildChannel() is needed for Android API levels 26 and higher (Android 8.0).
It reads as follows:
fun buildChannel(channelId:String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel, but only
// on API 26+ only after that it is needed
val channel = if (Build.VERSION.SDK_INT >=
Build.VERSION_CODES.O) {
NotificationChannel(channelId,
"Channel Name",
NotificationManager.IMPORTANCE_DEFAULT)
} else {
throw RuntimeException("Internal error")
}
channel.description = "Description"
// Register the channel with the system
val notificationManager =
if (Build.VERSION.SDK_INT >=
Build.VERSION_CODES.M) {
getSystemService(
NotificationManager::class.java)
} else {
throw RuntimeException("Internal error")
}
notificationManager.
createNotificationChannel(channel)
}
}


147
CHAPTER 8: APIs
An explanation for the other code follows:

The notification itself needs a unique ID; we save that inside 
NOTIFICATION_ID.

The action button, here for sending a broadcast, is for the example only. 
Having no action button is allowed.

setAutoCancel(true) will lead to automatically dismissing the 
notification once the user taps the notification. This works only if 
setContentIntent() is used as well.

Creating the notification channel is necessary only for API level 26 or 
higher (Android 8.0). The superfluous checks inside the outer if are 
necessary to make Android Studio not complain about compatibility 
issues.

For all the strings you should use resource IDs where feasible
otherwise, use texts that better suit your needs.
Adding Direct Reply
Starting with API level 24 (Android 7.0), you can allow the user to enter text as a reply to a 
notification message. A major use case for this is of course a notification message from a 
messaging system like a chat client or e-mail. See Figure 
8-3
for an example.

Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   125   126   127   128   129   130   131   132   ...   223




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling