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.

AlarmService.kt

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

TimerExpiredReceiver.kt

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

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

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:

WordPress.com Logo

You are commenting using your WordPress.com 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