Pandiyan Mani
2 min readAug 23, 2023

--

What is Service?

In Android, services are a specific component that allows an app to run in the background and do long-running operations activities. The primary goal of a service is to keep an application running in the background so that the user may utilize many programs at the same time.

Lets see the actual implementation:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service" />

<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service" />
</LinearLayout>

We have two button one is to start service and another one is to stop service.

Lets see the Service Code:

package com.app.webview

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.widget.Toast
import android.os.CountDownTimer

class MyService : Service() {
var i : Int =0
var ca:CountDownTimer ?= null
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Toast.makeText(
applicationContext, "This is a Service running in Background", Toast.LENGTH_SHORT
).show()
ca= object : CountDownTimer(30000, 1000) {
override fun onTick(millisUntilFinished: Long) {
println("Print count"+i++)
}
override fun onFinish() {
}
}.start()
return START_STICKY
}

override fun onBind(intent: Intent): IBinder? {
// TODO: Return the communication channel to the service.
throw UnsupportedOperationException("Not yet implemented")
}

override fun onDestroy() {
super.onDestroy()
ca!!.cancel()
Toast.makeText(
applicationContext, "Service Stopped", Toast.LENGTH_SHORT
).show()
}
}

Lets see the MainActivity Code:

package com.app.webview

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val start = findViewById<Button>(R.id.start)
val stop = findViewById<Button>(R.id.stop)

start.setOnClickListener {
startService(Intent(applicationContext, MyService::class.java))
}

stop.setOnClickListener {
stopService(Intent(applicationContext, MyService::class.java))
}
}
}

And in manifest add the service:

<service android:name=".MyService" android:enabled="true"
android:exported="true"></service>

Final Output:

you can see in the logcat count printing.

--

--