简介
上一节制作了一个传感器的应用,应用程序获取传感器数据代码流程大致如下
//get sensor manager
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
//show sensor list
List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
System.out.println("get sensor list:");
for (Sensor s: sensors) {
System.out.println("name:" + s.getName());
System.out.println("string_type:" + s.getStringType());
System.out.println("vendor:" + s.getVendor());
}
//gyro
Sensor mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
if (mGyroSensor == null) {
System.out.println("gyro sensor is null.");
mViewGyro.setText("gyro sensor is null.");
}
mSensorManager.registerListener(new SensorEventListener() {
long last_ts = 0;
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
String string = "sensor_gyro=(" + new DecimalFormat("0.00").format(sensorEvent.values[0]) + "," + new DecimalFormat("0.00").format(sensorEvent.values[1]) + "," + new DecimalFormat("0.00").format(sensorEvent.values[2]) + ")\nts=" + sensorEvent.timestamp + "\ninterval=" + (sensorEvent.timestamp - last_ts)/1000/1000 + "ms";
last_ts = sensorEvent.timestamp;
//System.out.println(string);
mViewGyro.setText(string);
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
System.out.println("onAccuracyChanged.");
}
},mGyroSensor,sample_type);
源码分析
如上所示,在应用层调用几个常用接口就能够获取到传感器数据了,主要接口包括
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
Sensor mAccSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
mSensorManager.registerListener(xxx);
下面对这四个接口为主线来学习源代码,理解传感器的框架
getSystemService
该接口是一个用来获取系统服务的接口,SensorManager是一个抽象类,为应用层提供传感器接口,SystemSensorManager继承SensorManager实现了这些接口功能,我们来看一下SystemSensorManager的创建.
final class SystemServiceRegistry {
static {
//...
registerService(Context.SENSOR_SERVICE, SensorManager.class,
new CachedServiceFetcher<SensorManager>() {
@Override
public SensorManager createService(ContextImpl ctx) {
return new SystemSensorManager(ctx.getOuterContext(),
ctx.mMainThread.getHandler().getLooper());
}});
//...
}
SystemSensorManager在SystemServiceRegistry的静态初始化块当中,因此在系统初始阶段加载SystemServiceRegistry时,SystemSensorManager就会被创建,来看一下它的构造函数
public SystemSensorManager(Context context, Looper mainLooper) {
synchronized(sLock) {
if (!sNativeClassInited) {
sNativeClassInited = true;
//获取FieldID和MethodID,存gSensorOffsets中.为后续JNI的get/set做准备
nativeClassInit();
}
}
mMainLooper = mainLooper;
mTargetSdkLevel = context.getApplicationInfo().targetSdkVersion;
mContext = context;
//创建Native层的SensorManager.
mNativeInstance = nativeCreate(context.getOpPackageName());
//通过Native层的SensorManager的getSensorList方法,初始化传感器列表,并填充到mFullSensorsList当中.建立sensor和handle之间的映射,存放在mHandleToSensor中.
for (int index = 0;;++index) {
Sensor sensor = new Sensor();
//将Native层的sensor,通过JNI返回到Java层
if (!nativeGetSensorAtIndex(mNativeInstance, sensor, index)) break;
mFullSensorsList.add(sensor);
mHandleToSensor.put(sensor.getHandle(), sensor);
}
}
调用nativeCreate创建Native层的SensorManager,在创建过程中会循环等待SensorService被创建,与其建立binder关系,接着调用SensorSerivce的getSensorList,来获取硬件传感器列表信息.
static jlong
nativeCreate
(JNIEnv *env, jclass clazz, jstring opPackageName)
{
ScopedUtfChars opPackageNameUtf(env, opPackageName);
return (jlong) &SensorManager::getInstanceForPackage(String16(opPackageNameUtf.c_str()));
}
SensorManager& SensorManager::getInstanceForPackage(const String16& packageName) {
Mutex::Autolock _l(sLock);
if (iterator != sPackageInstances.end()) {
sensorManager = iterator->second;
} else {
//创建Native层sensorManager,接着看SensorManager的构造函数
sensorManager = new SensorManager(opPackageName);
//....
sPackageInstances.insert(std::make_pair(opPackageName, sensorManager));
}
return *sensorManager;
}
SensorManager::SensorManager(const String16& opPackageName)
: mSensorList(0), mOpPackageName(opPackageName) {
// okay we're not locked here, but it's not needed during construction
assertStateLocked();
}
status_t SensorManager::assertStateLocked() {
bool initSensorManager = false;
if (mSensorServer == NULL) {
initSensorManager = true;
} else {
// Ping binder to check if sensorservice is alive.
status_t err = IInterface::asBinder(mSensorServer)->pingBinder();
if (err != NO_ERROR) {
initSensorManager = true;
}
}
if (initSensorManager) {
// 等待获取Native层的SensorService被注册,超时时间60*5s
const String16 name("sensorservice");
for (int i = 0; i < 60; i++) {
status_t err = getService(name, &mSensorServer);
if (err == NAME_NOT_FOUND) {
sleep(1);
continue;
}
if (err != NO_ERROR) {
return err;
}
break;
}
class DeathObserver : public IBinder::DeathRecipient {
SensorManager& mSensorManager;
virtual void binderDied(const wp<IBinder>& who) {
ALOGW("sensorservice died [%p]", who.unsafe_get());
mSensorManager.sensorManagerDied();
}
public:
DeathObserver(SensorManager& mgr) : mSensorManager(mgr) { }
};
LOG_ALWAYS_FATAL_IF(mSensorServer.get() == NULL, "getService(SensorService) NULL");
mDeathObserver = new DeathObserver(*const_cast<SensorManager *>(this));
IInterface::asBinder(mSensorServer)->linkToDeath(mDeathObserver);
//通过SensorServer获取传感器列表
mSensors = mSensorServer->getSensorList(mOpPackageName);
size_t count = mSensors.size();
mSensorList =
static_cast<Sensor const**>(malloc(count * sizeof(Sensor*)));
LOG_ALWAYS_FATAL_IF(mSensorList == NULL, "mSensorList NULL");
//将传感器列表存入SensorManager的mSensorList中
for (size_t i=0 ; i<count ; i++) {
mSensorList[i] = mSensors.array() + i;
}
}
return NO_ERROR;
}
上面SensorManager会等待SensorService注册,将它保存在成员变量mSensorServer中.小结一下这一段流程UML图
SensorManager功能都来自于SensorService,它在Android的Sensor框架中占据核心位置,接下来看一下分析一下SensorService的相关代码.
当内核启动后执行init 程序,该程序解析 init.rc文件(zygote包含在init.${ro.zygote}.rc中),rc文件中指定的应用程序在app_main.cpp中,调用AndroidRuntime的start方法,接着通过JNI调用Zyoteinit.java中的main函数,从这里开始追踪.
public static void main(String argv[]) {
//...
if (startSystemServer) {
startSystemServer(abiList, socketName);
}
//...
}
上面代码可知ZygoteInit的main函数执中调用startSystemServer函数,调用forkSystemServer创建系统服务,跳转到SystemServer的main函数
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
//...
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
//...
}
private void startBootstrapServices() {
//...
startSensorService();
//...
}
在 SystemServer 的main函数中,会创建SystemService对象,并调用run方法,在run方法中调用startBootstrapServices(),接着调用Native方法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 thread
createThreadEtc(start_sensor_service, nullptr,
"StartSensorThread", PRIORITY_FOREGROUND);
}
}
static int start_sensor_service(void* /*unused*/) {
SensorService::instantiate();
return 0;
}
static void instantiate() { publish(); }
static status_t publish(bool allowIsolated = false) {
sp<IServiceManager> sm(defaultServiceManager());
return sm->addService(
String16(SERVICE::getServiceName()),
new SERVICE(), allowIsolated);
}
在android_server_SystemServer_startSensorService中创建线程start_sensor_service来实例化SensorService,然后将SensorService添加到ServiceManager当中(SensorManager从ServiceManager里获取SensorService).当SensorService被创建时,onFirstRef被调用,这个初始化函数完成了一些重要的初始化过程,我们来看一下
void SensorService::onFirstRef() {
//SensorDevice为单例类,为SensorServic提供访问硬件的通道,它的构造函数中完成以下几件事
//1.获取HAL层sensor的动态库,获取module--->mSensorModule
//2.调用动态库的open方法,获取device--->mSensorDevice
//3.调用动态库get_sensors_list,获取所有sensor的列表,将它们填充到mActivationCount中,并对通过active接口,对每个HAL层的sensor执行一次关闭的动作
Se