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

相关文章

Android协程高级用法大全

《Android协程高级用法大全》这篇文章给大家介绍Android协程高级用法大全,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友跟随小编一起学习吧... 目录1️⃣ 协程作用域(CoroutineScope)与生命周期绑定Activity/Fragment 中手

SpringBoot通过main方法启动web项目实践

《SpringBoot通过main方法启动web项目实践》SpringBoot通过SpringApplication.run()启动Web项目,自动推断应用类型,加载初始化器与监听器,配置Spring... 目录1. 启动入口:SpringApplication.run()2. SpringApplicat

解决Nginx启动报错Job for nginx.service failed because the control process exited with error code问题

《解决Nginx启动报错Jobfornginx.servicefailedbecausethecontrolprocessexitedwitherrorcode问题》Nginx启... 目录一、报错如下二、解决原因三、解决方式总结一、报错如下Job for nginx.service failed bec

Spring Boot项目如何使用外部application.yml配置文件启动JAR包

《SpringBoot项目如何使用外部application.yml配置文件启动JAR包》文章介绍了SpringBoot项目通过指定外部application.yml配置文件启动JAR包的方法,包括... 目录Spring Boot项目中使用外部application.yml配置文件启动JAR包一、基本原理

Android 缓存日志Logcat导出与分析最佳实践

《Android缓存日志Logcat导出与分析最佳实践》本文全面介绍AndroidLogcat缓存日志的导出与分析方法,涵盖按进程、缓冲区类型及日志级别过滤,自动化工具使用,常见问题解决方案和最佳实... 目录android 缓存日志(Logcat)导出与分析全攻略为什么要导出缓存日志?按需过滤导出1. 按

解决若依微服务框架启动报错的问题

《解决若依微服务框架启动报错的问题》Invalidboundstatement错误通常由MyBatis映射文件未正确加载或Nacos配置未读取导致,需检查XML的namespace与方法ID是否匹配,... 目录ruoyi-system模块报错报错详情nacos文件目录总结ruoyi-systnGLNYpe

解决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