MainActivity.kt
package com.cfsuman.kotlinexamples
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.app.ActivityManager
import android.content.Context
import android.widget.Toast
import android.content.Intent
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Variable to hold service class name
val serviceClass = RandomNumberService::class.java
// Initialize a new Intent instance
val intent = Intent(applicationContext, serviceClass)
// Button to start the service
button_start.setOnClickListener{
// If the service is not running then start it
if (!isServiceRunning(serviceClass)) {
// Start the service
startService(intent)
} else {
toast("Service already running.")
}
}
// Button to stop the service
button_stop.setOnClickListener{
// If the service is not running then start it
if (isServiceRunning(serviceClass)) {
// Stop the service
stopService(intent)
} else {
toast("Service already stopped.")
}
}
// Get the service status
button_stats.setOnClickListener{
if (isServiceRunning(serviceClass)) {
toast("Service is running.")
} else {
toast("Service is stopped.")
}
}
}
// Custom method to determine whether a service is running
private fun isServiceRunning(serviceClass: Class<*>): Boolean {
val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
// Loop through the running services
for (service in activityManager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
// If the service is running then return true
return true
}
}
return false
}
}
// Extension function to show toast message
fun Context.toast(message:String){
Toast.makeText(applicationContext,message,Toast.LENGTH_SHORT).show()
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#7b917b"
android:orientation="vertical"
android:padding="16dp"
>
<Button
android:id="@+id/button_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service"
/>
<Button
android:id="@+id/button_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service"
/>
<Button
android:id="@+id/button_stats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Service Stats"
/>
</LinearLayout>
RandomNumberService.kt
package com.cfsuman.kotlinexamples
import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import java.util.*
class RandomNumberService : Service() {
private lateinit var mHandler: Handler
private lateinit var mRunnable: Runnable
override fun onBind(intent: Intent): IBinder? {
throw UnsupportedOperationException("Not yet implemented")
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
// Send a notification that service is started
toast("Service started.")
// Do a periodic task
mHandler = Handler()
mRunnable = Runnable { showRandomNumber() }
mHandler.postDelayed(mRunnable, 5000)
return Service.START_STICKY
}
override fun onDestroy() {
super.onDestroy()
toast("Service destroyed.")
mHandler.removeCallbacks(mRunnable)
}
// Custom method to do a task
private fun showRandomNumber() {
val rand = Random()
val number = rand.nextInt(100)
toast("Random Number : $number")
mHandler.postDelayed(mRunnable, 5000)
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cfsuman.kotlinexamples"
>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".RandomNumberService"
android:enabled="true"
android:exported="true"
/>
</application>
</manifest>
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3qSLg_59zuH4Aj-v_xKOWrU0ZA2uBxbR4dbtEgc3rNtXF8uw_aHnHD_fuqzZvM5-fgXcylYGZ8qe13mYasLa5NvohgptS1g6Ujt-sWJWa9sgPcGX8yB2gNxoD6PUW6RW4UIjEDorfr4f7/s1600/AndroidKotlinServiceExample.png)
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgn7OyZYskgm66ygnjZDk-viI_gqVJMX4D8UvRWGlXcNhyphenhyphenwwA5b7keBCbnuHhfRfY5qAFvWFpDtwxxS3GTU668HfZkaIS236QpizbYSYOnhbpjotZUGuJMYZnxfT0fx_VFiWtmZBA08pCBy/s1600/AndroidKotlinServiceExample2.png)
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiWrOVxKxTRKCEi3Lx7gPNyxkSJj76zHNtceokdSFMeelWp7ClFbKpuvYeeA3lJD32liy7P9tkJZW6JnXRImNh34UKUS61cWefDSTvQ0Jv7pdjACk8aBdutNSUk3ZI8m7F6nWsR4mp60ddt/s1600/AndroidKotlinServiceExample3.png)
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJv6SRlYVaybWl34HDyVRquOyBvAgxWFrjwgjrnaHMP4LL9vVoKssgIMQSUkaRLL5Aaxfq9lctSm64s47OPKdY_BPBPGRzglyGTP5MJn9UEVg2xjtCL8aVMwGwZWjWu8nVxxg1FK_6Wmfv/s1600/AndroidKotlinServiceExample4.png)
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhS6594oyfb8qPFqcHmoziJPkXyQySPoOaCL9-3NuR4Eze-sHXUofmoqqKY8irCBkdkRLkhhUmlmIWZAVSEGj6O3i1lvPMYpB62rHvbxIBmAlpiqi0LYBipwOJsvPAlWrzoHEEcGnN-g3MI/s1600/AndroidKotlinServiceExample5.png)