Sun. Dec 22nd, 2024

A Service is an app component that can handle long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC).

For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

These are the three different types of services:

Scheduled

A service is scheduled when an API such as the JobScheduler, introduced in Android 5.0 (API level 21), launches the service. You can use the JobScheduler by registering jobs and specifying their requirements for network and timing. The system then gracefully schedules the jobs for execution at the appropriate times. The JobScheduler provides many methods to define service-execution conditions.

Note: If your app targets Android 5.0 (API level 21), Google recommends that you use the JobScheduler to execute background services. For more information about using this class, see the JobScheduler reference documentation.

http://www.codebind.com/wp-content/uploads/2016/08/service_lifecycle_rdc.jpgStarted

A service is started when an application component (such as an activity) calls startService(). After it’s started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller.

For example, it can download or upload a file over the network. When the operation is complete, the service should stop itself.

Bound

A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, receive results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

Regardless of whether your application is started, bound, or both, any application component can use the service (even from a separate application) in the same way that any component can use an activity—by starting it with an Intent. However, you can declare the service as private in the manifest file and block access from other applications. This is discussed more in the section about Declaring the service in the manifest.

Caution: A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise. If your service is going to perform any CPU-intensive work or blocking operations, such as MP3 playback or networking, you should create a new thread within the service to complete that work. By using a separate thread, you can reduce the risk of Application Not Responding (ANR) errors, and the application’s main thread can remain dedicated to user interaction with your activities.

Activity_mai.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Services Example"
         />

    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Servie" />

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

</LinearLayout>
</layout>

MainActivity.kt

package com.androindian.services

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import com.androindian.services.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    var bining: ActivityMainBinding?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bining=DataBindingUtil.setContentView(this,R.layout.activity_main)

        bining?.start?.setOnClickListener {
            var intent= Intent(this,Myservices::class.java)
            startService(intent)

        }

        bining?.stop?.setOnClickListener {
            var intent= Intent(this,Myservices::class.java)
            stopService(intent)

        }
    }
}

Myservices.kt

package com.androindian.services

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

class Myservices : Service() {

    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
        Toast.makeText(this,"onBind",Toast.LENGTH_LONG).show()
    }

    override fun onStart(intent: Intent?, startId: Int) {
        super.onStart(intent, startId)
        Toast.makeText(this,"onStart",Toast.LENGTH_LONG).show()
    }

    override fun onCreate() {
        super.onCreate()
        Toast.makeText(this,"onCreate",Toast.LENGTH_LONG).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        Toast.makeText(this,"onDestroy",Toast.LENGTH_LONG).show()
    }

    override fun onRebind(intent: Intent?) {
        super.onRebind(intent)
        Toast.makeText(this,"onRebind",Toast.LENGTH_LONG).show()
    }
}

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *