What is Service

A service in android is an application component that run in background and there is no user interface of the service.For example downloading the file and playing the music in background is the example of service in android.


Service:.

In this section i am going to show the Service with practical example.

In my service program when you click on start service button it will play the music you can work like chatting etc in your mobile there is no problem.When you click on stop service button then the service will stop means playing music will stop.

First open the android studio and create a project and give the name of your project like ServiceDemo.

The screenshots of the program is as follows:

Smiley face Smiley face

Drag and drop the two Button from pallet. Open the activity_main.xml file and code look like this


<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.example.niitpc.servicedemo.MainActivity">


    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service"
        android:layout_marginTop="250dp"
        android:layout_marginLeft="30dp"

        tools:ignore="MissingConstraints"
        android:onClick="startService"
        />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Service"
        android:layout_marginTop="250dp"
        android:layout_marginLeft="200dp"


        android:onClick="stopService"
        tools:ignore="MissingConstraints" />
</RelativeLayout>


     

After that i am going to create the Service for this you explore the app folder and than explore the java folder and than right click tha package of your MainActivity.java class.A dialog box will display and then click on new->service->service.Again a dialog box will display where you need to give the service name in my case it is TheService.

The service class code look like this.The created TheService class always inherit the service parent class.

import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;


public class TheService extends Service {

    MediaPlayer mediaPlayer;
    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer=MediaPlayer.create(this,R.raw.abc);
        mediaPlayer.setLooping(false);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mediaPlayer.start();
        Toast.makeText(getApplicationContext(),"Playing music start", Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {

        mediaPlayer.stop();
        Toast.makeText(getApplicationContext(),"Playing music stop", Toast.LENGTH_LONG).show();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}



       

Explanation:

MediaPlayer mediaPlayer:In this statement i am declaring the mediaPlayer object of MediaPlayer class.

onCreate():When a service is start then the onCreate() method called.In my case i have called the MediaPlayer method create that take the song path like R.raw.abc.For this you simple need to right click on res folder and a dialog box will display click on new->android resource directory again a dialog box will display then you select the Resource type as raw and then click on finish.

onStartCommand():This method is called when the service is start and in my case with in this method i am calling the mediaPlayer.start().This will play the music.

onDestroy():This method is called when the service is destroyed in my case the mediaPlayer.stop() methos is called that will stop the play music.

onBind():You must need to implement this method.


Open the MainActivity.java file and write code look like this.


package com.example.niitpc.servicedemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void startService(View v)
    {
        Intent intent=new Intent(this,TheService.class);
        startService(intent);

    }
    public  void stopService(View v)
    {
        Intent intent=new Intent(this,TheService.class);
        stopService(intent);
    }
}


       

Explanation:

startService():with in this method i am creating the intent object of the Intent class and it will take the two argument first is this and second is Service class(TheService).After that i am passing the intent to startService() as argument that start the service and play the music.

stopServiceWith in this method i am creating the intent object of the Intent class and it will take the two argument first is this and second is Service class(TheService).After that i am passing the intent to stopService() as argument that stop the service and stop the music.


Open the AndroidMenifest.xml file and write the one line below the activity like this.

<


   <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>
      //you need to add this line
       <service
            android:name=".TheService"
            android:enabled="true"
            android:exported="true"></service>
    </application>

</manifest>
     

Do not forgot the setting of button onClick preperty of first button as startService() and second button as stopService().

Service

What is service for video Click here

Smiley face                     Smiley face