SERVICE

A service is a component that runs in the background without needing to interact with the user and it works even if application is destroyed.

Service can take  two states :

  • Start Service : Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.
  • Bind Service : 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).

For starting a service:

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

For stopping a service :

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

Example :

When service  is started, MediaPlayer is started and selected song is played. When service is destroyed, MediaPlayer is stopped and all the resources are released. 
MyService.java

public class MyService extends Service {

    MediaPlayer player;

    @Override
    public void onCreate() {
        super.onCreate();
    }

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

        player = new MediaPlayer();
        String songName = intent.getStringExtra("keySong");
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+songName;

        try{
            player.setDataSource(path);
            player.prepare();
            player.start();   //player started
        }catch (Exception e){

        }
	 return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
       
        player.stop();
        player.release();
    }

    @Override
    public IBinder onBind(Intent intent) {
	 return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
}

Leave a comment