Tuesday, December 29, 2009

Adding a system server to the Android framework

Following our other posts about booting and the system server, here are some more details of how to add a service to the system server.

It should be noted that extending the system server and other framework features is not recommended, as the code requires to be ported to future releases of the framework.
The most common reason for adding a system server would be for supporting proprietary hardware.

Design considerations
There are a few questions to be answered before implementing a system server, such as threads needed, application interfaces, and hardware interfaces. It's no easy task specifying your server design, but considering the following will hopefully help you out:
1. How frequently will the server run? If the server is only needed occasionaly, it might very well run within the system server context, even though the most common way is give it its own thread. A typical infrequent server is the Headset observer, which will only run when a headset is connected or removed.
2. How is the hardware accessed? Standard hardware could be accessible through device file access and file observers, but the best solution is no doubt to implement a HAL library. The HAL makes it easier to port your server to other hardware, and also makes it possible to run some functionality in native threads if needed.
3. Application interfacing? It is sometimes possible to get away with using intents and implementing your server as a receiver, but for anything but the simplest requests, you will no doubt have to use aidl.
4. Extending the framework? If you want to make your new interface visible to the applications, you will have to update the api description and build your own sdk. (That is easily done with "make update-api", followed by "make sdk".) However, if you only want the your nifty features to be accessible from your own proprietary applications, you should make use of the javadoc @hide-option for your interface.
5. Is there another way? Adding your own server adds migration work for new releases of the framework. To minimise files added, it's easy to be tempted to alter existing services instead of adding your own. That is fine to do, but keep in mind that if some functionality changes, third-party applications may not work anymore. Again, if your server will only be accessed from a proprietary application and not publicly available, consider adding the code to the application instead.

Code sample
Following is an example of a proprietary service, that knows how to set a value. For simplicity, the code is just added to the framework. For a production implementation, the code should go into the vendor directory.

Specifying the interface.
This example uses aidl, so the first step is to add an interface definition file:
frameworks/base/core/java/android/os/IEneaService.aidl
package android.os;

interface IEneaService {
  /**
  * {@hide}
  */
  void setValue(int val);
}

The interface file will need to be added to the build system:
frameworks/base/Android.mk
Add the following around line 165 (the end of the list of SRC_FILES):
core/java/android/os/IEneaService.aidl \


Implementing the server
The service spawns a worker thread that will do all the work, as part of the system server process. Since the service is created by the system server, it will need to be located somewhere where the system server can find it.
frameworks/base/services/java/com/android/server/EneaService.java
package com.android.server;

import android.content.Context;
import android.os.Handler;
import android.os.IEneaService;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.util.Log;

public class EneaService extends IEneaService.Stub {
  private static final String TAG = "EneaService";
  private EneaWorkerThread mWorker;
  private EneaWorkerHandler mHandler;
  private Context mContext;

  public EneaService(Context context) {
    super();
    mContext = context;
    mWorker = new EneaWorkerThread("EneaServiceWorker");
    mWorker.start();
    Log.i(TAG, "Spawned worker thread");
  }

  public void setValue(int val)
  {
    Log.i(TAG, "setValue " + val);
    Message msg = Message.obtain();
    msg.what = EneaWorkerHandler.MESSAGE_SET;
    msg.arg1 = val;
    mHandler.sendMessage(msg);
  }

  private class EneaWorkerThread extends Thread{
    public EneaWorkerThread(String name) {
      super(name);
    }

    public void run() {
      Looper.prepare();
      mHandler = new EneaWorkerHandler();
      Looper.loop();
    }
  }

  private class EneaWorkerHandler extends Handler {
    private static final int MESSAGE_SET = 0;

    @Override
    public void handleMessage(Message msg) {
      try {
        if (msg.what == MESSAGE_SET) {
          Log.i(TAG, "set message received: " + msg.arg1);
        }
      } catch (Exception e) {
        // Log, don't crash!
        Log.e(TAG, "Exception in EneaWorkerHandler.handleMessage:", e);
      }
    }
  }
}

You may want to add to the log printouts the thread id or name just to visualise which thread the code is executing in.

All that's left to do now is to type make to build the repository, and then start up the emulator. Using logcat, you will find the message saying that the thread has been spawned.


Test program
You probably want to test your service as well. For this you can create a "Hello World" activity using the project wizard. Place the project in the vendor/enea directory.

In the main activity class of your test program, add the following lines to onCreate()
IEneaService em = IEneaService.Stub.asInterface(ServiceManager.getService("EneaService"));
try {
  em.setValue(7); // Any value would do, really.
} catch (Exception e) {
  e.printStackTrace();
}

You will also need to import android.os.IEneaService and of course add an apropriate Android.mk to build your test program.

Start your test program and look in the log. You should now find the "set value"-messages.

Cheers
Robert

Monday, December 21, 2009

Howto setup a android project in Eclipse that access both Java and C/C++ code

If you follow the instructions on http://source.android.com/using-eclipse you will only have a Java project and will only see the C/C++ project files as 2:nd class citizens without any indexing. I will propose a another solution that will combine the ideas from http://lorinc.blogspot.com/2006/10/how-to-mix-java-and-c-code-in-singe.html.
1. Copy the already available Java setup
$ cd <your mydroid folder>
$ cp development/ide/eclipse/.classpath .
# You might need to make the copy writable (describe on android.com) 
$ chmod u+w .classpath 
2. From Eclipse create a new C++ project File -> New -> Other, select C/C++ -> C++ Project give it a project name and uncheck "Use default location"
and give it the path to your directory (often called the mydroid dir)
Select Project Type: "Makefile project" -> "Empty Project", let the "-- Other Toolchain" be selected and press "Finish"

3. Add in Java to the same project
Close Eclipse as you will edit a file it holds open and will overwrite otherwise Now a /.project file has been created open it in a text editor and add the following:
<buildCommand>
    <name>org.eclipse.jdt.core.javabuilder</name>
    <arguments></arguments>
</buildCommand>
and
<nature>org.eclipse.jdt.core.javanature</nature>
as described here:
<?xml version="1.0" encoding="UTF-8"?>
<projectdescription>
    <name>android zoom2</name>
    <comment></comment>
    <projects>
    </projects>
    <buildspec>
------------------------------- below is added 
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
     <arguments>
     </arguments>
        </buildCommand>
------------------------------- end of the added stuff 
        <buildcommand>
            <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
            <triggers>clean,full,incremental,</triggers>
...
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.cdt.core.cnature</nature>
 <nature>org.eclipse.cdt.core.ccnature</nature>
  <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
 <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
------------------------------- below is added 
 <nature>org.eclipse.jdt.core.javanature</nature>
------------------------------- end of the added stuff 
    </natures>
...
Now start eclipse again, now the Java classes are available in "Project Explorer" view and C/C++ files in "C/C++ Projects" view.

One problem remain when you build it will use "make all" and that will not work and need to be changed to "make" this can be done if you right-click on the project and select "Properties"
In the "Properties" window select "C/C++ Build" and click on the "Behaviour" tab and remove "all" from all the places where available.

I still used the java heap enlargement in eclipse.ini from the first link by changing the numbers in eclipse.ini to the numbers below:
-Xms128m
-Xmx512m
-XX:MaxPermSize=256m

The standard eclipse from Ubuntu 9.10 (installed from synaptic) uses this file /usr/lib/eclipse/eclipse.ini you need to be root to edit it e.g.

$ sudo gedit /usr/lib/eclipse/eclipse.ini

/Zingo

2010-12-08 Edit: removed wrongly formated spaces around < and >

Thursday, December 3, 2009

Ubuntu 9.10, Java 5 and the Android Open Source Project

Currently there is an issue with building the Android Open Source project on Ubuntu 9.10 Karmic Koala, or more specific with the Java 5 support. Java 5 was obsoleted by Sun on October 30 2009 and is not part of the Ubuntu 9.10 distribution. However there is still a need to use Java 5 for building Android since Java6 is not yet supported. There are two methods to get Java5 working on Ubuntu 9.10.

Method 1 - download and install from Sun
This method will let you install the Java5 JDK in a separate directory and add it to the path when

Download the Java5 JDK for Linux from http://java.sun.com/javase/downloads/5u21/jdk
This is a binary file that you should save to a suitable location like ~/tools
In order to make i executable chmod the file as
$ chmod 777 jdk-1_5_0_21-linux-i586.bin
and run it
$ ./jdk-1_5_0_21-linux-i586.bin
This will install the jdk to the current directory.
To use the JDK5 tools you need to add it first in the path before building the Android Open Source Project
$ export PATH=~/tools/jdk1.5.0_21/bin:$PATH
This allows you to remove the JDK5 from the path when not building Android and use the standard Java settings instead.

Method 2 - use the Ubuntu 9.04 repositories to get Java5
This method adds the Jaunty repositories and installs Java5 as the default java setting in the system. Open the sources file (/etc/apt/sources.list) for editing, as root
$ sudo gedit /etc/apt/sources.list
and add:
deb http://us.archive.ubuntu.com/ubuntu/ jaunty multiverse
deb http://us.archive.ubuntu.com/ubuntu/ jaunty-updates multiverse

save the file and close gedit. Next sync your sources by running
$ sudo apt-get update
and install
$ sudo apt-get install sun-java5-jdk
To set the system to use Java 5 you need to update your java alternatives by running
$ sudo update-alternatives --config java
Choose java-1.5.0-sun and you should be done.

Hopefully the Android Open Source Project will build with Java 6 shortly but the above solutions should get you going with platform work on Ubuntu 9.10.