Android Service Example

06-Dec-2024

Learn how to implement background services in Android Studio Project using Kotlin to run tasks in the background


1/ Step : Create A New class  MyService .



import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.os.SystemClock
import androidx.core.app.NotificationCompat

class MyService : Service() {

private var isRunning = false
private var startTime: Long = 0

override fun onBind(intent: Intent?): IBinder? {

return null
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (!isRunning) {
isRunning = true
startTime = SystemClock.elapsedRealtime()


startForegroundService()


Thread {
while (isRunning) {
val elapsedTime = SystemClock.elapsedRealtime() - startTime
println("Service is running: ${elapsedTime / 1000} seconds")
SystemClock.sleep(1000)
}
}.start()
}

return START_STICKY
}

override fun onDestroy() {
super.onDestroy()
isRunning = false
println("Service Stopped")
}

@SuppressLint("ForegroundServiceType")
private fun startForegroundService() {
val channelId = "MyServiceChannel"
val channelName = "My Background Service"
val notificationManager = getSystemService(NotificationManager::class.java)

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
channelName,
NotificationManager.IMPORTANCE_LOW
)
notificationManager?.createNotificationChannel(channel)
}

val notification: Notification = NotificationCompat.Builder(this, channelId)
.setContentTitle("My Service is Running")
.setContentText("Performing background tasks...")
.setSmallIcon(android.R.drawable.ic_notification_overlay)
.build()

startForeground(1, notification)
}
}


2/Spep :  AndroidManifest.xml  add the code


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
tools:targetApi="31">

<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>
</activity>
//////////////////////////////////////////////////////

<service
android:name="MyService"
android:enabled="true"
android:exported="false"
tools:ignore="MissingClass" />

///////////////////////////////////////////////////////////
</application>

</manifest>


3/Step :  Add the code MainActivity .


package com.alomkaisa.myapplication

import MyService
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {

private lateinit var startServiceButton: Button
private lateinit var stopServiceButton: Button

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

startServiceButton = findViewById(R.id.startServiceButton)
stopServiceButton = findViewById(R.id.stopServiceButton)

val serviceIntent = Intent(this, MyService::class.java)

startServiceButton.setOnClickListener {
startService(serviceIntent) // Start Service
}

stopServiceButton.setOnClickListener {
stopService(serviceIntent) // Stop Service
}
}
}


4/Spep :  Add the code  Activity_main.xml


     <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#BECDDC39"
android:padding="16dp">

<Button
android:layout_marginTop="100dp"
android:id="@+id/startServiceButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="Start Service" />

<Button
android:layout_marginTop="30dp"
android:id="@+id/stopServiceButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="Stop Service"
/>
</LinearLayout>

Comments