Services In Android



The service is a component that keeps an app running in the background to perform long-running operations based on our needs. For the service, we have no user interface and will run apps in the background such as music playing in the background or when users handle network operations in different apps.


Example of Service: A good example is your music player.

“When you play music in your Android handset using a playlist, the music player takes care of the job, without user intervention. You do not have to change the song every time a song ends. This automation is due to the service component of Android"

Life Cycle of Android Service

A service may have two forms. The service lifecycle can follow two different paths: starting and Running,Destoyed.
  1. Starting
  2. Running
  3. Destroyed
Android Services

Forms of Service

A Service can have two forms:

1)Start / unbound: In this case, an application starts the component service, and it will continue running in the background, even if the original component that started it is destroyed. For example, when launched, a service will continue to play music in the background indefinitely.

2) Bound: An Android component can bind itself to a service using bind service (). A bound service will run until other application components are bound to it. The service destroys itself as soon as they unbind. the service destroys itself.

Example of Services:-

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"
    android:background="#E91E63"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/buttonStart"
        android:layout_width="200dp"
        android:layout_height="60dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:background="#123"
        android:layout_marginTop="74dp"
        android:text="Start Service"
        android:textColor="#ffff"/>

    <Button
        android:id="@+id/buttonStop"
        android:layout_width="200dp"
        android:layout_height="60dp"
        android:background="#123"
        android:textColor="#ffff"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Stop Service" />


    </RelativeLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    Button buttonStart, buttonStop;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonStart = findViewById(R.id.buttonStart);
        buttonStop = findViewById(R.id.buttonStop);


        buttonStart.setOnClickListener(this);
        buttonStop.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;
                    }
    }
}

MyService.java

package com.example.services;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

import androidx.annotation.Nullable;

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.song);
        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();

    }


Let's see the complete AndroidManifest.xml file

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

    <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>
        <service
            android:name=".MyService"
            android:enabled="true" />
    </application>
</manifest>

Make  the resourse directory folder name is raw and Add any music which you want to  listen in background

Android Services file

This is design of above code.

Android Services Results



Post a Comment

0 Comments