/** * A constructor is required, and must call the super [android.app.IntentService.IntentService] * constructor with a name for the worker thread. */ classHelloIntentService : IntentService("HelloIntentService") {
/** * The IntentService calls this method from the default worker thread with * the intent that started the service. When this method returns, IntentService * stops the service, as appropriate. */ overridefunonHandleIntent(intent: Intent?) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. try { Thread.sleep(5000) } catch (e: InterruptedException) { // Restore interrupt status. Thread.currentThread().interrupt() }
// Handler that receives messages from the thread privateinnerclassServiceHandler(looper: Looper) : Handler(looper) {
overridefunhandleMessage(msg: Message) { // Normally we would do some work here, like download a file. // For our sample, we just sleep for 5 seconds. try { Thread.sleep(5000) } catch (e: InterruptedException) { // Restore interrupt status. Thread.currentThread().interrupt() }
// Stop the service using the startId, so that we don't stop // the service in the middle of handling another job stopSelf(msg.arg1) } }
overridefunonCreate() { // Start up the thread running the service. Note that we create a // separate thread because the service normally runs in the process's // main thread, which we don't want to block. We also make it // background priority so CPU-intensive work will not disrupt our UI. HandlerThread("ServiceStartArguments", Process.THREAD_PRIORITY_BACKGROUND).apply { start()
// Get the HandlerThread's Looper and use it for our Handler serviceLooper = looper serviceHandler = ServiceHandler(looper) } }
// For each start request, send a message to start a job and deliver the // start ID so we know which request we're stopping when we finish the job serviceHandler?.obtainMessage()?.also { msg -> msg.arg1 = startId serviceHandler?.sendMessage(msg) }
// If we get killed, after returning from here, restart return START_STICKY }
overridefunonBind(intent: Intent): IBinder? { // We don't provide binding, so return null returnnull }