Get immediate access to this and over 1,500+ other videos and books.

Boost your skills with a raywenderlich.com Beginner subscription. With over 60+ video courses and our core foundational programming books bundled in one subscription, it’s simply the best investment you can make in your development career.

Use Android Service

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

Implement the basic Android Service, to run work in the background, and offload the main thread.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

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()
}

Reviews

Comments