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.
AlarmService.kt
package com.isscroberto.powernap.util | |
import android.app.Service | |
import android.content.Context | |
import android.content.Intent | |
import android.media.Ringtone | |
import android.media.RingtoneManager | |
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 { | |
playAlarm() | |
return super.onStartCommand(intent, flags, startId) | |
} | |
override fun onDestroy() { | |
super.onDestroy() | |
ringtone.stop() | |
} | |
fun playAlarm() { | |
val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM) | |
ringtone = RingtoneManager.getRingtone(this, notification) | |
if(!ringtone.isPlaying()) { | |
ringtone.play() | |
} | |
} | |
} |
Then, this is how it’s started from the BroadcastReceiver.
TimerExpiredReceiver.kt
package com.isscroberto.powernap | |
import android.content.BroadcastReceiver | |
import android.content.Context | |
import android.content.Intent | |
import com.isscroberto.powernap.data.NapState | |
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. | |
NotificationUtil.showTimerExpired(context) | |
// Save status in preferences. | |
PrefUtil.setTimerState(NapState.Finished, context) | |
PrefUtil.setAlarmSetTime(0, context) | |
// Play alarm sound. | |
context.startService(Intent(context, AlarmService::class.java)) | |
} | |
} |
Finally don’t forget to add your reference to your app’s manifest file.
<service android:name=".util.AlarmService"/> |
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. | |
context!!.stopService(Intent(context!!, AlarmService::class.java)) |
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.