做系统开发,有时候需要自己定义一些接口供App使用, 同时为了方便维护管理,就会需要自己建立一个服务,把新的功能集中在一起。下面就是新建一个系统服务的基本步骤。
frameworks/base/core/java/android/app/IDemoManager.aidl
package android.app;
interface IDemoManager
{
int getCpuTemperature();
}
frameworks/base/services/core/java/com/android/server/DemoManagerService.java
package com.android.server;
import android.app.IDemoManager;
import android.content.Context;
import android.util.Slog;
public class DemoManagerService extends IDemoManager.Stub {
private Context mContext;
public DemoManagerService(Context context) {
mContext = context;
Slog.d("Demo", "Construct");
}
@Override
public int getCpuTemperature() {
return 100; // Test code
}
}
frameworks/base/core/java/android/app/DemoManager.java
package android.app;
import android.content.Context;
import android.os.RemoteException;
import android.util.Slog;
public class DemoManager {
Context mContext;
IDemoManager mService;
public DemoManager(Context context, IDemoManager service) {
mContext = context;
mService = service;
}
public int getCpuTemperature() {
if (mService != null) {
try {
return mService.getCpuTemperature();
} catch (RemoteException e) {
Slog.e("Demo", "RemoteException " + e);
}
}
return -1;
}
}
frameworks/base/Android.mk
LOCAL_SRC_FILES += \
core/java/android/app/IDemoManager.aidl \
frameworks/base/core/java/android/content/Context.java
public static final String DEMO_SERVICE = "demo";
frameworks/base/core/java/android/app/SystemServiceRegistry.java
registerService(Context.ORISLINK_SERVICE, DemoManager.class,
new CachedServiceFetcher<DemoManager>() {
@Override
public DemoManager createService(ContextImpl ctx) {
IBinder b = ServiceManager.getService(Context.DEMO_SERVICE);
return new DemoManager(ctx, IDemoManager.Stub.asInterface(b));
}});
frameworks/base/services/java/com/android/server/SystemServer.java
try {
ServiceManager.addService(Context.DEMO_SERVICE, new DemoManagerService(context));
} catch (Throwable e) {
Slog.e("Demo", "Failed to start Demo Service " + e);
}
make update-api
更新接口。然后再整编刷机。
device/qcom/sepolicy/msm8937/service.te
type demo_service, system_api_service, system_server_service, service_manager_type;
device/qcom/sepolicy/msm8937/service_contexts
demo u:object_r:demo_service:s0
```java
import android.app.DemoManager;
DemoManager om = (DemoManager) getSystemService(Context.DEMO_SERVICE);
Log.d(TAG, "Current temperature is " + om.getCpuTemperature());
```
最终log打印出100,服务添加完成。
个人博客
http://wossoneri.github.io/2018/09/15/Androidcreate-system-service/
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。