Android Senor Framework (三)SensorService启动

2024-04-18 10:58

本文主要是介绍Android Senor Framework (三)SensorService启动,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

SystemServer 启动SensorService

Zygote启动之后,调用SystemServer的main方法(调用run方法)启动系统服务;

代码路径:

./frameworks/base/services/java/com/android/server/SystemServer.java

SystemServer类中提供的run 方法中,在启动service之前,会加载本地动态库System.loadLibrary(“android_servers”)初始化本地 Native service,过程如下:

/*** The main entry point from zygote.*/
public static void main(String[] args) {new SystemServer().run();
}
public final class SystemServer {private static final String TAG = "SystemServer";private void run() {// Initialize native services.System.loadLibrary("android_servers");// Start services.try {Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");startBootstrapServices();startCoreServices();startOtherServices();}
...
}

在 startBootstrapServices(); 的过程的最后 会调用startSensorService(); 如下:

    private void startBootstrapServices() {
......// The sensor service needs access to package manager service, app ops// service, and permissions service, therefore we start it after them.startSensorService();}

在SystemServer类定义中,定义了本地方法startSensorService 如下:

public final class SystemServer {                                                                                                                                                                                   private static final String TAG = "SystemServer";//......private static native void startSensorService();//......
}

当SystemServer调用run 方法,会通过JNI调用到本地方法;

JNI 访问native 方法

通过对JNI的了解 System.loadLibrary(“android_servers”); 会去查找libandroid_servers.so 这个库文件;

yujixuan@yujixuan:~/prj/SC20_R06_master_0526/code/frameworks$ grep -rn libandroid_servers ./
./base/services/Android.mk:54:LOCAL_MODULE:= libandroid_servers

通过检索可知,加载该本地库,会调用在 base/services/ 下编译库文件的onload函数;即:

代码路径: ./base/services/core/jni/onload.cpp
extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */)
{JNIEnv* env = NULL;jint result = -1;if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {ALOGE("GetEnv failed!");return result;}ALOG_ASSERT(env, "Could not retrieve the env!");register_android_server_ActivityManagerService(env);register_android_server_PowerManagerService(env);register_android_server_SerialService(env);register_android_server_InputApplicationHandle(env);register_android_server_InputWindowHandle(env);register_android_server_InputManager(env);register_android_server_LightsService(env);register_android_server_AlarmManagerService(env);register_android_server_UsbDeviceManager(env);register_android_server_UsbMidiDevice(env);register_android_server_UsbHostManager(env);register_android_server_vr_VrManagerService(env);register_android_server_VibratorService(env);register_android_server_SystemServer(env);
//......return JNI_VERSION_1_4;
}

由上可知,在JNI_OnLoad 中会调用添加若干个 server,没有发现sensor相关的server;

实则它是 SystemServer中,下面是register_android_server_SystemServer内容:

代码路径:./base/services/core/jni/com_android_server_SystemServer.cpp
/** JNI registration.*/
static const JNINativeMethod gMethods[] = {/* name, signature, funcPtr */{ "startSensorService", "()V", (void*) android_server_SystemServer_startSensorService },
};int register_android_server_SystemServer(JNIEnv* env)
{return jniRegisterNativeMethods(env, "com/android/server/SystemServer",gMethods, NELEM(gMethods));
}

可以看到 register_android_server_SystemServer 实际上是注册绑定了 sensor相关的 service启动方法(为啥不直接命名为sensor server,目前还不清楚);

通过method可知,systemServer调用run方法启动 startSensorService,会调用到android_server_SystemServer_startSensorService ; 以下是它的实现:

static void android_server_SystemServer_startSensorService(JNIEnv* /* env */, jobject /* clazz */) {char propBuf[PROPERTY_VALUE_MAX];property_get("system_init.startsensorservice", propBuf, "1");if (strcmp(propBuf, "1") == 0) {// Start the sensor service in a new threadcreateThreadEtc(start_sensor_service, nullptr,"StartSensorThread", PRIORITY_FOREGROUND);}
}

判断属性 “system_init.startsensorservice” 是否存在,如果存在 创建线程"StartSensorThread"(默认被配置了,还找到哪里配置的)

线程内容如下:

static int start_sensor_service(void* /*unused*/) {SensorService::instantiate();return 0;
}

该线程调用SensorService中的instantiate方法,创建了SensorService的实例;

SensorService实现

继续分析SensorService instantiate的创建,首先是看SensorService类的定义:

路径:./frameworks/native/services/sensorservice/SensorService.h
class SensorService :public BinderService<SensorService>,public BnSensorServer,protected Thread
{// nested class/struct for internal useclass SensorEventConnection;public:void cleanupConnection(SensorEventConnection* connection);status_t enable(const sp<SensorEventConnection>& connection, int handle,nsecs_t samplingPeriodNs,  nsecs_t maxBatchReportLatencyNs, int reservedFlags,const String16& opPackageName);status_t disable(const sp<SensorEventConnection>& connection, int handle);status_t setEventRate(const sp<SensorEventConnection>& connection, int handle, nsecs_t ns,const String16& opPackageName);status_t flushSensor(const sp<SensorEventConnection>& connection,const String16& opPackageName);
private:friend class BinderService<SensorService>;// nested class/struct for internal useclass SensorRecord;class SensorEventAckReceiver;struct SensorRegistrationInfostatic char const* getServiceName() ANDROID_API { return "sensorservice"; }SensorService() ANDROID_API;virtual ~SensorService();virtual void onFirstRef();// Thread interfacevirtual bool threadLoop();// ISensorServer interfacevirtual Vector<Sensor> getSensorList(const String16& opPackageName);virtual status_t dump(int fd, const Vector<String16>& args);String8 getSensorName(int handle) const;bool isVirtualSensor(int handle) const;sp<SensorInterface> getSensorInterfaceFromHandle(int handle) const;bool isWakeUpSensor(int type) const;void recordLastValueLocked(sensors_event_t const* buffer, size_t count);static void sortEventBuffer(sensors_event_t* buffer, size_t count);const Sensor& registerSensor(SensorInterface* sensor,bool isDebug = false, bool isVirtual = false);const Sensor& registerVirtualSensor(SensorInterface* sensor, bool isDebug = false);
};

删了一些相对无关的方法及属性后,还有如上内容,没有instantiate方法;

通过类的定义可以发现SensorService 继承了BinderService;BnSensorServer,Thread这三个class; instantiate 是被定义在它的父类BinderService中了;

以下是BinderService的实现:

代码路径:./frameworks/native/include/binder/BinderService.hclass BinderService
{
public:static status_t publish(bool allowIsolated = false) {sp<IServiceManager> sm(defaultServiceManager());return sm->addService(String16(SERVICE::getServiceName()),new SERVICE(), allowIsolated);}static void publishAndJoinThreadPool(bool allowIsolated = false) {publish(allowIsolated);joinThreadPool();}static void instantiate() { publish(); }
......
};

publish()中

sp sm(defaultServiceManager());

可知SensorService::instantiate()在这一过程创建了SensorService并通过addService将自己新创建的SensorService服务添加到Android服务列表里了。

SensorService有一条继承关系如下:

SensorService : public BnSensorServer
BnSensorServer : public BnInterface<ISensorServer>
BnInterface :  public BBinder
BBinder : public IBinder
IBinder : public virtual RefBase 

在Android引用计数系统里,当RefBase的子类对象被第一次强引用时自动调用其onFirstRef方法,所以当第一次使用SensorService,onFirstRef方法将被被自动回调,onFirstRef方法里会创建SensorDevice 用来与HAL层进行交互,后面内容会做分析。

note:Android系统智能指针的设计思路(轻量级指针、强指针、弱指针) 虚继承

void SensorService::onFirstRef() {ALOGD("nuSensorService starting...");SensorDevice& dev(SensorDevice::getInstance());
//......

时序图:

根据以上过程,可绘制绘制出简要的uml时序图,如下:

总结过程:

  1. 系统初始化进程加载,启动SystemServer,Zygote中会执行SystemServier main方法,导致其run方法被调用;
  2. 加载本地库文件, System.loadLibrary("android_servers"); 获取本地方法;
  3. 被加载到的JNI库文件导致JNI_Onload函数被调用;调用本地jni文件
  4. 注册本地方法jniRegisterNativeMethods 数组;
  5. 完成Java 到 C++ 函数绑定,使Java能否访问到C库中的函数;
  6. 启动startBootstrapServices();
  7. 最后调用native方法 native void startSensorService();
  8. JNI文件com_android_server_SystemServer.cpp,绑定的函数数组,由java的startSensorService方法绑定到android_server_SystemServer_startSensorService函数;
  9. C++函数中,start_sensor_service被调用;
  10. 调用SensorService的inistantiate函数(继承父类BinderService得到的);
  11. 调用publish
  12. 创建一个Serivces,通过sm->addService 来添加到android中去; sm->addService( String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated); 其中sm是ServiceManager的引用:sp sm(defaultServiceManager());

这篇关于Android Senor Framework (三)SensorService启动的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/914592

相关文章

解决hive启动时java.net.ConnectException:拒绝连接的问题

《解决hive启动时java.net.ConnectException:拒绝连接的问题》Hadoop集群连接被拒,需检查集群是否启动、关闭防火墙/SELinux、确认安全模式退出,若问题仍存,查看日志... 目录错误发生原因解决方式1.关闭防火墙2.关闭selinux3.启动集群4.检查集群是否正常启动5.

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

Android Paging 分页加载库使用实践

《AndroidPaging分页加载库使用实践》AndroidPaging库是Jetpack组件的一部分,它提供了一套完整的解决方案来处理大型数据集的分页加载,本文将深入探讨Paging库... 目录前言一、Paging 库概述二、Paging 3 核心组件1. PagingSource2. Pager3.

kkFileView启动报错:报错2003端口占用的问题及解决

《kkFileView启动报错:报错2003端口占用的问题及解决》kkFileView启动报错因office组件2003端口未关闭,解决:查杀占用端口的进程,终止Java进程,使用shutdown.s... 目录原因解决总结kkFileViewjavascript启动报错启动office组件失败,请检查of

Linux下在线安装启动VNC教程

《Linux下在线安装启动VNC教程》本文指导在CentOS7上在线安装VNC,包含安装、配置密码、启动/停止、清理重启步骤及注意事项,强调需安装VNC桌面以避免黑屏,并解决端口冲突和目录权限问题... 目录描述安装VNC安装 VNC 桌面可能遇到的问题总结描js述linux中的VNC就类似于Window

linux下shell脚本启动jar包实现过程

《linux下shell脚本启动jar包实现过程》确保APP_NAME和LOG_FILE位于目录内,首次启动前需手动创建log文件夹,否则报错,此为个人经验,供参考,欢迎支持脚本之家... 目录linux下shell脚本启动jar包样例1样例2总结linux下shell脚本启动jar包样例1#!/bin

Android kotlin中 Channel 和 Flow 的区别和选择使用场景分析

《Androidkotlin中Channel和Flow的区别和选择使用场景分析》Kotlin协程中,Flow是冷数据流,按需触发,适合响应式数据处理;Channel是热数据流,持续发送,支持... 目录一、基本概念界定FlowChannel二、核心特性对比数据生产触发条件生产与消费的关系背压处理机制生命周期

Android ClassLoader加载机制详解

《AndroidClassLoader加载机制详解》Android的ClassLoader负责加载.dex文件,基于双亲委派模型,支持热修复和插件化,需注意类冲突、内存泄漏和兼容性问题,本文给大家介... 目录一、ClassLoader概述1.1 类加载的基本概念1.2 android与Java Class

Android DataBinding 与 MVVM使用详解

《AndroidDataBinding与MVVM使用详解》本文介绍AndroidDataBinding库,其通过绑定UI组件与数据源实现自动更新,支持双向绑定和逻辑运算,减少模板代码,结合MV... 目录一、DataBinding 核心概念二、配置与基础使用1. 启用 DataBinding 2. 基础布局

解决Entity Framework中自增主键的问题

《解决EntityFramework中自增主键的问题》:本文主要介绍解决EntityFramework中自增主键的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录Entity Framework中自增主键问题解决办法1解决办法2解决办法3总结Entity Fram