Tuesday, May 31, 2011

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 atricle 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!

Happy Coding!! :-))




Best Car pool Android Application Best Car Pool Application Source Code Download Here



Best Social Network Cordova Ionic Application Best Social Networking Source Code Cordova Ioinc Application Download Here


Best Android Application, Android Restaurant System Best Android Restaurant Application Source code download here


Best Android Application Android Chat Source code download Android Chat Source code download


Best Android Quiz Source Code Download Best Android Quiz Source Code Download here

More and Lots of useful Android source codes here Best Android Source codes download here



11 comments:

Dominik said...
This comment has been removed by the author.
Unknown said...

Nice explanation...Keep it up...

Unknown said...

gud one

Unknown said...

gud

zoso said...

From whatever you have coded, it doesn't seem that you really do implement a "remote" service. Its just a local service isn't it because its still running in the same process as your client "the activity" is running in.

Unknown said...

Nice tutorial !! It helps me lot to solve problems in my project :)
Thanks :)

Unknown said...

@indranil : Do you know how to do with remote service. Can u provide me a good link on that

Barkat said...

How we get current Location of user when he is not accessing my app. Like Background Location and within 2km of user position.


Syam Sundar said...
This comment has been removed by the author.
Syam Sundar said...
This comment has been removed by the author.
Syam Sundar said...

u have any small example with activity and also need to run after restart the device. if killed then automatically start the process.

thanks

Animated Container in Flutter

Please check this flutter video tutorial for detailed example and implementation of Animated Container in Flutter.