Creating a Remote Background Service In Android.

How to create a basic Remote Services in Android:

Following article will illustrate how to create a simple basic Remote Service in Android that will run in the background, and which will be triggered by the activity.

Since last so many days I was struggling badly on creating a Remote background service in Android, For the same I found various articles, also went through many blogs, the docs for the android developers etc. Whatever articles I went through, the example given in them had some service task performing, which was confusing me, however I wanted a clear framework and design starting from a strach to implement the background service, and so is this post,

Following article will illustrate the basics of creating a Remote Background Service in Android.

The very first step is to create a new Android Project in Eclipse.

Then add the Service Interface in a '.aidl' file.

AIDL  (Android Interface Definition Language) is similar to the java interface with the method signature defined.

Following are the contents of 'RemoteServiceExample.aidl' file:

package com.example;

interface RemoteServiceExample {
      void doServiceTask();
}

Once after creating above file whenever you build the workspace, Eclipse generates the corresponding java interface, you can see the same in the 'gen' section. Also a care is to be taken that this is the autogenerated file and no need to modify the same.


Following is the code for the Core Service implementation:


package com.example;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder; 
import android.os.RemoteException;
import android.util.Log;


public class CoreRemoteService extends Service{
@Override
public IBinder onBind(Intent arg0) {
Log.d(getClass().getSimpleName(), "onBind()");
return coreRemoteServiceStub;
}  

private Stub RemoteServiceExample.Stub coreRemoteServiceStub = new RemoteServiceExample.Stub() {
public void doServiceTask() throws RemoteException {
/// Write here, code to be executed in background
Log.d(getClass().getSimpleName(),"Hello World From Remote Service!!");
}   
};

@Override 
public void onCreate() {
super.onCreate();
Log.d(getClass().getSimpleName(),"onCreate()");
}

@Override
public void onDestroy() {
super.onDestroy();
Log.d(getClass().getSimpleName(),"onDestroy()");
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(getClass().getSimpleName(), "onStart()");
}
}

Form the above code have a look at the onBind() method, it returns the IBinder object. IBinder will represent the implementation of the remote service.
The implementation of the method of the 'aidl' interface (doServiceTask() in this example) is provided by the Stub class of the RemoteServiceExample.
In the method doServiceTask() will have the list of all the task to be executed while service is running. It can have the other method calls or the Code blocks to be executed. In the example I'm just printing a single line log "Hello World From Remote Service!!".

Now, coming to the main Activity class which will trigger the service, or we can say that the Activity will act as Client which can connect to the above created service. Have a look at the code for the same as follows:

package com.example;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;


public class ExampleRemoteService extends Activity {
RemoteServiceExample remoteServiceExample;
private RemoteServiceConnection conn = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        Intent i = new Intent();        
i.setClassName("com.example", "com.example.CoreRemoteService");
startService(i);
conn = new RemoteServiceConnection(); 
bindService(i, conn, Context.BIND_AUTO_CREATE);        
    }       
    class RemoteServiceConnection implements ServiceConnection {
        public void onServiceConnected(ComponentName className, IBinder boundService ) {    
        remoteServiceExample = RemoteServiceExample.Stub.asInterface((IBinder)boundService);        
        try{
        remoteServiceExample.doServiceTask();
        }catch(RemoteException e){        
        e.printStackTrace();
        }        
          Log.d( getClass().getSimpleName(), "onServiceConnected()" );
        }


        public void onServiceDisconnected(ComponentName className) {          
  Log.d( getClass().getSimpleName(), "onServiceDisconnected" );
        }
    };
    
}

Here I haven't kept any button to explicitly start the service, instead the service is started as the Activity is created.
An object of Intent is created, where the classname of the same is set, and then this object is passed as an argument of startService() method.
The class name set in the Intent is the fully qualified class name of the Class which extends 'Service', here in the example, 'CoreRemoteService' class.
Now the class 'RemoteServiceConnection' which implements 'ServiceConnection' interface is created to establish the connection with the remote service.
The object of this class along with the Intent object is passed as an argument in bindService() method.

Finally, we need to add a reference of the remote service created in Android Manifest file as follows:
<service android:name=".CoreRemoteService">
</service>

Now you are done with creating the remote background service.

As you install the apk and run on an Android Device or Emulator, service Prints in the log "Hello World From Remote Service!!".

Also you can check in your device, Settings>Applications>Running Service, the name of your service in the running services list.

So this was the very basic example of creating a remote background service in Android.

Thats all from my end!

Comments

Popular posts from this blog

How to draw an overlay on a SurfaceView used by Camera on Android?

Create EditText with dropdown in android

Android TCP Connection Chat application