11package io.goooler.demoapp.base.core
22
33import android.app.Notification
4- import android.app.NotificationChannel
54import android.app.NotificationManager
6- import android.os.Build
75import androidx.annotation.CallSuper
86import androidx.annotation.DrawableRes
97import androidx.annotation.IntRange
8+ import androidx.core.app.NotificationChannelCompat
109import androidx.core.app.NotificationCompat
11- import androidx.core.content.getSystemService
10+ import androidx.core.app.NotificationManagerCompat
1211import androidx.lifecycle.LifecycleService
1312
1413abstract class BaseService : LifecycleService () {
@@ -19,40 +18,38 @@ abstract class BaseService : LifecycleService() {
1918 @IntRange(from = 1 )
2019 protected open val channelId: Int = 1
2120
22- protected open val contentTitle: String = " "
21+ protected open val contentTitle: String get() = applicationInfo.name
22+
23+ protected open val contentText: String? get() = null
2324
2425 protected open val channelName: String get() = getString(applicationInfo.labelRes)
2526
2627 @get:DrawableRes
2728 protected open val smallIcon: Int
2829 get() = applicationInfo.icon
2930
30- protected open val notification: Notification get() = createNormalNotification(contentTitle)
31+ protected open val notification: Notification
32+ get() = NotificationCompat .Builder (this , channelId.toString())
33+ .setContentTitle(contentTitle)
34+ .setContentText(contentText)
35+ .setWhen(System .currentTimeMillis())
36+ .setSmallIcon(smallIcon)
37+ .build()
38+
39+ protected open val channel: NotificationChannelCompat
40+ get() = NotificationChannelCompat .Builder (
41+ channelId.toString(), @Suppress(" InlinedApi" ) NotificationManager .IMPORTANCE_MIN
42+ ).setName(channelName).build()
3143
3244 @CallSuper
3345 override fun onCreate () {
3446 super .onCreate()
35- if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .O ) {
36- val channel = NotificationChannel (
37- channelId.toString(),
38- channelName,
39- NotificationManager .IMPORTANCE_MIN
40- )
41- getSystemService<NotificationManager >()?.createNotificationChannel(channel)
42- startForeground(channelId, notification)
43- }
47+ NotificationManagerCompat .from(this ).createNotificationChannel(channel)
48+ startForeground(channelId, notification)
4449 }
4550
46- protected open fun createNormalNotification (content : String? ): Notification {
47- return NotificationCompat .Builder (this , channelId.toString()).also {
48- if (content.isNullOrEmpty()) {
49- it.setNotificationSilent()
50- } else {
51- it.setContentTitle(applicationInfo.name)
52- .setContentTitle(content)
53- .setWhen(System .currentTimeMillis())
54- .setSmallIcon(smallIcon)
55- }
56- }.build()
51+ override fun onDestroy () {
52+ stopForeground(true )
53+ super .onDestroy()
5754 }
5855}
0 commit comments