Android Background Processing

Sep 23 2022 · Kotlin 1.6, Android 12, Android Studio Chipmunk 2021.2.1

Part 3: Use Android Services

16. Use Android Service

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 15. Introduction Next episode: 17. Use IntentService

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Notes: 16. Use Android Service

The student materials have been reviewed and are updated as of SEPTEMBER 2022.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

The first type of Services you’ll implement is the unbound background Service! Let’s see how to implement one, to download an image.

class DownloadService : Service() {

  override fun onBind(intent: Intent?): IBinder? {
    return null
  }

  override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
  }
}
<service android:name=".service.DownloadService" />
class DownloadService : Service() {

  override fun onBind(intent: Intent?): IBinder? {
    return null
  }

  override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    val imagePath = intent?.getStringExtra("image_path")
    if (imagePath != null) {
      downloadImage(imagePath)
    } else {
      Log.d("Missing image path", "Stopping service")
      stopSelf()
    }

    return START_NOT_STICKY
  }
}
class DownloadService : Service() {

  ...

  private fun downloadImage(imagePath: String) {
    Thread(Runnable {
      val file = File(applicationContext.externalMediaDirs.first(), imagePath)

      FileUtils.downloadImage(file, imagePath)
    }).start()
  }
}
override fun onImageDownload(imageUrl: String) {
  val intent = Intent(activity, DownloadService::class.java)
  intent.putExtra("image_path", imageUrl)

  activity?.startService(intent)
}
  override fun onStop() {
    val intent = Intent(this, DownloadService::class.java)
    stopService(intent)

    super.onStop()
  }
override fun onDestroy() {
  applicationContext?.toast("Stopping service!")
  super.onDestroy()
}