ForegroundService.kt raw
1 package io.github.domi04151309.alwayson.services
2
3 import android.app.NotificationChannel
4 import android.app.NotificationManager
5 import android.app.Service
6 import android.content.ComponentName
7 import android.content.Intent
8 import android.content.IntentFilter
9 import android.os.Build
10 import android.os.IBinder
11 import android.service.quicksettings.TileService
12 import androidx.core.app.NotificationCompat
13 import io.github.domi04151309.alwayson.R
14 import io.github.domi04151309.alwayson.receivers.CombinedServiceReceiver
15
16 class ForegroundService : Service() {
17 private val combinedServiceReceiver = CombinedServiceReceiver()
18
19 override fun onCreate() {
20 super.onCreate()
21 CombinedServiceReceiver.compat = packageManager.getInstallerPackageName(packageName)
22 ?.hashCode()
23 ?: 0
24 CombinedServiceReceiver.helper = packageName.hashCode()
25 val filter = IntentFilter()
26 filter.addAction(Intent.ACTION_POWER_CONNECTED)
27 filter.addAction(Intent.ACTION_POWER_DISCONNECTED)
28 filter.addAction(Intent.ACTION_SCREEN_OFF)
29 filter.addAction(Intent.ACTION_SCREEN_ON)
30 registerReceiver(combinedServiceReceiver, filter)
31 TileService.requestListeningState(
32 this,
33 ComponentName(this, AlwaysOnTileService::class.java),
34 )
35 }
36
37 override fun onDestroy() {
38 super.onDestroy()
39 unregisterReceiver(combinedServiceReceiver)
40 }
41
42 override fun onStartCommand(
43 intent: Intent,
44 flags: Int,
45 startId: Int,
46 ): Int {
47 createNotificationChannel()
48 startForeground(
49 1,
50 NotificationCompat.Builder(this, CHANNEL_ID)
51 .setContentText(resources.getString(R.string.service_text))
52 .setSmallIcon(R.drawable.ic_always_on_black)
53 .setShowWhen(false)
54 .build(),
55 )
56 return START_REDELIVER_INTENT
57 }
58
59 override fun onBind(intent: Intent): IBinder? = null
60
61 private fun createNotificationChannel() {
62 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
63 val channel =
64 NotificationChannel(
65 CHANNEL_ID,
66 resources.getString(R.string.service_channel),
67 NotificationManager.IMPORTANCE_LOW,
68 )
69 channel.setShowBadge(false)
70 getSystemService(NotificationManager::class.java)?.createNotificationChannel(channel)
71 }
72 }
73
74 companion object {
75 const val CHANNEL_ID: String = "service_channel"
76 }
77 }
78