Android 自定义系统服务初始化流程详解
Android 自定义系统服务初始化流程详解
1. 概述
自定义系统服务的初始化是一个系统化的过程,涉及多个组件和阶段的协同工作。下面是完整的初始化流程图和详细说明:
▼mermaid复制代码flowchart TD A[定义AIDL接口] --> B[实现服务Stub] B --> C[创建SystemService] C --> D[在SystemServer中注册] D --> E[Context中添加常量] E --> F[权限配置] F --> G[SELinux策略] G --> H[构建配置] H --> I[系统启动时初始化] I --> J[启动阶段回调] J --> K[服务就绪]
2. 详细初始化流程
2.1 定义服务接口 (AIDL)
首先创建AIDL接口文件,这是定义服务契约的基础:
▼java复制代码// frameworks/base/core/java/android/os/ICustomService.aidl package android.os; import android.annotation.Nullable; import android.annotation.NonNull; /** * @hide Custom service interface for advanced system operations */ interface ICustomService { // 示例方法:设置配置值 boolean setConfiguration(in String key, in String value); // 示例方法:获取配置值 String getConfiguration(in String key); // 示例方法:执行特定操作 int performOperation(in int operationId); }
2.2 实现服务核心逻辑
创建服务的具体实现,继承自Stub类:
▼java复制代码// frameworks/base/services/core/java/com/android/server/CustomService.java package com.android.server; import android.content.Context; import android.os.ICustomService; import android.util.Slog; import android.util.ArrayMap; import java.util.Map; public class CustomService extends ICustomService.Stub { private static final String TAG = "CustomService"; private final Context mContext; private final Map<String, String> mConfigurations = new ArrayMap<>(); // 单例实例 private static CustomService sInstance; public CustomService(Context context) { mContext = context; sInstance = this; Slog.i(TAG, "CustomService initialized"); // 初始化默认配置 initializeDefaultConfigurations(); } public static CustomService getInstance() { return sInstance; } private void initializeDefaultConfigurations() { mConfigurations.put("timeout", "5000"); mConfigurations.put("retry_count", "3"); mConfigurations.put("debug_mode", "false"); } @Override public boolean setConfiguration(String key, String value) { // 权限检查 mContext.enforceCallingOrSelfPermission( android.Manifest.permission.MANAGE_CUSTOM_SERVICE, "Requires MANAGE_CUSTOM_SERVICE permission"); if (key == null || value == null) { Slog.w(TAG, "setConfiguration: null key or value"); return false; } mConfigurations.put(key, value); Slog.d(TAG, "Configuration set: " + key + " = " + value); return true; } @Override public String getConfiguration(String key) { // 权限检查 mContext.enforceCallingOrSelfPermission( android.Manifest.permission.USE_CUSTOM_SERVICE, "Requires USE_CUSTOM_SERVICE permission"); return mConfigurations.get(key); } @Override public int performOperation(int operationId) { // 权限检查 mContext.enforceCallingOrSelfPermission( android.Manifest.permission.MANAGE_CUSTOM_SERVICE, "Requires MANAGE_CUSTOM_SERVICE permission"); Slog.i(TAG, "Performing operation: " + operationId); // 执行具体操作逻辑 switch (operationId) { case 1: return operation1(); case 2: return operation2(); default: Slog.w(TAG, "Unknown operation ID: " + operationId); return -1; } } private int operation1() { // 操作1的具体实现 return 100; } private int operation2() { // 操作2的具体实现 return 200; } // 系统启动阶段回调 public void onSystemReady() { Slog.i(TAG, "System is ready, performing final initialization"); // 系统就绪后的初始化操作 } // 启动完成回调 public void onBootCompleted() { Slog.i(TAG, "Boot completed, starting background operations"); // 启动后台任务等 } }
2.3 创建SystemService包装器
为了更好的集成到系统服务生命周期中,创建SystemService包装器:
▼java复制代码// frameworks/base/services/core/java/com/android/server/CustomSystemService.java package com.android.server; import android.content.Context; import android.util.Slog; import com.android.server.SystemService; public class CustomSystemService extends SystemService { private static final String TAG = "CustomSystemService"; private final CustomService mCustomService; public CustomSystemService(Context context) { super(context); mCustomService = new CustomService(context); Slog.i(TAG, "CustomSystemService created"); } @Override public void onStart() { Slog.i(TAG, "Publishing CustomService"); publishBinderService(Context.CUSTOM_SERVICE, mCustomService); publishLocalService(CustomService.class, mCustomService); } @Override public void onBootPhase(int phase) { Slog.d(TAG, "Boot phase: " + phase); if (phase == PHASE_SYSTEM_SERVICES_READY) { // 系统服务就绪阶段 mCustomService.onSystemReady(); } else if (phase == PHASE_BOOT_COMPLETED) { // 启动完成阶段 mCustomService.onBootCompleted(); } } @Override public void onStartUser(int userHandle) { Slog.i(TAG, "Starting for user: " + userHandle); // 用户启动时的处理 } @Override public void onUnlockUser(int userHandle) { Slog.i(TAG, "Unlocking user: " + userHandle); // 用户解锁时的处理 } @Override public void onStopUser(int userHandle) { Slog.i(TAG, "Stopping user: " + userHandle); // 用户停止时的处理 } }
2.4 在SystemServer中注册服务
在SystemServer的适当阶段启动自定义服务:
▼java复制代码// frameworks/base/services/java/com/android/server/SystemServer.java public final class SystemServer { // ... private void startBootstrapServices() { // ... 其他引导服务 // 启动自定义服务(如果需要早期启动) try { traceBeginAndSlog("StartCustomService"); mSystemServiceManager.startService(CustomSystemService.class); traceEnd(); } catch (Throwable e) { reportWtf("starting CustomService", e); } } private void startOtherServices() { // ... 其他服务 // 或者在这里启动(如果不需要早期启动) try { traceBeginAndSlog("StartCustomService"); mSystemServiceManager.startService(CustomSystemService.class); traceEnd(); } catch (Throwable e) { reportWtf("starting CustomService", e); } // ... } }
2.5 在Context中添加服务常量
▼java复制代码// frameworks/base/core/java/android/content/Context.java public abstract class Context { // ... /** * Use with {@link #getSystemService} to retrieve a {@link android.os.ICustomService} * for managing custom system operations. * * @see #getSystemService * @hide */ public static final String CUSTOM_SERVICE = "custom_service"; // ... }
2.6 添加权限定义
▼xml复制代码<!-- frameworks/base/core/res/AndroidManifest.xml --> <permission android:name="android.permission.MANAGE_CUSTOM_SERVICE" android:protectionLevel="signature|privileged" android:label="@string/permlab_manageCustomService" android:description="@string/permdesc_manageCustomService" /> <permission android:name="android.permission.USE_CUSTOM_SERVICE" android:protectionLevel="normal" android:label="@string/permlab_useCustomService" android:description="@string/permdesc_useCustomService" />
2.7 添加SELinux策略
▼selinux复制代码# device/yourvendor/yourdevice/sepolicy/common/service_contexts custom_service u:object_r:custom_service:s0 # device/yourvendor/yourdevice/sepolicy/common/service.te type custom_service, system_api_service, system_server_service, service_manager_type; # device/yourvendor/yourdevice/sepolicy/common/system_server.te allow system_server custom_service:service_manager { add find }; allow system_server custom_service:binder { call transfer }; # device/yourvendor/yourdevice/sepolicy/common/your_app.te allow your_app custom_service:service_manager find; allow your_app custom_service:binder call;
2.8 构建配置
在对应的Android.bp或Makefile中添加构建配置:
▼bp复制代码// frameworks/base/Android.bp android_library { name: "custom-service", srcs: [ "services/core/java/com/android/server/CustomService.java", "services/core/java/com/android/server/CustomSystemService.java", ], libs: [ "android.app", "android.hardware", ], static_libs: [ "services.core", ], }
3. 初始化阶段详解
3.1 阶段1:类加载和实例化
▼java复制代码// SystemServiceManager启动服务时发生: CustomSystemService service = new CustomSystemService(context); // -> 创建CustomSystemService实例 // -> 创建CustomService实例 // -> 执行CustomService构造函数中的初始化
3.2 阶段2:服务发布
▼java复制代码// onStart()方法被调用时: publishBinderService(Context.CUSTOM_SERVICE, mCustomService); // -> 服务注册到ServiceManager // -> 现在其他进程可以通过ServiceManager.getService("custom_service")获取服务
3.3 阶段3:启动阶段回调
▼java复制代码// 系统启动过程中,不同阶段会调用onBootPhase() onBootPhase(PHASE_SYSTEM_SERVICES_READY); // 系统服务就绪 onBootPhase(PHASE_ACTIVITY_MANAGER_READY); // ActivityManager就绪 onBootPhase(PHASE_THIRD_PARTY_APPS_CAN_START); // 第三方应用可启动 onBootPhase(PHASE_BOOT_COMPLETED); // 启动完成
3.4 阶段4:用户相关回调
▼java复制代码// 多用户相关回调 onStartUser(int userHandle); // 用户启动 onUnlockUser(int userHandle); // 用户解锁 onStopUser(int userHandle); // 用户停止
4. 客户端访问方式
4.1 系统组件访问方式
▼java复制代码// 通过ServiceManager直接访问 ICustomService customService = ICustomService.Stub.asInterface( ServiceManager.getService(Context.CUSTOM_SERVICE)); // 或者通过Context获取 CustomManager customManager = (CustomManager) context.getSystemService( Context.CUSTOM_SERVICE);
4.2 创建CustomManager客户端
▼java复制代码// frameworks/base/core/java/android/os/CustomManager.java package android.os; import android.content.Context; import android.annotation.SystemService; import android.annotation.RequiresPermission; @SystemService(Context.CUSTOM_SERVICE) public class CustomManager { private final ICustomService mService; public CustomManager(Context context, ICustomService service) { mService = service; } @RequiresPermission(android.Manifest.permission.USE_CUSTOM_SERVICE) public String getConfiguration(String key) { try { return mService.getConfiguration(key); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } @RequiresPermission(android.Manifest.permission.MANAGE_CUSTOM_SERVICE) public boolean setConfiguration(String key, String value) { try { return mService.setConfiguration(key, value); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } }
5. 调试和验证
5.1 服务状态检查
▼bash复制代码# 检查服务是否注册 adb shell service list | grep custom # 检查服务运行状态 adb shell dumpsys custom_service # 检查权限设置 adb shell dumpsys package | grep -A5 -B5 custom
5.2 日志监控
▼java复制代码// 在服务中添加详细的日志记录 Slog.d(TAG, "Service method called with params: " + parameters); Slog.w(TAG, "Unexpected condition: " + condition); Slog.e(TAG, "Error occurred: ", exception);
6. 常见问题排查
- 服务未注册:检查SystemServer中添加服务的代码是否正确执行
- 权限拒绝:检查SELinux策略和权限定义
- 绑定失败:检查AIDL接口定义是否一致
- 启动顺序问题:确保服务在依赖的服务之后启动
评论
问答助学
相关内容
0个评论
全部评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
