LOADING...
03 Feb

Android work with background Service

The AsyncTask which, in its own way, allows to start asynchronous activities to support the user interface. Tasks managed by this class should not be very long, “a few seconds at the most” as the official documentation explicitly states. For long-term or non-permanent jobs, an appropriate Android component must be used, the Service. To use a Service it is necessary to perform two operations:     

  • create a Java class that extends Service or a derivative thereof;     
  • register the service in the manifest with the <service> node   

  <service android: name = “DownloadService” />

The services can be classified into two types, depending on the way they are

started:     the Started services are started using the startService () method. Their particularity is to be executed in the background indefinitely even if the component that started them is terminated. They generally do not offer interaction with the caller and continue until they are stopped with the stopService method or auto-stop with stopSelf ();   Bound services live in a client-server mode. They only make sense if some other component connects to it. They are interrupted when there are no more clients connected to them. We immediately clarify that the services of the two categories are not radically different. What sets them apart is the way they are started and the callback methods implemented within them. The same service can be started in a started or bound manner.

 Service Started are to be pre-set for operations with their own purposes independent of the status of the other applications. You could take care of data updates in the background, downloading files or images, remote synchronization to external servers, etc. Considering that the service Started will remain in the background for a long time, its existence must be justified by the intended purpose.

Service Bounds play the role of support for other applications. Therefore, they do not risk being “forgotten” in the background as it could unfortunately happen to Started but they are not suitable for jobs to be carried out continuously in the background.

An example that allows a quick approach to implement a simple Service :

public class DownloadService extends IntentService
{
 public DownloadService()
 {
 super("DownloadService");
 }
 
 @Override
 protected void onHandleIntent(Intent i)
 {
 while (true){
 Log.i("TEST SERVICE","I DO SOMETHING" );
 try {
 Thread.sleep(15000);
 } 
 catch (InterruptedException e) 
 { } 
 }
 
 @Override
 public void onDestroy()
 {
 Log.i("DESTROY HERE", "DESTROYED");
 }
}

In the activity to start it is enought to write  startService(new Intent(this,LogService.class)) and rember to stop it with stopService(new Intent(this,LogService.class)).