指定一个接口
该例使用了AIDL,因此第一步添加一个接口定义文件。
frameworks/base/core/java/android/os/IEneaService.aidl
package android.os;
interface IEneaService {
/**
* {@hide}
*/
void setValue(int val);
}
这个文件将被添加到系统build文件中:
frameworks/base/Android.mk
添加下面的内容在 165行 ( SRC_FILES列的末尾 ):
core/java/android/os/IEneaService.aidl
实现服务器端
服务产生一个工作线程作为系统服务器进程的一部分,将做的一切工作。由于服务是由系统服务创建的,它会需要到系统服务可以找到它的位置。
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);
}
}
}
}
添加系统服务
services/java/com/android/server/SystemServer.java
try {
Log.i(TAG, “Enea Service”);
ServiceManager.addService(Context. ENEA_SERVICE, new EneaService(context));
} catch (Throwable e) {
Log.e(TAG, “Failure starting Enea Service”, e);
}
添加常量值到 Context
./core/java/android/content/Context.java
public static final String ENEA_SERVICE = “enea”;
最后
make update-api
make