1 package com.android.onboarding.process 2 3 import android.annotation.TargetApi 4 import android.app.Notification 5 import android.app.NotificationChannel 6 import android.app.NotificationManager 7 import android.app.Service 8 import android.content.Intent 9 import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE 10 import android.os.Build 11 import android.os.IBinder 12 import android.util.Log 13 14 /** 15 * Service utilized to ensure that the calling process remains active and is protected from being 16 * terminated by the system on displaying a foreground notification. 17 */ 18 class NotificationKeepAliveService : Service() { 19 onBindnull20 override fun onBind(intent: Intent?): IBinder? = null 21 22 override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { 23 Log.d("KeepAliveService", "NotificationKeepAliveService Started") 24 25 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 26 createNotificationChannel() 27 val notification = 28 Notification.Builder(this, "keep_alive_id") 29 .setSmallIcon(R.drawable.notification_action_background) 30 .setOngoing(true) 31 .build() 32 33 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { 34 startForeground(NOTIFICATION_ID, notification, FOREGROUND_SERVICE_TYPE_SPECIAL_USE) 35 } else { 36 startForeground(NOTIFICATION_ID, notification) 37 } 38 } 39 40 return START_STICKY 41 } 42 onDestroynull43 override fun onDestroy() { 44 super.onDestroy() 45 46 Log.d("KeepAliveService", "NotificationKeepAliveService Stopped") 47 } 48 49 @TargetApi(Build.VERSION_CODES.O) createNotificationChannelnull50 private fun createNotificationChannel() { 51 val notificationChannel = 52 NotificationChannel("keep_alive_id", "Keep Alive", NotificationManager.IMPORTANCE_MIN) 53 val notificationManager = getSystemService(NotificationManager::class.java) 54 notificationManager?.createNotificationChannel(notificationChannel) 55 } 56 57 private companion object { 58 59 const val NOTIFICATION_ID = 12345 60 } 61 } 62