提到开机启动的Service,在android平台中有很多方式,今天要讲的是传统的在Framework层添加一个Service,并启动它,功能很简单,主要是这当中涉及的各个层面的层次结构,从而学会如何自己添加Service。
1)在framework相关目录创建aidl文件(frameworks/base/core/java/android/os),比如ITestService.aidl
编辑如下内容:
package android.os;
interface ITestService {
void setVal(int val);
int getVal();
}
2)修改frameworks/base/Android.mk,添加上一步的文件
--- a/frameworks/base/Android.mk
+++ b/frameworks/base/Android.mk
@@ -163,6 +163,7 @@ LOCAL_SRC_FILES += \
core/java/android/os/ISchedulingPolicyService.aidl \
core/java/android/os/IUpdateLock.aidl \
core/java/android/os/IUserManager.aidl \
+ core/java/android/os/ITestService.aidl \
core/java/android/os/IVibratorService.aidl \
core/java/android/service/notification/INotificationListener.aidl \
core/java/android/print/ILayoutResultCallback.aidl \
4)进入frameworks/base/services/java/com/android/server目录,创建TestService.java源文件,编辑如下内容:
package com.android.server;
import android.content.Context;
import android.os.ITestService;
import android.util.Slog;
public class TestService extends ITestService.Stub {
private static final String TAG = "TestService";
TestService() {
init_native();
}
public void setVal(int val) {
setVal_native(val);
}
public int getVal() {
return getVal_native();
}
private static native boolean init_native();
private static native void setVal_native(int val);
private static native int getVal_native();
};
5)修改SystemServer.java,开机启动该Service,在initAndLoop方法中,添加:
try {
Slog.i(TAG, "Test Service");
ServiceManager.addService("test", new TestService());
} catch (Throwable e) {
Slog.e(TAG, "Failure starting Test Service", e);
}