1+ class CustomService : Service () {
2+
3+ // use worker thread if long running operation to not block main UI thread
4+ // or provide some multithreading if needed
5+ private val handlerThread = HandlerThread (" HandlerThread" )
6+ private lateinit var handler : Handler
7+
8+ override fun onBind (intent : Intent ? ): IBinder ? {
9+ // invokes when bindService called, retrieve intent and decide what to do
10+ // if service is created by bindService and onStartCommand wasn't called then runs only as components are bound
11+
12+ return null // provide communication interface or return null when no bind needed
13+ }
14+
15+ override fun onStartCommand (intent : Intent ? , flags : Int , startId : Int ): Int {
16+ // invokes when startService or startForegroundService called, retrieve intent and decide what to do
17+ // continues to run until stops itself or by another component
18+
19+ return START_STICKY // restart service strategy after destroyed by the system
20+ }
21+
22+ override fun onCreate () {
23+ // invokes one time setup before onStartCommand or onBind
24+ // not called when service already running
25+ super .onCreate()
26+ handlerThread.start()
27+ handler = Handler (handlerThread.looper)
28+ }
29+
30+ override fun onDestroy () {
31+ // invokes when stopSelf or stopService is called
32+ // service is no longer used or is being destroyed by system or client
33+ super .onDestroy()
34+ handler.removeCallbacksAndMessages(null )
35+ handlerThread.quitSafely()
36+ handlerThread.interrupt()
37+ }
38+
39+ // more lifecycle callbacks
40+ }
41+
42+ // run startService or bindService and pass Intent to run Service
0 commit comments