Android Services with Kotlin

An Android Service, is an application component that can perform long-running operations in the background, and it doesn’t provide a user interface.

A few example uses for a service could be:

  • Network transactions
  • Play music
  • Perform file I/O operations
  • Interact with content providers
  • Background operations

I’ve recently implemented a service in one of my applications to start a sound triggered by a BroadcastReceiver when an alarm expires and here is how I implemented it with Kotlin.


package com.isscroberto.powernap.util
import android.content.Context
import android.content.Intent
import android.os.IBinder
class AlarmService : Service() {
private lateinit var ringtone: Ringtone
override fun onBind(p0: Intent?): IBinder? {
return null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return super.onStartCommand(intent, flags, startId)
override fun onDestroy() {
fun playAlarm() {
val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
ringtone = RingtoneManager.getRingtone(this, notification)
if(!ringtone.isPlaying()) {

view raw
hosted with ❤ by GitHub

Then, this is how it’s started from the BroadcastReceiver.


package com.isscroberto.powernap
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.isscroberto.powernap.util.NotificationUtil
import com.isscroberto.powernap.util.PrefUtil
import com.isscroberto.powernap.util.AlarmService
class TimerExpiredReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// Show notification of expiration.
// Save status in preferences.
PrefUtil.setTimerState(NapState.Finished, context)
PrefUtil.setAlarmSetTime(0, context)
// Play alarm sound.

Finally don’t forget to add your reference to your app’s manifest file.

<service android:name=".util.AlarmService"/>

view raw
hosted with ❤ by GitHub

By using this service I’m able to stop it from anywhere within the application and stop the alarm sound when the user interacts with my app by calling stopService().

// Stop alarm.

view raw
hosted with ❤ by GitHub

I implemented this functionality in PowerNap, an app that will help you take efficient naps by controlling the time you sleep. You can find the source code in GitHub.

Posted in Dev

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s