Application Component in Android

Pandiyan Mani
5 min readMar 23, 2023

Application components are the essential building blocks of an Android application. Lets see four main components that is used for android application deveopment.

1.Activity → Handles the user interaction from the user.

2.Service → It will be helpful on performing a long running operation and the service doesn't not have any UI related stuffs.

3.Broadcast Receiver → Handles communication between Android OS and Application.

4.Content Providers → handle data and database management issues.

Lets see all them in detail with an example

So the first step is to create a new project inside the Android Studio Workspace

for that we can go to File → New Project → Select Empty Activity From List

so it will ask us for the Name which is Project name so currently I am naming it has applicationcomponent followed by package name which will be unique for each project so I am naming it has com.student.applicationcomponent below we have Save Location where we want to save our project and Language will be Kotlin so the Minimum SDK will be starting from Api 24 That is Android 7 OS from there to Api 33 which is the current one Android 13 OS.

By Default we will be having an activity created MainActivity which point to the Screen/Xml activity_main.xml under layout folder if you want you can rename this to by right clicking thee file and refractor for both files.

Choose on the applicationcomponent folder right click choose service like the one in the above image

it will ask for Service Class Name so i am going to name it has CountDownTimers and exported is checked Whether or not components of other applications can invoke the service or interact with it — “true” if they can, and “false” if not.And Language is kotlin.

override fun onBind(intent: Intent): IBinder? {
return null
}

I am just returning the onBind with null since I am not going to implement any logic there the use of onBind → interface that clients can use to interact with the service.

Next step is override the three method that will be used later on the Count Down Timer Development

override fun onCreate() {
super.onCreate()
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return super.onStartCommand(intent, flags, startId)
}

override fun onDestroy() {
super.onDestroy()
}

onStartCommand() → The system invokes this method by calling startService() when another component (such as an activity) requests that the service be started.

onCreate() → The system calls this method when the service is first created using onStartCommand().

onDestroy() → will be called when the service get destroyed by swiping or by stopService().

So always onCreate will be called first whenever the service created for the first time followed by onStartCommand. so if you again start an service if its running you can see only onStartCommand will be called not onCreate.

first we will be declaring the variables that we are going to use inside the service so that first one will be static which will be declared under companion object

companion object {
var COUNT_DOWN = "com.student.countdown_timer"
}
var intent : Intent = Intent(COUNT_DOWN)
// since var is mutable we can change at later point of time.
var ct: CountDownTimer? = null 
// Currently we intilize the CountDownTimer variable to null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return super.onStartCommand(intent, flags, startId)
}

So next step is to start the Count Down Timer and send result on each count Down using sendBroadcast .so you can see we added value inside the intent as putExtra and passed to sendBroadcast(intent).

ct = object : CountDownTimer(30000, 1000) {
override fun onTick(milliunits: Long) {
intent.putExtra("cttimer", "" + milliunits / 1000)
sendBroadcast(intent)
}

override fun onFinish() {

}
}
ct!!.start()

So on onDestroy() we need to cancel the Timer if the user Cancel/Stop Service.

override fun onDestroy() {
super.onDestroy()
ct!!.cancel()
}

That is it on the service end lets see the complete code of the CountDownTimers class which is psted below.

package com.student

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

class CountDownTimers : Service() {

companion object {
var COUNT_DOWN = "com.student.countdown_timer"
}

var intent: Intent = Intent(COUNT_DOWN)
var ct: CountDownTimer? = null

override fun onBind(intent: Intent): IBinder? {
return null
}

override fun onCreate() {
super.onCreate()
ct = object : CountDownTimer(30000, 1000) {
override fun onTick(milliunits: Long) {
intent.putExtra("cttimer", "" + milliunits / 1000)
sendBroadcast(intent)
}

override fun onFinish() {

}
}
ct!!.start()
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return super.onStartCommand(intent, flags, startId)
}

override fun onDestroy() {
super.onDestroy()
ct!!.cancel()
}
}

Lets design the screen which is activity_main.xml which holds two button and one TextView. so one button is start and another one is stop and in the TextView we will display countdown.

<?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:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textStyle="italic|bold"
android:textSize="40sp"
android:textColor="@color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_margin="10sp"
android:weightSum="2"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/start"
android:layout_weight="1"
android:text="Start"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

</Button>
<Button
android:id="@+id/stop"
android:layout_marginStart="10sp"
android:layout_weight="1"
android:text="Stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

</Button>
</LinearLayout>

</LinearLayout>

Lets see the MainActivity code which get user interaction when user tap start and stop button and perform operation based on that.

package com.student.applicationcomponent

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.student.CountDownTimers
import com.student.CountDownTimers.Companion.COUNT_DOWN

class MainActivity : AppCompatActivity() {
var countdown: TextView ?= null
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)
countdown = findViewById<TextView>(R.id.countdownss)



start.setOnClickListener {
registerReceiver(br, IntentFilter(COUNT_DOWN))
startService(Intent(this,CountDownTimers::class.java))
}
stop.setOnClickListener {
countdown!!.text = "0"
try {
unregisterReceiver(br)
} catch (e: Exception) {
}
stopService(Intent(this,CountDownTimers::class.java))
}

}

override fun onPause() {
super.onPause()
try {
unregisterReceiver(br)
} catch (e: Exception) {
}
}

private val br: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent:Intent) {
countdown!!.text = intent.getStringExtra("cttimer")
}
}

override fun onResume() {
registerReceiver(br, IntentFilter(COUNT_DOWN))
super.onResume()
}
}

I pasted the entire code which start the service and stop the service and we registered the receiver based on the UI Update we need to listen. we used BroadcastReceiver to listen the value from service and update on the text.

Attached Final GitHub Source Code:

https://github.com/Pandiyanmk/Application-Component.git

--

--