Android Service

1- The types of services on Android

What is service ?

A service is a component that runs in the background to perform long-running operations without needing to interact with the user and it works even if application is destroyed. A service can essentially take two states

State Description
Started A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.

This service is also known as Un Bounded Service.

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, get results, and even do so across processes with interprocess communication (IPC).

In computer science, inter-process communication (IPC) is the activity of sharing data across multiple and commonly specialized processes using communication protocols. Typically, applications using IPC are categorized as clients and servers, where the client requests data and the server responds to client requests.

Bạn đang đọc: Android Service

A service has life cycle callback methods that you can implement to monitor changes in the service’s state and you can perform work at the appropriate stage. The following diagram on the left shows the life cycle when the service is created with startService() and the diagram on the right shows the life cycle when the service is created with bindService()

To create an service, you create a Java class that extends the Service base class or one of its existing subclasses. The Service base class defines various callback methods and the most important are given below. You don’t need to implement all the callbacks methods. However, it’s important that you understand each one and implement those that ensure your app behaves the way users expect.

Also, there are another service called IntentService. Intent Service is used to perform one time task i.e when the task completes the service destroys itself.


Comparison of services :

Unbound
Service
Bound 
Service
Intent 
Service
Unbounded Service is used to perform long repetitive task Bounded Service is used to perform background task in bound with another component Intent Service is used to perform one time task i.e when the task completes the service destroys itself.
Unbound Service gets starts by calling startService(). Bounded Service gets starts by calling bindService(). Intent Service gets  starts by calling startService().
Unbound Service is stopped or destroyed explicitly  by calling stopService(). Bounded Service is unbind or destroyed by calling unbindService(). IntentService Implicitly calls stopself() to destroy
Unbound Service is independent of the component in which it is started. Bound Service dependents on the component in which it is started. Intent Service is independent of the component in which it is started.

The callback methods and description :

Callback Description
onStartCommand() The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). If you implement this method, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService() methods.
onBind() The system calls this method when another component wants to bind with the service by calling bindService(). If you implement this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder object. You must always implement this method, but if you don’t want to allow binding, then you should return null.
onUnbind() The system calls this method when all clients have disconnected from a particular interface published by the service.
onRebind() The system calls this method when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent).
onCreate() The system calls this method when the service is first created using onStartCommand() or onBind(). This call is required to perform one-time set-up.
onDestroy() The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc.

2- Unbounded Service

Unbound Service (or Started Service): In this case, an application component starts the service by calling startService(), and it would continue to run in the background, even if the original component that initiated it is destroyed. For instance, when started, a service would continue to play music in the background indefinitely.

onStartCommand() method has integer return type value which can be any of the following:

 

  • START_STICKY
  • START_NOT_STICKY
  • TART_REDELIVER_INTENT

START_STICKY và START_NOT_STICKY

  • Both values are only relevant when the phone runs out of memory and kills the service before it finishes executing.
  • START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent.
  • START_NOT_STICKY tells the OS to not bother recreating the service again.

There is also a third code START_REDELIVER_INTENT that tells the OS to recreate the service AND redelivery the same intent to onStartCommand().

Playing music service example ( Run in background )

Create “Empty Activity” project with name PlaySongService

  • Name: PlaySongService
  • Package name: org.o7planning.playsongservice


Project created .

Prepare mp3 file :

Right-click on the ‘res’ folder, and select:

  • New > Folder > Raw Resources Folder

Copy and Paste a mp3 file to ‘raw‘ folder that you just have been created



Interface design of the application :

activity_main. xml





    

    

Create Service class
Right-click a Java package, select :

  • New  > Service > Service


Enter class name :

  • PlaySongService


You can see that PlaySongService has been declared with AndroidManifest.xml:

* * AndroidManifest. xml * *





    

        

            ....

    


PlaySongService. java


package org.o7planning.playsongservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.media.MediaPlayer;

public class PlaySongService extends Service {

    private MediaPlayer mediaPlayer;

    public PlaySongService() {
    }

    // Return the communication channel to the service.
    @Override
    public IBinder onBind(Intent intent){
        // This service is unbounded
        // So this method is never called.
        return null;
    }


    @Override
    public void onCreate(){
        super.onCreate();
        // Create MediaPlayer object, to play your song.
        mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.mysong);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        // Play song.
        mediaPlayer.start();

        return START_STICKY;
    }

    // Destroy
    @Override
    public void onDestroy() {
        // Release the resources
        mediaPlayer.release();
        super.onDestroy();
    }
}

MainActivity. java


package org.o7planning.playsongservice;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

    private Button buttonPlay;
    private Button buttonStop;

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

        this.buttonPlay = (Button) this.findViewById(R.id.button_play);
        this.buttonStop = (Button) this.findViewById(R.id.button_stop);

        this.buttonPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playSong();
            }
        });

        this.buttonStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopSong();
            }
        });
    }

    // This method is called when users click on the Play button.
    public void playSong()  {
        // Create Intent object for PlaySongService.
        Intent myIntent = new Intent(MainActivity.this, PlaySongService.class);

        // Call startService with Intent parameter.
        this.startService(myIntent);
    }

    // This method is called when users click on the Stop button.
    public void stopSong( )  {
        
        // Create Intent object
        Intent myIntent = new Intent(MainActivity.this, PlaySongService.class);
        this.stopService(myIntent);
    }

}

That’s OK, you can run your application and enjoy the song. 

3- Bouned Service

Hereinafter, I simulate a serivce that provides weather information current day, with the input is geographical location ( Hanoi, Chicago, … ), the result returned is rainy, sunny, …

Create project named WeatherService.

  • Name: WeatherService
  • Package name: org.o7planning.weatherservice


Interface design for the application :


activity_main. xml





    

    

    

    

Create Service :

Right-click a Java package, select:

  • New > Service > Service


Enter :

  • Class name: WeatherService

WeatherService class which  is extended from android.app.Service class.has been created.

You can see the WeatherService has been declared with AndroidManifest.xml:

* * AndroidManifest. xml * *





    
        

        ...

    


WeatherService. java


package org.o7planning.weatherservice;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Binder;
import android.util.Log;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


public class WeatherService extends Service {

    private static String LOG_TAG = "WeatherService";

    // Store the weather data.
    private static final Map weatherData = new HashMap();

    private final IBinder binder = new LocalWeatherBinder();

    public class LocalWeatherBinder extends Binder {

        public WeatherService getService()  {
            return WeatherService.this;
        }
    }

    public WeatherService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(LOG_TAG,"onBind");
        return this.binder;
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i(LOG_TAG, "onRebind");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i(LOG_TAG, "onUnbind");
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(LOG_TAG, "onDestroy");
    }

    // Returns the weather information corresponding to the location of the current date.
    public String getWeatherToday(String location) {
        Date now= new Date();
        DateFormat df= new SimpleDateFormat("dd-MM-yyyy");

        String dayString = df.format(now);
        String keyLocAndDay = location + "$"+ dayString;

        String weather=  weatherData.get(keyLocAndDay);
        //
        if(weather != null)  {
            return weather;
        }

        //
        String[] weathers = new String[]{"Rainy", "Hot", "Cool", "Warm" ,"Snowy"};

        // Random value from 0 to 4
        int i= new Random().nextInt(5);

        weather =weathers[i];
        weatherData.put(keyLocAndDay, weather);
        //
        return weather;
    }

}

MainActivity. java


package org.o7planning.weatherservice;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private boolean binded = false;
    private WeatherService weatherService;

    private TextView textViewWeather;
    private EditText editTextLocation;
    private Button buttonWeather;

    ServiceConnection weatherServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            WeatherService.LocalWeatherBinder binder = (WeatherService.LocalWeatherBinder) service;
            weatherService = binder.getService();
            binded = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            binded = false;
        }
    };

    // When the Activity creating its interface.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        this.textViewWeather = (TextView) this.findViewById(R.id.textView_weather);
        this.editTextLocation = (EditText) this.findViewById(R.id.editText_location);
        this.buttonWeather = (Button) this.findViewById(R.id.button_weather);

        this.buttonWeather.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 showWeather();
            }
        });
    }

    // When Activity starting.
    @Override
    protected void onStart() {
        super.onStart();

        // Create Intent object for WeatherService.
        Intent intent = new Intent(this, WeatherService.class);

        // Call bindService(..) method to bind service with UI.
        this.bindService(intent, weatherServiceConnection, Context.BIND_AUTO_CREATE);
    }

    // Activity stop
    @Override
    protected void onStop() {
        super.onStop();
        if (binded) {
            // Unbind Service
            this.unbindService(weatherServiceConnection);
            binded = false;
        }
    }

    // When user click on 'Show weather' button.
    public void showWeather()  {
        String location = this.editTextLocation.getText().toString();

        String weather= this.weatherService.getWeatherToday(location);

        this.textViewWeather.setText(weather);
    }

}

OK, now you can run the application .

4- IntentService service

IntentService example :

The below imagine illustrates the communication between Client (Activity) and  IntentService, Client start the service, it sends request through an Intent object, the service is run and do their duties, at the same time, it can send information relating to its working situation, for example, how many percentage does it work. At client, you can use ProgressBar to display the percentage of work.

The IntentService is designed to automatically stop naturally when the job is done, and only use once, so you should use it in such situations. The .stopService(intentService) method will not work with the IntentService. Moreover, it is difficult for you to use the application’s UI to interact with the IntentService.

Create SimpleIntentService project.

  • Name: SimpleIntentService
  • Package name: org.o7planning.simpleintentservice


Interface design :


activity_main. xml





    

    

    

    

Create IntentService by right-clicking to a package, and select:

  • New > Service > Service (IntentService)



You can see SimpleIntentService has been declared with AndroidManifest.xml:

* * AndroidManifest. xml * *





    
        

        ...
    


SimpleIntentService has been created, it is also registered with AndroidManifest.xml, code generated  is a suggestion for you to write a IntentService, you can erase the code generated.

SimpleIntentService.java


package org.o7planning.simpleintentservice;

import android.app.IntentService;
import android.content.Intent;
import android.os.SystemClock;

public class SimpleIntentService extends IntentService {

    public static volatile boolean shouldStop = false;

    public static final String ACTION_1 ="MY_ACTION_1";

    public static final String PARAM_PERCENT = "percent";

    public SimpleIntentService() {
        super("SimpleIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        // Create Intent object (to broadcast).
        Intent broadcastIntent = new Intent();

        // Set Action name for this Intent.
        // A Intent can perform many different actions.
        broadcastIntent.setAction(SimpleIntentService.ACTION_1);

        // Loop 100 times broadcast of Intent.
        for (int i = 0; i <= 100; i++) {

            // Set data
            // (Percent of work)
            broadcastIntent.putExtra(PARAM_PERCENT, i);

            // Send broadcast
            sendBroadcast(broadcastIntent);

            // Sleep 100 Milliseconds.
            SystemClock.sleep(100);

            if(shouldStop) {
                stopSelf();
                return;
            }
        }

    }
}

MainActivity. java


package org.o7planning.simpleintentservice;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Button buttonStart;
    private Button buttonStop;
    private TextView textViewPercent;

    private ProgressBar progressBar;

    private Intent serviceIntent;

    private ResponseReceiver receiver = new ResponseReceiver();


    // Broadcast component
    public class ResponseReceiver extends BroadcastReceiver {

        // On broadcast received
        @Override
        public void onReceive(Context context, Intent intent) {

            // Check action name.
            if(intent.getAction().equals(SimpleIntentService.ACTION_1)) {
                int value = intent.getIntExtra(SimpleIntentService.PARAM_PERCENT, 0);

                new ShowProgressBarTask().execute(value);
            }
        }
    }

    // Display value for the ProgressBar.
    class ShowProgressBarTask extends AsyncTask {

        @Override
        protected Integer doInBackground(Integer... args) {

            return args[0];
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);

            progressBar.setProgress(result);

            textViewPercent.setText(result + " % Loaded");

            if (result == 100) {
                textViewPercent.setText("Completed");
                buttonStart.setEnabled(true);
            }

        }
    }

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

        this.textViewPercent = (TextView) this.findViewById(R.id.textView_percent);
        this.progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
        this.buttonStart = (Button) this.findViewById(R.id.button_start);
        this.buttonStop = (Button)this.findViewById(R.id.button_stop);

        this.buttonStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttonStartClicked();
            }
        });

        this.buttonStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttonStopClicked();
            }
        });
    }


    // On Resume of MainActivity
    @Override
    protected void onResume() {
        super.onResume();

        // Register receiver with Activity.
        registerReceiver(receiver, new IntentFilter(
                SimpleIntentService.ACTION_1));
    }

    // On Stop of MainActivity
    @Override
    protected void onStop() {
        super.onStop();

        // Unregister receiver with Activity.
        unregisterReceiver(receiver);
    }

    // Method is called when the user clicks on the Start button.
    public void buttonStartClicked( )  {
        this.buttonStart.setEnabled(false);

        this.serviceIntent = new Intent(this, SimpleIntentService.class);

        startService(this.serviceIntent);
    }


    public void buttonStopClicked( )  {
        if(this.serviceIntent!= null)  {
            // stopService(this.serviceIntent) does not work with IntentService(s).

            // Mandatory stopping of an IntentService is not recommended.
            SimpleIntentService.shouldStop = true;
        }
    }

}

Run the application :
And you can see the working principle of this example according to the illustration below :