1
1
package io.goooler.demoapp.base.core
2
2
3
3
import android.app.Notification
4
- import android.app.NotificationChannel
5
4
import android.app.NotificationManager
6
- import android.os.Build
7
5
import androidx.annotation.CallSuper
8
6
import androidx.annotation.DrawableRes
9
7
import androidx.annotation.IntRange
8
+ import androidx.core.app.NotificationChannelCompat
10
9
import androidx.core.app.NotificationCompat
11
- import androidx.core.content.getSystemService
10
+ import androidx.core.app.NotificationManagerCompat
12
11
import androidx.lifecycle.LifecycleService
13
12
14
13
abstract class BaseService : LifecycleService () {
@@ -19,40 +18,38 @@ abstract class BaseService : LifecycleService() {
19
18
@IntRange(from = 1 )
20
19
protected open val channelId: Int = 1
21
20
22
- protected open val contentTitle: String = " "
21
+ protected open val contentTitle: String get() = applicationInfo.name
22
+
23
+ protected open val contentText: String? get() = null
23
24
24
25
protected open val channelName: String get() = getString(applicationInfo.labelRes)
25
26
26
27
@get:DrawableRes
27
28
protected open val smallIcon: Int
28
29
get() = applicationInfo.icon
29
30
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()
31
43
32
44
@CallSuper
33
45
override fun onCreate () {
34
46
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)
44
49
}
45
50
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()
57
54
}
58
55
}
0 commit comments