Development and remote installation of Java service for the Android Devices

Android
by laihiu

Development and remote installation of Java service for the Android Devices

Written by:
Igor Darkov, Software Developer of Device Team, Apriorit Inc.

In this article I’ve described:

How to develop simple Java service for the Android Devices; How to communicate with a service from the other processes and a remote PC; How to install and start the service remotely from the PC. 1. Java Service Development for the Android Devices

Services are long running background processes provided by Android. They could be used for background tasks execution. Tasks can be different: background calculations, backup procedures, internet communications, etc. Services can be started on the system requests and they can communicate with other processes using the Android IPC channels technology. The Android system can control the service lifecycle depending on the client requests, memory and CPU usage. Note that the service has lower priority than any process which is visible for the user.

Let’s develop the simple example service. It will show scheduled and requested notifications to user. Service should be managed using the service request, communicated from the simple Android Activity and from the PC.

First we need to install and prepare environment:

Download and install latest Android SDK from the official web site (http://developer.android.com); Download and install Eclipse IDE (http://www.eclipse.org/downloads/); Also we’ll need to install Android Development Tools (ADT) plug-in for Eclipse.

After the environment is prepared we can create Eclipse Android project. It will include sources, resources, generated files and the Android manifest.

1.1 Service class development

First of all we need to implement service class. It should be inherited from the android.app.Service (http://developer.android.com/reference/android/app/Service.html) base class. Each service class must have the corresponding <service> declaration in its package’s manifest. Manifest declaration will be described later. Services, like the other application objects, run in the main thread of their hosting process. If you need to do some intensive work, you should do it in another thread.

In the service class we should implement abstract method onBind. Also we override some other methods:

onCreate(). It is called by the system when the service is created at the first time. Usually this method is used to initialize service resources. In our case the binder, task and timer objects are created. Also notification is send to the user and to the system log: public void onCreate() { super.onCreate(); Log.d(LOG_TAG, “Creating service”); showNotification(”Creating NotifyService”); binder = new NotifyServiceBinder(handler, notificator); task = new NotifyTask(handler, notificator); timer = new Timer(); } onStart(Intent intent, int startId). It is called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it requires and the unique integer token representing the start request. We can launch background threads, schedule tasks and perform other startup operations. public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Log.d(LOG_TAG, “Starting service”); showNotification(”Starting NotifyService”); timer.scheduleAtFixedRate(task, Calendar.getInstance().getTime(), 30000); } onDestroy(). It is called by the system to notify a Service that it is no longer used and is being removed. Here we should perform all operations before service is stopped. In our case we will stop all scheduled timer tasks. public void onDestroy() { super.onDestroy(); Log.d(LOG_TAG, “Stopping service”); showNotification(”Stopping NotifyService”); timer.cancel(); } onBind(Intent intent). It will return the communication channel to the service. IBinder is the special base interface for a remotable object, the core part of a lightweight remote procedure call mechanism. This mechanism is designed for the high performance of in-process and cross-process calls. This interface describes the abstract protocol for interacting with a remotable object. The IBinder implementation will be described below. public IBinder onBind(Intent intent) { Log.d(LOG_TAG, “Binding service”); return binder; }

To send system log output we can use static methods of the android.util.Log class (http://developer.android.com/reference/android/util/Log.html). To browse system logs on PC you can use ADB utility command: adb logcat.

The notification feature is implemented in our service as the special runnable object. It could be used from the other threads and processes. The service class has method showNotification, which can display message to user using the Toast.makeText call. The runnable object also uses it:

public class NotificationRunnable implements Runnable { private String message = null; public void run() { if (null != message) { showNotification(message); } } public void setMessage(String message) { this.message = message; } }

Code will be executed in the service thread. To execute runnable method we can use the special object android.os.Handler. There are two main uses for the Handler: to schedule messages and runnables to be executed as some point in the future; and to place an action to be performed on a different thread than your own. Each Handler instance is associated with a single thread and that thread’s message queue. To show notification we should set message and call post() method of the Handler’s object.

1.2 IPC Service

Each application runs in its own process. Sometimes you need to pass objects between processes and call some service methods. These operations can be performed using IPC. On the Android platform, one process can not normally access the memory of another process. So they have to decompose their objects into primitives that can be understood by the operating system , and “marshall” the object across that boundary for developer.

The AIDL IPC mechanism is used in Android devices. It is interface-based, similar to COM or Corba, but is lighter . It uses a proxy class to pass values between the client and the implementation.

AIDL (Android Interface Definition Language) is an IDL language used to generate code that enables two processes on an Android-powered device to communicate using IPC. If you have the code in one process (for example, in Activity) that needs to call methods of the object in another process (for example, Service), you can use AIDL to generate code to marshall the parameters.

Service interface example showed below supports only one sendNotification call:

interface INotifyService { void sendNotification(String message); }

The IBinder interface for a remotable object is used by clients to perform IPC. Client can communicate with the service by calling Context’s bindService(). The IBinder implementation could be retrieved from the onBind method. The INotifyService interface implementation is based on the android.os.Binder class (http://developer.android.com/reference/android/os/Binder.html):

public class NotifyServiceBinder extends Binder implements INotifyService { private Handler handler = null; private NotificationRunnable notificator = null; public NotifyServiceBinder(Handler handler, NotificationRunnable notificator) { this.handler = handler; this.notificator = notificator; } public void sendNotification(String message) { if (null != notificator) { notificator.setMessage(message); handler.post(notificator); } } public IBinder asBinder() { return this; } }

As it was described above, the notifications could be send using the Handler object’s post() method call. The NotificaionRunnable object is passed as the method’s parameter.

On the client side we can request IBinder object and work with it as with the INotifyService interface.  To connect to the service the android.content.ServiceConnection interface implementation can be used. Two methods should be defined: onServiceConnected, onServiceDisconnected:

ServiceConnection conn = null; … conn = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder service) { Log.d(”NotifyTest”, “onServiceConnected”); INotifyService s = (INotifyService) service; try { s.sendNotification(”Hello”); } catch (RemoteException ex) { Log.d(”NotifyTest”, “Cannot send notification”, ex); } } public void onServiceDisconnected(ComponentName name) { } };

The bindService method can be called from the client Activity context to connect to the service:

Context.bindService(new Intent(this, NotifyService.class), conn, Context.BIND_AUTO_CREATE);

The unbindService method can be called from the client Activity context to disconnect from the service:

Context.unbindService(conn); 1.3 Remote service control

Broadcasts are the way applications and system components can communicate. Also we can use broadcasts to control service from the PC. The messages are sent as Intents, and the system handles dispatching them, including starting receivers.

Intents can be broadcasted to BroadcastReceivers, allowing messaging between applications. By registering a BroadcastReceiver in application’s AndroidManifest.xml (using <receiver> tag) you can have your application’s receiver class started and called whenever someone sends you a broadcast. Activity Manager uses the IntentFilters, applications register to figure out which program should be used for a given broadcast.

Let’s develop the receiver that will start and stop notify service on request. The base class android.content.BroadcastReceiver should be used for these purposes (http://developer.android.com/reference/android/content/BroadcastReceiver.html):

public class ServiceBroadcastReceiver extends BroadcastReceiver { … private static String

You can also subscribe here to get this site update in your email.
Enter your email address:

Pages: 1 2

Leave a Reply

You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by Yahoo! Answers