Android Service Tutorial

Android Service Tutorial

Android service is a component that is used to perform operations on the background such as playing music, handle network transactions, interacting content providers etc. It doesn’t have any UI (user interface).

The service runs in the background indefinitely even if the application is destroyed.service can be bounded by a component to perform interactivity and inter-process communication (IPC).

Life Cycle of Android Service

There are two types of a service. The lifecycle of service can follow two different paths: started or bound.

  1. Started
  2. Bound

1) Started Service

A service is started when App component (like activity) calls startService() method, now it runs in the background indefinitely. It is stopped by stopService() method. The service can stop itself by calling the stopSelf() method.

2) Bound Service

A service is bound when another component calls bindService() method. A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). The client can unbind the service by calling the unbindService() method

Android Service Example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>  

<RelativeLayout 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"  

    tools:context="com.codeplayon.androidservice.MainActivity">  

    

    <Button  

      android:id="@+id/buttonStart"  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content"  

        android:layout_alignParentTop="true"  

        android:layout_centerHorizontal="true"  

        android:layout_marginTop="74dp"  

        android:text="Start Service" />  

  

    <Button  

        android:id="@+id/buttonStop"  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content"  

        android:layout_centerHorizontal="true"  

        android:layout_centerVertical="true"  

        android:text="Stop Service" />  

  

    <Button  

        android:id="@+id/buttonNext"  

        android:layout_width="wrap_content"  

       android:layout_height="wrap_content"  

       android:layout_alignParentBottom="true"  

       android:layout_centerHorizontal="true"  

       android:layout_marginBottom="63dp"  

        android:text="Next Page" />  

</RelativeLayout>  

MainActivity.java

package com.codeplayon.androidservice;  

  

import android.content.Intent;  

import android.support.v7.app.AppCompatActivity;  

import android.os.Bundle;  

import android.view.View;  

import android.widget.Button;  

  

public class MainActivity extends AppCompatActivity implements View.OnClickListener{  

    Button buttonStart, buttonStop,buttonNext;  

    @Override  

    protected void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.activity_main);  

  

        buttonStart = findViewById(R.id.buttonStart);  

        buttonStop = findViewById(R.id.buttonStop);  

        buttonNext =  findViewById(R.id.buttonNext);  

  

        buttonStart.setOnClickListener(this);  

        buttonStop.setOnClickListener(this);  

        buttonNext.setOnClickListener(this);  

  

  

    }  

    public void onClick(View src) {  

        switch (src.getId()) {  

            case R.id.buttonStart:  

  

                startService(new Intent(this, MyService.class));  

                break;  

            case R.id.buttonStop:  

                stopService(new Intent(this, MyService.class));  

                break;  

            case R.id.buttonNext:  

                Intent intent=new Intent(this,NextPage.class);  

                startActivity(intent);  

                break;  

        }  

    }  

}  

Service class

Now create the service implementation class by inheriting the Service class and overriding its callback methods.

package com.codeplayon.androidservice;  

  

import android.app.Service;  

import android.content.Intent;  

import android.media.MediaPlayer;  

import android.os.IBinder;  

import android.support.annotation.Nullable;  

import android.widget.Toast;  

  

public class MyService extends Service {  

    MediaPlayer myPlayer;  

    @Nullable  

    @Override  

    public IBinder onBind(Intent intent) {  

        return null;  

    }  

    @Override  

    public void onCreate() {  

        Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();  

  

        myPlayer = MediaPlayer.create(this, R.raw.sun);  

        myPlayer.setLooping(false); // Set looping  

    }  

    @Override  

    public void onStart(Intent intent, int startid) {  

        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();  

        myPlayer.start();  

    }  

    @Override  

    public void onDestroy() {  

        Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();  

        myPlayer.stop();  

    }  

}  

 

Now, create another activity. Second Activity

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>  

<android.support.constraint.ConstraintLayout 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"  

    tools:context="com.codeplayon.androidservice.NextPage">  

  

    <TextView  

        android:id="@+id/textView"  

        android:layout_width="wrap_content"  

        android:layout_height="wrap_content"  

        android:layout_marginEnd="8dp"  

        android:layout_marginStart="8dp"  

        android:layout_marginTop="200dp"  

        android:text="Second Page"  

        app:layout_constraintEnd_toEndOf="parent"  

        app:layout_constraintStart_toStartOf="parent"  

        app:layout_constraintTop_toTopOf="parent" />  

</android.support.constraint.ConstraintLayout>  

Second.java

package  com.codeplayon.androidservice;  

  

import android.support.v7.app.AppCompatActivity;  

import android.os.Bundle;  

  

public class NextPage extends AppCompatActivity {  

  

    @Override  

    protected void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.activity_next);  

    }  

}  
AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>  

<manifest xmlns:android="http://schemas.android.com/apk/res/android"  

    package="com.codeplayon.androidservice">  

  

    <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>  

        <activity android:name=".Second"></activity>  

        <service  

            android:name=".MyService"  

            android:enabled="true" />  

    </application>  

  

</manifest>  

 

 

 

You may also like...