Skip to main content

Android Remote Service


This tutorial is to demonstrate usage of AIDL Interface and interacting 2 Android applications through Service. You can get the complete example source code- RemoteService Example and RemoteService Calling Example 

As we all know Android Service concept is good for tasks running in the background. Based on scope of accessibility services are of 2 types- Local and Remote. As the name indicates, Local Service can be accessed only within the process or application which it is part of. On the other hand, Remote Services can be accessed from different process/application and thus it posses inter-application communication use cases e.g. you are running one service to provide Geo Location for Cell ID. So, any application can read the Cell-ID and access your service to get Geo Co-ordinates. 

As the usability increases so as the building blocks for creating Remote Service. The first challenge is to do inter-process communication so that one application running on one process can access services running on another process. To achieve this IPC (Inter Process Communication) Android has provided a concept of AIDL Interface which acts as the communication interface between 2 processes.  

Following section explains steps to create a Remote Service and an Application to call that service- 

Steps to create a Remote Service
1.     Create an AIDL Interface. Define methods which you are planning to expose to client applications. AIDL interface syntax is similar to Java. It supports most of the Java primitive data types and does not need explicit import statements. Though for custom classes you need to add specific import statements.
a)     Create the interface file, PrasRemote.aidl under pras.service.aidl package. I have defined one method sayHello(String name) which I’ll access from client application and pass some name and it will return “Hello [Name]
         package pras.service.aidl;
         interface PrasRemote {
String sayHello(String name);
}  
b)    If there is no syntax error, it will generate a Java file under gen folder pras.service.aidl.PrasRemote.java

2.     Define the implementation of the methods defined in Step 1.
package pras.service;

import android.os.RemoteException;
import pras.service.aidl.PrasRemote;

/**
 * Implementation of AIDL interface method
 *
 * @author prasanta
 */
public class MethodImpl extends PrasRemote.Stub {

      public String sayHello(String name) throws RemoteException {
            return "Hello "+ name;
      }
}

3.     Define the Service.
package pras.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * The actual Service class which will receive remote calls from Clients
 *
 * @author prasanta
 */
public class PrasService extends Service {

      String TAG = "PrasService";
      @Override
      public IBinder onBind(Intent intent) {
            Log.i(TAG, "onBind_________________________");
            //Return Instance of MethodImpl.java which implements AIDL Interface
            return new MethodImpl();
      }
}

4.     Add entries into Manifest for the service defined in Step 3
[service android:name=".PrasService"]
[intent-filter]
            [action android:name="com.my.service.REMOTE_SERVICE"/]
      [/intent-filter]
[/service]
An intent action having value com.my.service.REMOTE_SERVICE need to be used to call this Service from Client Application

Steps to Call the Remote Service-
1.     Create a new Android project. 


2.     Copy the AIDL file i.e. PrasRemote.aidl file into this new Application Project. Please make sure you are keeping the .aidl file in the same package name as you define in RemoteService application i.e. pras.service.aidl Otherwise it might cause java.lang.SecurityException : Binder invocation to an incorrect interface  
3.     Create a Listener class which implements ServiceConnection Interface and handle call backs when connected to Remote Service. ServiceConnection interface has 2 methods- onServiceConnected(ComponentName cmp, IBinder binder) which will get invoked when client is connected to RemoteService and onServiceDisconnected(ComponentName cmp) if unexpectedly it gets disconnected.
onServiceConnected will provide a IBinder instance which will be casted to get instance of the Interface i.e. PrasRemote. Now you can call the method i.e. sayHello() using this instance.


PrasRemote remoteIntf = PrasRemote.Stub.asInterface(binder);
try{
   String remoteMsg = remoteIntf.sayHello("Prasanta");
}catch(RemoteException ex){}  


4.     Define an UI to Bind and Unbind RemoteService. Execute following when user click on “Bind_Remote_Service” button-
RemoteServiceCon serCon = new RemoteServiceCon(this);
Intent intent = new Intent("com.my.service.REMOTE_SERVICE");
bindService(intent, serCon, Context.BIND_AUTO_CREATE);

To unbind-
unbindService(serCon);

Kindly note: bindService() and unbindService() are methods of Context.java

  

Comments

  1. Prasanta, Nice explanation about remote service. Could you explain more about, if i have to share a class object through remote service, i read the class have to extend parcelable class and do some necessary steps. Could you explain about that if you have come across ? thanks, mani

    ReplyDelete
  2. Thanks...!! a lot... i too share some learnings on android.. i am working on a android tablet..good to be friend with you..!!

    ReplyDelete
  3. Is it possible to use AIDL for C++ based native level?

    ReplyDelete
  4. Regarding AIDL for C++ based native:
    Well I never tried that...
    But the probable solution is, using JNI you can attach your C/C++ code. This will be part of your Remote Service Implementation logic. e.g. in my example, sayHello() can use a Native C/C++ method call.
    You can use NDK to create C/C++ and Java integrated APK.
    hope it helps!

    ReplyDelete
  5. Prasanta, thanks; I'd been battling this a long time, I was sure I'd tried to get that aidl into my client package as you described before but I must have had something else wrong at the same time.
    Anyway, it looks like my test is working now. And, I see, you know about C++ on Android - my primary lang - so I might be back to question you on that.
    Many thanks
    Steve

    ReplyDelete
  6. Thanks Buddy... It was great help. I was trying to work it out properly for last 3 days

    ReplyDelete
  7. Nice page, thanks. What is the difference if doing the same with Messenger instead of aidl? I have a messenger service that I try to bind using your example but get "Unable to start service Intent { act=com.my.service.REMOTE_SERVICE }: not found".

    The client is in different apk and package, I build them by including services build time classes folder in the class path when building client.

    ReplyDelete
    Replies
    1. Please ignore my question. It works the same way and well with AIDL and Messenger, I just had a bug in my code (missed call to super.onCreate() in the services onCreate).

      Thanks for you helpful blog post.

      Delete
  8. Hi Prashanth,
    Nice page, explanations are simple to follow. I was not able to download the code, can you pls shared the code.
    -Thanks & regards,
    Manjunath S

    ReplyDelete

Post a Comment

Popular posts from this blog

Android Parcelable Example

Few days back I had a requirement to send a ArrayList of my Custom Class Objects through Android Intent , I guess most of you also find this requirement now and then. I never thought it can be that tricky. There are built in functions in Intent to send ArrayList of primitive objects e.g. String, Integer, but when it comes to Custom Data Handling Objects, BOOM … you need to take that extra pain! Android has defined a new light weight IPC ( Inter Process Communication ) data structure called Parcel , where you can flatten your objects in byte stream, same as J2SDK’s Serialization concept. So let’s come back to my original requirement, I had a Data Handling class, which groups together a set of information- public class ParcelData {       int id;       String name;       String desc;       String[] cities = {"suwon", "delhi"}; } I want an ArrayList<ParcelData> of Data Handling objec...

Call Control in Android

This tutorial is for those who want to control Phone Call in Android OS. Programmatic approach to Accept or Reject call without user intervention. Kindly note, this approach uses Java Reflection to call methods of an internal class of Android Telephony Framework and might not work with all versions of Android OS. The core concept has been explained in this Android open code . 1st thing 1st, Give the permission . You need to define 3 User Permissions to handle call related functionality- android.permission.READ_PHONE_STATE android.permission.MODIFY_PHONE_STATE (For answerRingingCall() method) android.permission.CALL_PHONE (For endCall() method) Define a Receiver... Create a Receiver which accepts broadcasts with intent action android.intent.action.PHONE_STATE, define following in the Manifest- [receiver android:name=".PhoneCall"]         [intent-filter]             [action android:name="android.in...

Android Looper and Toast from WorkerThread

Have you ever tried to launch Android Toast message from worker thread? Probably you are wondering why the heck it is giving this error- java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() In this article we are going to explore reason behind the above exception and try to understand how Looper works in Android. At the end, I am going to explain one approach to run Toast from a worker thread, but before that we need to understand how Looper works. If you already know in/out of Looper, you can skip below section and directly move to the solution part. Looper is a very basic wrapper class which attach a MessageQueue to a Thread and manage this queue. MessageQueue is a structure to sequentialize simultaneous processing requests of a Thread.  In Android, message/request processing classes like Handler uses Looper to manage their respective MessageQueue. Looper = Thread + MessageQueue Android Looper Life Cycle: As you can see in the abo...

Overlay on Android Layout

This will help you to create custom Layout and add Overlay on a LinearLayout. The concept can be reused on other Layout classes i.e. RelativeLayout, FrameLayout etc. I have added a popup Selection Palette, containing "Map Pin" and "List" icons. You can minimize the popup by clicking on the section in Green on the left side bottom corner of the screen.   How can I do that- You need to follow 4 steps- 1. Override LinearLayout Create a Class MyLinearLayout.java which should overwrite LinearLayout 2. Drawing You need to overwrite dispatchDraw (Canvas canvas) method. It gives control to the whole screen. Make sure you set android:layout_height="fill_parent" for the associated layout definition in XML. You can draw anything and anywhere on the canvas. dispatchDraw (Canvas canvas) gets called only after underlying views are drawn, so whatever you draw comes in the foreground.   3. Event Handling You need to overwrite dispatchTouchEvent (MotionEvent e...

Android Custom TextView

Have you ever tried to add custom behavior to in-build Android Text View or create custom attributes? If yes, this article is going to help you. Here we'll create Single Custom TextView with support for custom attributes to display First and Last Name in different font and colors. During this process we'll learn following topics- 1. How to override default Views in Android 2. How to define custom Layout Attributes in Android So, Let's get started... Following sections explains necessary changes required in Java code and XML layout files. Create Custom Text View (MyTextView.java) 1. Override Android's default TextView   2. Implement Constructors. If you want custom attributes, override Constructor having Attributes in argument. 3. Override onMeasure(): Calculate required width and height, based on Text Size and selected Font. Once calculation is complete, set updated measure using setMeasuredDimension (reqWidth, reqHeight) Note: It’s really important to define the corr...

Google SpreadSheet Library for Android

You might have already tried using Google's GData Lib to access SpreadSheet from Android, and after few hours of try, you start Google for any alternate solution. I have also spent number of hours without any solution. So, I have developed SpreadSheet client Lib [ works on Android :-) ] and ideally work on any Java platform- http://code.google.com/p/google-spreadsheet-lib-android/ Latest version: 2.1 (Added support for List Feed. Please visit above link to get more info.) Supported Features: 1. Create/Delete Spreadsheet 2. List all stored Spreadsheets 3. Add/Delete WorkSheet into/from a given SpreadSheet 4. List all Worksheets of a given Spreadsheet 5. Add Records into WorkSheet/SpreadSheet (It supports Table based record handling) 6. Retrieve Record from WorkSheet/SpreadSheet ( Structured Query support) 7. Retrieve Record as List Feed from Worksheet 8. Update/Delete Records 9. Share ShreadSheet with user/group/domain. 10. Conditional data retrieval- ...

Android Fragment

Fragment is being hanging out since Andriod 3.0, but with the release of 4.0, it has become an obvious choice for Android Application development for both Tabs and Smart phones. Few people think, fragment is a " Superman " which can add any kind of UI layout/style/decoration. But that is not true, rather than being an UI layout or decoration enhancer, Fragment is a very important concept to manage segments of your UI component code base . Prior to Fragment, developers were able manage UI flow only at the Activity level. All UI components were Views (mentioned in XML layout and part of Activity) and there was no way to manage these components separately. As a result all view management code were in a single file i.e. Activity class. With fragment approach, we can now remove View management code from Activity and place them in their respective Java classes. So, a pretty neat approach for code management. Here I'll explain various concepts of Fragment with an example appli...

HashMap Internal

I always wanted to implement the logic behind the famous data structure of Java , HashMap and here it comes. Though it’s not the complete implementation considering all optimization scenarios, but it will highlight the basic algorithm behind the HashMap . So let’s start, this implementation will use my LinkedList implementation (Reason: for this implementation I thought to write everything from the scratch apart from primitive data types. Sounds weird? May be ;-) ). You may refer my earlier post on LinkedList , as I’m going to use it. HashMap is a key-value pair data structure, where you retrieve value by passing key. To optimize the search of key, a concept of Bucket (an Array of Java Objects) has been introduced. This is used, so that if search hits this Bucket , corresponding value element is instantly retrieved, otherwise it iterates sequentially through the Linked List associated with each Bucket element. So you can say if all HashMap elements get fit into the Bucket, retrieving...

Accessing Yahoo Finance API

Since last few days I was wondering the right set of Web Service to read Country wise Stock Exchange index information . I found a bunch of scattered information, but no straight forward answer. It seems there are not many "reliable" and "flexible" options and Yahoo Finance is one of the top of this class. Though Yahoo Finance is very powerful, some how its very less documented and it seems Yahoo doesn't care much about this wonderful web service and expect Developers to do some kind of "hacking". The only online resource that I (and most of you as well ) found is one 3rd party web site- http://www.gummy-stuff.org/Yahoo-data.htm and it seems they know much more than what Yahoo dose..;-) Anyway let me continue and share my experience and information to help budding developer who wants to use Yahoo Finance Web Service in their Mobile, Web o r Desktop s olution. There are 2 set of APIs to access Yahoo Finance details- YQL based Web Service : Th...

Eclipse EGIT, Download Code, Attach Framework code & Debug

This article explains procedure to download Android source (few important Apps and Framework base code) using Eclipse EGit plugin and then attach framework code to debug important framework classes (e.g. Activity etc.). Install EGit Download Source from GIT Repository Attach Framework code Debug Download EGit Plug-in EGit is a GIT plugin for Eclipse which helps to mange GIT clone, Check-ins, Sync etc. from your Eclipse workspace. Eclipse (Version: 3.7.x) -> Help -> Install New Software -> "Add" - " http://download.eclipse.org/egit/updates ". Once the plug-in installation is successful, you'll find a new Eclipse View perspective- "Git Repository Exploring"    Download Android source To download code from Android GIT repository, we need to create "local Git clone". Each local clone is associated with Remote Clone URL.   https://android.googlesource.com/ lists Git Repository URLs for different sections of An...