sensormanager 经常register int有什么坏处

传感器 Sensor 加速度【示例】
时间: 19:40:36
&&&& 阅读:191
&&&& 评论:
&&&& 收藏:0
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&简介坐标系x轴:从左到右 y轴:从下到上 z轴:从内到外这个坐标系与Android 2D API中的不同,传感器中的返回值都以此坐标系为准。SENSOR_TYPE_ACCELEROMETER&&&&&& 1 //加速度SENSOR_TYPE_MAGNETIC_FIELD&&&&& 2 //磁力SENSOR_TYPE_ORIENTATION&&&&&&&& 3 //方向SENSOR_TYPE_GYROSCOPE&&&&&&&&&& 4 //陀螺仪SENSOR_TYPE_LIGHT&&&&&&&&&&&&&& 5 //光线感应SENSOR_TYPE_PRESSURE&&&&&&&&&&& 6 //压力SENSOR_TYPE_TEMPERATURE&&&&&&&& 7 //温度SENSOR_TYPE_PROXIMITY&&&&&&&&&& 8 //接近SENSOR_TYPE_GRAVITY&&&&&&&&&&&& 9 //重力SENSOR_TYPE_LINEAR_ACCELERATION 10//线性加速度SENSOR_TYPE_ROTATION_VECTOR&&&& 11//旋转矢量API概况sensor相关API被放到了android.hardware包下,主要使用的类有Sensor、SensorEvent、SensorManager及SensorEventListener接口。 SensorManager顺其自然的担任起管理的工作,负责注册监听某Sensor的状态;Sensor的数据通过SensorEvent返回。Sensor: 表示传感器的类,它保存有传感器名称,厂商,版本,精确度等信息SensorEvent:表示传感器事件,它可以保存传感器的值,传感器类型,时间戳等信息SensorEventListener:用于接收传感器来自SensorManager的通知,当传感器发生变化时,它包含两个回调函数SensorManager:SensorManager让你可以访问手机的全部传感器SensorListener:已废除注意:应当始终保证在不需要使用传感器的时候禁用传感器,特别是当你的activity【暂停】的时候。没有这样做将会导致电池只能使用很少几个小时。记住,系统不会在屏幕关闭的时候自动禁用传感器。延迟时间的精密度参数如下:SensorManager.SENSOR_DELAY_FASTEST & & 0msSensorManager.SENSOR_DELAY_GAME&&&&&&& 20msSensorManager.SENSOR_DELAY_UI & & & & & & &60msSensorManager.SENSOR_DELAY_NORMAL & 200ms因为感应检测Sensor的服务是否频繁和快慢都与电池参量的消耗有关,同时也会影响处理的效率,所以兼顾到消耗电池和处理效率的平衡,需要根据应用系统的需求来做适当的设置。加速度加速度传感器的背景这里的加速度特指重力加速度,所以在【静止时】重力传感器的返回值与加速度传感器值相同。地表上静止物体的重力加速度约为9.8 m/s^2.借用SensorManager中的常量:public static final float STANDARD_GRAVITY = 9.80665F;我们可以借助三轴上的值来确定设备的状态,比如:将手机平放在桌面上,x轴默认为0,y轴默认0,z轴默认9.81。将手机朝下放在桌面上,z轴为-9.81。将手机向左倾斜,x轴为正值;当x轴的值接近重力加速度时,说明设备的左边朝下。将手机向右倾斜,x轴为负值;当x轴的值接近负的g值时,说明设备的右边朝下。将手机向上倾斜,y轴为负值;当y轴的值接近负的g值时,说明设备的上边朝下。将手机向下倾斜,y轴为正值;当y轴的值接近g值时,说明设备的下边超下。地磁磁场传感器主要读取的是磁场的变化,通过该传感器便可开发出指南针、罗盘等磁场应用。该传感器读取的数据同样是空间坐标系三个方向的磁场值,其数据单位为?T。磁场传感器可以用来检测磁场大小,和加速度传感器一样,有x、y、z轴三个方向,单位为uT(microteslas),即微特斯拉。磁场传感器也称为compass(指南针),在uses-feature中使用Android.pass作为其名字。可以拿着手机到处测测,在电器附近不同位置,值还是相差巨大的。不过单看磁场数值其实也看不出所以然。方向安卓平台提供了2个传感器用于让我们判断设备的位置,分别是【地磁场传感器】和【方向传感器】。关于Orientation Sensor在官方文档中的概述里有这样一句话:The orientation sensor is&software-based&and derives its data from the&accelerometer and the geomagnetic&field sensor. 方向传感器是基于软件的,并且它的数据是通过【加速度传感器】和【磁场传感器】共同获得的。第一个元素azimuth,【z轴旋转角度】,手机由水平正北放置时开始顺时针旋转,z的值变化情况为0~360/0;表示指向地心的【方位角】第二个元素pitch,【x轴旋转角度】,手机由水平正北放置时开始顺时针旋转,x的值变化情况为0~-180/180~0;表示前后旋转的【仰俯角】第三个元素roll,【y轴旋转角度】,手机由水平正北放置时开始顺时针旋转,y的值变化情况为0~90~0~-90~0;表示左右旋转的【翻转角】一定要清楚,上面的值都是【旋转】角度,上面的总结是没有错的,如果你觉得错了,那就是没有理解【旋转】的意思。当手机顶部指向正北方时,方向值为0;顶部指向正东方时,方向值为90;顶部指向正南方时,方向值为180;顶部指向正西方时,方向值为270。磁场+加速度代替方向传感器在最新版的SDK中,使用Orientation传感器会看到这么一句话“This constant is deprecated. use SensorManager.getOrientation() instead. ”即这种方式已过期,不建议使用!Google建议我们在应用程序中使用SensorManager.getOrientation()来获得原始数据。public static float[] getOrientation (float[] R, float[] values)第一个参数是R[] 是一个旋转矩阵,用来保存磁场和加速度的数据,可以理解为这个函数的传入值,通过它这个函数给你求出方位角。第二个参数就是这个函数的输出了,他有函数自动为我们填充,这就是我们想要的。输出值values各个元素的含义values[0]& :方向角,但用(磁场+加速度)得到的数据范围是(-180~180),也就是说,0表示正北,90表示正东,180/-180表示正南,-90表示正西。而直接通过方向感应器数据范围是(0~359)360/0表示正北,90表示正东,180表示正南,270表示正西。values[1]& pitch 倾斜角,即由静止状态开始,前后翻转,手机顶部往上抬起(0~-90),手机尾部往上抬起(0~90)values[2]& roll 旋转角,即由静止状态开始,左右翻转,手机左侧抬起(0~90),手机右侧抬起(0~-90)现在问题是这个R[]怎么获取,其实他是通过函数getRotationMatrix得到的。看看getRotationMatrix的定义:public static boolean getRotationMatrix (float[] R, float[] I, float[] gravity, float[] geomagnetic)第一个就是我们需要填充的R数组,大小是9第二个是一个转换矩阵,将磁场数据转换进实际的重力坐标中,一般默认情况下可以设置为null第三个是一个大小为3的数组,表示从加速度感应器获取来的数据,在onSensorChanged中第四个是一个大小为3的数组,表示从磁场感应器获取来的数据,在onSensorChanged中加速度示例public&class&AccelerometerActivity&extends&ListActivity&implements&SensorEventListener&{&&&&private&TextView&tv_info;&&&&private&SensorManager&sm;//传感器管理器&&&&private&Vibrator&vibrator;//震动&&&&private&long&lastTime&=&System.currentTimeMillis();&&&&private&static&final&int&UPTATE_INTERVAL_TIME&=&3500;//&两次检测的时间间隔&&&&&&private&static&final&float&MEDUMVALUE&=&SensorManager.STANDARD_GRAVITY&+&8.5f;//标准值为9.80665&&&&private&static&final&float&SENSEVALUE&=&SensorManager.STANDARD_GRAVITY&-&0.5f;&&&&protected&void&onCreate(Bundle&savedInstanceState)&{&&&&&&&&super.onCreate(savedInstanceState);&&&&&&&&String[]&array&=&{&"注册,摇一摇,检测手机屏幕方向",&"取消注册",&};&&&&&&&&tv_info&=&new&TextView(this);&&&&&&&&tv_info.setTextColor(Color.BLUE);&&&&&&&&tv_info.setTextSize(TypedValue.COMPLEX_UNIT_SP,&16);&&&&&&&&tv_info.setPadding(20,&10,&20,&10);&&&&&&&&getListView().addFooterView(tv_info);&&&&&&&&setListAdapter(new&ArrayAdapter&String&(this,&android.R.layout.simple_list_item_1,&new&ArrayList&String&(Arrays.asList(array))));&&&&&&&&sm&=&(SensorManager)&getSystemService(SENSOR_SERVICE);&&&&&&&&vibrator&=&(Vibrator)&getSystemService(VIBRATOR_SERVICE);//权限【android.permission.VIBRATE】&&&&}&&&&protected&void&onResume()&{&&&&&&&&super.onResume();&&&&&&&&if&(sm&!=&null)&sm.registerListener(this,&sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),&SensorManager.SENSOR_DELAY_NORMAL);&&&&}&&&&protected&void&onPause()&{//保证在不需要使用传感器的时候禁用传感器&&&&&&&&super.onPause();&&&&&&&&if&(sm&!=&null)&sm.unregisterListener(this);&&&&}&&&&@Override&&&&protected&void&onListItemClick(ListView&l,&View&v,&int&position,&long&id)&{&&&&&&&&switch&(position)&{&&&&&&&&case&0:&&&&&&&&&&&&if&(sm&!=&null)&sm.registerListener(this,&sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),&SensorManager.SENSOR_DELAY_NORMAL);//设置获取传感器信息的频率&&&&&&&&&&&&break;&&&&&&&&case&1://Accelerometer&加速度传感器,32&&&&&&&&&&&&if&(sm&!=&null)&sm.unregisterListener(this);&&&&&&&&&&&&break;&&&&&&&&}&&&&}&&&&@Override&&&&public&void&onSensorChanged(SensorEvent&event)&{//在感应检测到Sensor的值有变化时会被调用到&&&&&&&&//实时检测,震动&&&&&&&&if&(Math.abs(event.values[0])&&&MEDUMVALUE&||&Math.abs(event.values[1])&&&MEDUMVALUE&||&Math.abs(event.values[2])&&&MEDUMVALUE)&vibrator.vibrate(200);&&&&&&&&//抽样检测&&&&&&&&if&(System.currentTimeMillis()&-&lastTime&&&UPTATE_INTERVAL_TIME)&return;&&&&&&&&lastTime&=&System.currentTimeMillis();//&现在的时间变成last时间&&&&&&&&tv_info.setText("传感器类型&"&+&event.sensor.getName()&+&"\n时间戳&"&+&event.timestamp&+&"\n精度&"&+&event.accuracy&+&//&&&&&&&&&&&&&&&&"\nx轴方向的值,右侧向上时为正&"&+&event.values[0]&+&"\ny轴方向的值,前侧向上时为正&"&+&event.values[1]&+&"\nz轴方向的值,屏幕向上时为正&"&+&event.values[2]);&&&&&&&&//检测手机屏幕方向&&&&&&&&if&(event.values[0]&&&SENSEVALUE)&Toast.makeText(this,&"屏幕朝左,重力指向设备左边",&Toast.LENGTH_SHORT).show();&&&&&&&&else&if&(event.values[0]&&&-SENSEVALUE)&Toast.makeText(this,&"屏幕朝右,重力指向设备右边",&Toast.LENGTH_SHORT).show();&&&&&&&&else&if&(event.values[1]&&&SENSEVALUE)&Toast.makeText(this,&"屏幕朝前,重力指向设备下边",&Toast.LENGTH_SHORT).show();&&&&&&&&else&if&(event.values[1]&&&-SENSEVALUE)&Toast.makeText(this,&"屏幕朝后,重力指向设备上边",&Toast.LENGTH_SHORT).show();&&&&&&&&else&if&(event.values[2]&&&SENSEVALUE)&Toast.makeText(this,&"屏幕朝上",&Toast.LENGTH_SHORT).show();&&&&&&&&else&if&(event.values[2]&&&-SENSEVALUE)&Toast.makeText(this,&"屏幕朝下",&Toast.LENGTH_SHORT).show();&&&&}&&&&@Override&&&&public&void&onAccuracyChanged(Sensor&paramSensor,&int&paramInt)&{//在感应检测到Sensor的精密度有变化时被调用到&&&&}}方向示例public&class&OrientationActivity2&extends&Activity&implements&SensorEventListener&{&&&&private&TextView&tv_info;&&&&private&TextView&tv_orientation;&&&&private&ImageView&iv;&&&&private&SensorManager&sm;//传感器管理器&&&&private&float[]&accelValues&=&new&float[3];&&&&private&float[]&magValues&=&new&float[3];&&&&private&long&lastTime&=&System.currentTimeMillis();&&&&private&static&final&int&UPTATE_INTERVAL_TIME&=&500;//&两次检测的时间间隔&&&&&&private&float&lastRotateDegree;&&&&protected&void&onCreate(Bundle&savedInstanceState)&{&&&&&&&&super.onCreate(savedInstanceState);&&&&&&&&setContentView(R.layout.activity_main);&&&&&&&&tv_info&=&(TextView)&findViewById(R.id.tv_info);&&&&&&&&tv_orientation&=&(TextView)&findViewById(R.id.tv_orientation);&&&&&&&&iv&=&(ImageView)&findViewById(R.id.iv);&&&&&&&&sm&=&(SensorManager)&getSystemService(SENSOR_SERVICE);&&&&}&&&&protected&void&onResume()&{&&&&&&&&super.onResume();&&&&&&&&if&(sm&!=&null)&{&&&&&&&&&&&&sm.registerListener(this,&sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),&SensorManager.SENSOR_DELAY_NORMAL);&&&&&&&&&&&&sm.registerListener(this,&sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),&SensorManager.SENSOR_DELAY_NORMAL);&&&&&&&&}&&&&}&&&&protected&void&onPause()&{//保证在不需要使用传感器的时候禁用传感器&&&&&&&&super.onPause();&&&&&&&&if&(sm&!=&null)&sm.unregisterListener(this);&&&&}&&&&@Override&&&&public&void&onSensorChanged(SensorEvent&event)&{&&&&&&&&switch&(event.sensor.getType())&{&&&&&&&&case&Sensor.TYPE_ACCELEROMETER:&&&&&&&&&&&&accelValues&=&event.values;&&&&&&&&&&&&break;&&&&&&&&case&Sensor.TYPE_MAGNETIC_FIELD:&&&&&&&&&&&&magValues&=&event.values;&&&&&&&&&&&&break;&&&&&&&&}&&&&&&&&tv_info.setText("传感器类型&"&+&event.sensor.getName()&+&"\n获取到的值\n"&+&event.values[0]&+&"\n"&+&event.values[1]&+&"\n"&+&event.values[2]);&&&&&&&&if&(System.currentTimeMillis()&-&lastTime&&&UPTATE_INTERVAL_TIME)&return;&&&&&&&&lastTime&=&System.currentTimeMillis();//&现在的时间变成last时间&&&&&&&&calculateOrientation();&&&&}&&&&@Override&&&&public&void&onAccuracyChanged(Sensor&paramSensor,&int&paramInt)&{&&&&}&&&&private&void&calculateOrientation()&{&&&&&&&&float[]&R&=&new&float[9];//旋转数组&&&&&&&&float[]&values&=&new&float[3];//模拟方向传感器的数据&&&&&&&&//要填充的旋转数组;将磁场数据转换进实际的重力坐标中,一般默认情况下可以设置为null;加速度传感器数据;地磁传感器数据&&&&&&&&&SensorManager.getRotationMatrix(R,&null,&accelValues,&magValues);&&&&&&&&SensorManager.getOrientation(R,&values);&&&&&&&&//将弧度转化为角度后输出&&&&&&&&&&tv_orientation.setText("角度\n");&&&&&&&&for&(float&value&:&values)&{&&&&&&&&&&&&value&=&(float)&Math.toDegrees(value);&&&&&&&&&&&&tv_orientation.append(value&+&"\n");&&&&&&&&}&&&&&&&&float&value&=&-(float)&Math.toDegrees(values[0]);&&&&&&&&if&(Math.abs(value&-&lastRotateDegree)&&&1)&{&&&&&&&&&&&&//旋转补间动画&&&&&&&&&&&&RotateAnimation&animation&=&new&RotateAnimation(lastRotateDegree,&value,&Animation.RELATIVE_TO_SELF,&0.5f,&Animation.RELATIVE_TO_SELF,&0.5f);&&&&&&&&&&&&animation.setFillAfter(true);&&&&&&&&&&&&iv.startAnimation(animation);&&&&&&&&&&&&lastRotateDegree&=&&&&&&&&&}&&&&&&&&value&=&-&&&&&&&&if&(value&&=&-10&&&&value&&&10)&{&&&&&&&&&&&&tv_orientation.append("正北");&&&&&&&&}&else&if&(value&&=&10&&&&value&&&80)&{&&&&&&&&&&&&tv_orientation.append("东北");&&&&&&&&}&else&if&(value&&=&80&&&&value&&=&100)&{&&&&&&&&&&&&tv_orientation.append("正东");&&&&&&&&}&else&if&(value&&=&100&&&&value&&&170)&{&&&&&&&&&&&&tv_orientation.append("东南");&&&&&&&&}&else&if&((value&&=&170&&&&value&&=&180)&||&(value)&&=&-180&&&&value&&&-170)&{&&&&&&&&&&&&tv_orientation.append("正南");&&&&&&&&}&else&if&(value&&=&-170&&&&value&&&-100)&{&&&&&&&&&&&&tv_orientation.append("西南");&&&&&&&&}&else&if&(value&&=&-100&&&&value&&&-80)&{&&&&&&&&&&&&tv_orientation.append("正西");&&&&&&&&}&else&if&(value&&=&-80&&&&value&&&-10)&{&&&&&&&&&&&&tv_orientation.append("西北");&&&&&&&&}&&&&}}附件列表&标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&国之画&&&& &&&&chrome插件
版权所有 京ICP备号-2
迷上了代码!3251人阅读
Android framework 源码分析(2)
SensorManager 基于Android 5.1源码分析:
1、Java层启动轮询线程的流程
SensorManager.java
这里有4个供上层APP使用的注册接口。
public&boolean&registerListener(SensorListener
listener, int&sensors)
public&boolean&registerListener(SensorListener
listener, int&sensors,int&rate)//以上两个方法在5.1版本上已被废弃
public&boolean&registerListener(SensorEventListener
listener, Sensor sensor,int&samplingPeriodUs)
public&boolean&registerListener(SensorEventListener
listener, Sensor sensor, int&samplingPeriodUs,int&maxReportLatencyUs){
&&&&&&&&int&delay =getDelay(samplingPeriodUs);
&&&&&&&&return&registerListenerImpl(listener, sensor, delay,null,
maxReportLatencyUs, 0);//SensorManager类的registerListenerImpl方法是抽象法,真正的实现在其子类SystemSensorManager.java中。
SystemSensorManager.java
public&class&SystemSensorManagerextends&SensorManager
{//SystemSensorManager是SensorManager的子类。
&@Override
&&&&protected&boolean&registerListenerImpl(SensorEventListener
listener, Sensor sensor,
&&&&&&&&&&&&int&delayUs, Handler handler,int&maxBatchReportLatencyUs,int&reservedFlags)&{
synchronized&(mSensorListeners) {
&&&&&&&&&&&&SensorEventQueue queue = mSensorListeners.get(listener);
&&&&&&&&&&&&if&(queue ==null)
&&&&&&&&&&&&&&&&Looper looper = (handler !=null) ? handler.getLooper() : mMainL
&&&&&&&&&&&&&&&&queue = new&SensorEventQueue(listener, looper,this);//将looper传入启动轮询线程。
&&&&&&&&&&&&&&&&......
&&&&&&&&&&&&&&&&mSensorListeners.put(listener, queue);
&&&&&&&&&&&&&&&&return&true;
&&&&&&&&&&&&} else&{
&&&&&&&&&&&&&&&&return&queue.addSensor(sensor, delayUs, maxBatchReportLatencyUs, reservedFlags);
&&&&&&&&&&&&}
//SensorEventQueue构造方法中调用父类构造方法。
static&final&class&SensorEventQueue&extends&BaseEventQueue&{
&&&&&&&&private&final&SensorEventListener mL
&&&&&&&&private&final&SparseArray&SensorEvent&
mSensorsEvents = new&SparseArray&SensorEvent&();
&&&&&&&&public&SensorEventQueue(SensorEventListener listener, Looper looper,
&&&&&&&&&&&&&&&&SystemSensorManager manager) {
&&&&&&&&&&&&super(looper, manager);
&&&&&&&&&&&&mListener =
//SensorEventQueue和TriggerEventQueue是BaseEventQueue的两个子类。在BaseEventQueue类中声明了以下几个native方法
&&&&private&static&abstract&class&BaseEventQueue&{
&&&&&&&&private&native&long&nativeInitBaseEventQueue(BaseEventQueue
eventQ, MessageQueue msgQ,
&&&&&&&&&&&&&&&&float[] scratch);
&&&&&&&&private&static&native&int&nativeEnableSensor(long&eventQ,int&handle,int&rateUs,
&&&&&&&&&&&&&&&&int&maxBatchReportLatencyUs,int&reservedFlags);
&&&&&&&&private&static&native&int&nativeDisableSensor(long&eventQ,int&handle);
&&&&&&&&private&static&native&void&nativeDestroySensorEventQueue(long&eventQ);
&&&&&&&&private&static&native&int&nativeFlushSensor(long&eventQ);
BaseEventQueue(Looper looper, SystemSensorManager manager) {
&&&&&&&&&&&&nSensorEventQueue = nativeInitBaseEventQueue(this,
looper.getQueue(), mScratch);//调用JNI native中的消息队列初始化
&&&&&&&&&&&&mCloseGuard.open(&dispose&);
&&&&&&&&&&&&mManager =
2、native中的消息队列初始化流程
android_hardware_SensorManager.cpp
static JNINativeMethod gBaseEventQueueMethods[] = {
&&&&{&nativeInitBaseEventQueue&,
&&&&&&&&&&&&&(Landroid/hardware/SystemSensorManager$BaseEventQLandroid/os/MessageQ[F)J&,
&&&&&&&&&&&&(void*)nativeInitSensorEventQueue},//对应的native函数nativeInitSensorEventQueue指针
&&&&{&nativeEnableSensor&,
&&&&&&&&&&&&&(JIIII)I&,
&&&&&&&&&&&&(void*)nativeEnableSensor },
&&&&{&nativeDisableSensor&,
&&&&&&&&&&&&&(JI)I&,
&&&&&&&&&&&&(void*)nativeDisableSensor },
&&&&{&nativeDestroySensorEventQueue&,
&&&&&&&&&&&&&(J)V&,
&&&&&&&&&&&&(void*)nativeDestroySensorEventQueue },
&&&&{&nativeFlushSensor&,
&&&&&&&&&&&&&(J)I&,
&&&&&&&&&&&&(void*)nativeFlushSensor },
static&jlongnativeInitSensorEventQueue(JNIEnv *env, jclass clazz,
jobject eventQ, jobject msgQ, jfloatArray scratch)&{
&&&&SensorManager& mgr(SensorManager::getInstance());//单例模式(通过继承Singleton实现),所调用的构造函数在SensorManager.cpp中
&&&&sp&SensorEventQueue& queue(mgr.createEventQueue());//创建消息队列
&&&&sp&Receiver& receiver = new&Receiver(queue, messageQueue, eventQ, scratch);
&&&&receiver-&incStrong((void*)nativeInitSensorEventQueue);
&&&&return&jlong(receiver.get());
SensorManager.h
class SensorManager :
public AsensorManager,//ASensorManager是NDK的接口,应该是个结构体,c++是可以继承结构体的
public Singleton&SensorManager&//Singleton是一个单例泛型类(详见附1节),提供了getInstance与hasInstance两个方法
mutable sp&ISensorServer& mSensorS//注意,sp是强引用,要关注onFirstRef回调,这个变量的初始化是在SensorManager::assertStateLocked()中
SensorManager.cpp
SensorManager::SensorManager()
&&&&: mSensorList(0)
&&&&// okay we're not locked here, but it's not needed during construction
&&&&assertStateLocked();
status_t SensorManager::assertStateLocked()const&{
&&&&if&(mSensorServer == NULL) {
&&&&&&&&// try for one second
&&&&&&&&const&String16 name(&sensorservice&);
&&&&&&&&for&(int&i=0
; i&4 ; i++) {
&&&&&&&&&&&&status_t err = getService(name, &mSensorServer);
//得到服务SensorService,注意mSensorServer是强引用类型,要关注onFirstRef回调
//另外getService定义在IServiceManager.h中,是一个全局函数,不属于任何类,但会通过另一个全局函数defaultServiceManager()调用到IServiceManager.cpp中的BpServiceManager::getService
//而服务也是通过defaultServiceManager()调用IServiceManager.cpp中的BpServiceManager::addService注册的(详见第4节开头)
&&&&&&&&&&&&if&(err == NAME_NOT_FOUND) {
&&&&&&&&&&&&&&&&usleep(250000);
&&&&&&&&&&&&&&&&continue;
&&&&&&&&&&&&}
&&&&&&&&&&&&if&(err != NO_ERROR) {
&&&&&&&&&&&&&&&&return&
&&&&&&&&&&&&}
&&&&&&&&&&&&break;
&&&&&&&&class&DeathObserver :public&IBinder::DeathRecipient
{//服务SensorService的死亡监听
&&&&&&&&&&&&SensorManager& mSensorM
&&&&&&&&&&&&virtual&void&binderDied(const&wp&IBinder&&
&&&&&&&&&&&&&&&&ALOGW(&sensorservice&died [%p]&, who.unsafe_get());
&&&&&&&&&&&&&&&&mSensorManger.sensorManagerDied();//若服务SensorService死亡,则同时结束SensorManager
&&&&&&&&&&&&}
&&&&&&&&public:
&&&&&&&&&&&&DeathObserver(SensorManager& mgr) : mSensorManger(mgr) { }
&&&&&&&&};
//注册服务SensorService的死亡监听
&&&&&&&&mDeathObserver = new&DeathObserver(*const_cast&SensorManager
*&(this));
&&&&&&&&mSensorServer-&asBinder()-&linkToDeath(mDeathObserver);
//从服务SensorService获取sensor列表,并保存在SensorManager中
&&&&&&&&mSensors = mSensorServer-&getSensorList();
&&&&&&&&size_t count = mSensors.size();
&&&&&&&&mSensorList = (Sensor const**)malloc(count *sizeof(Sensor*));
&&&&&&&&for&(size_t i=0 ; i& i++) {
&&&&&&&&&&&&mSensorList[i] = mSensors.array() +
&&&&return&NO_ERROR;
SensorManager.cpp
sp&SensorEventQueue& SensorManager::createEventQueue()
&&&&sp&SensorEventQueue&
&&&&Mutex::Autolock _l(mLock);
&&&&while (assertStateLocked() == NO_ERROR) {
&&&&&&&&sp&ISensorEventConnection& connection =
&&&&&&&&&&&&&&&&mSensorServer-&createSensorEventConnection();//创建连接接口(详见第2.1节),需要注意:这是客户端在调用服务端的接口
&&&&&&&&if (connection == NULL) {
&&&&&&&&&&&&// SensorService just died.
&&&&&&&&&&&&ALOGE(&createEventQueue: connection is NULL. SensorService died.&);
&&&&&&&&&&&&usleep(100000);
&&&&&&&&&&&&
&&&&&&&&queue = new SensorEventQueue(connection);//创建消息队列(详见第2.2节)
2.1、创建连接接口的过程
SensorService.cpp
sp&ISensorEventConnection& SensorService::createSensorEventConnection()
&&&&uid_t uid = IPCThreadState::self()-&getCallingUid();
&&&&sp&SensorEventConnection& result(new
SensorEventConnection(this, uid));
SensorService::SensorEventConnection::SensorEventConnection(
&&&&&&&&const sp&SensorService&& service, uid_t uid)
&&&&: mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
&&&&&&mDead(false), mEventCache(NULL), mCacheSize(0), mMaxCacheSize(0) {
mChannel = new BitTube(mService-&mSocketBufferSize);
//BitTube的作用是创建一对管道(详见附2节)
//sp&BitTube& const mC保存的管道会在SensorService::SensorEventConnection::sendEvents中用到,而sendEvents在native服务线程中用到(详见4.2节)
2.2、创建消息队列的过程
SensorEventQueue.h
class SensorEventQueue : public ASensorEventQueue, public RefBase
SensorEventQueue.cpp
SensorEventQueue::SensorEventQueue(const sp&ISensorEventConnection&& connection)
&&&&: mSensorEventConnection(connection), mRecBuffer(NULL), mAvailable(0), mConsumed(0),
&&&&&&mNumAcksToSend(0) {
&&&&mRecBuffer = new ASensorEvent[MAX_RECEIVE_BUFFER_EVENT_COUNT];//赋值
3、SystemSensorManager的初始化流程
3.1、从开机到实例化SystemSensorManager
SystemServer.java
public&final&class&SystemServer&{
&&&&&* Called to initialize native system services.
&&&&private&static&native&void&nativeInit();
&&&&&* The main entry point from zygote.
&&&&public&static&void&main(String[]
&&&&&&&&new&SystemServer().run();
&private&void&run()
// Initialize native services.
&&&&&&&&System.loadLibrary(&android_servers&);
&&&&&&&&nativeInit();//第1步,JNI到com_android_server_SystemServer.cpp中去
// Create the system service manager.
&&&&&&&&mSystemServiceManager = new&SystemServiceManager(mSystemContext);
&&&&&&&&LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
&&&&&&&&// Start services.
&&&&&&&&try&{
&&&&&&&&&&&&startBootstrapServices();
&&&&&&&&&&&&startCoreServices();
&&&&&&&&&&&&startOtherServices();
&&&&&&&&} catch&(Throwable ex) {
&&&&&&&&&&&&Slog.e(&System&, &******************************************&);
&&&&&&&&&&&&Slog.e(&System&, &************ Failure starting system services&, ex);
&&&&&&&&&&&&/// M: RecoveryManagerService &@{
&&&&&&&&&&&&if&(mRecoveryManagerService !=null&&&
exinstanceof&RuntimeException) {
&&&&&&&&&&&&&&&&mRecoveryManagerService.handleException((RuntimeException)ex,true);
&&&&&&&&&&&&}
&&&&&&&&&&&&/// @}
private&void&startBootstrapServices()
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);//第4步
private&void&startOtherServices()
mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());//第5步
PowerManagerService.cpp&
public&final&class&PowerManagerServiceextends&SystemServiceimplements&Watchdog.Monitor&{
public void systemReady(IAppOpsService appOps) {
&&&&&&&&synchronized (mLock) {
SensorManager&sensorManager =new&SystemSensorManager(mContext,
mHandler.getLooper());&//第6步,实例化SystemSensorManager
com_android_server_SystemServer.cpp
static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz)&{//第2步
&&&&char propBuf[PROPERTY_VALUE_MAX];
&&&&property_get(&system_init.startsensorservice&, propBuf, &1&);
&&&&if (strcmp(propBuf, &1&) == 0) {
&&&&&&&&// Start the sensor service
&&&&&&&&SensorService::instantiate();
//第3步SensorService实例化启动
static&JNINativeMethod gMethods[] = {&//函数签名信息
&&&&/* name, signature, funcPtr */
&&&&{ &nativeInit&, &()V&, (void*)android_server_SystemServer_nativeInit&},
int&register_android_server_SystemServer(JNIEnv* env)//动态注册JNI函数
&&&&return&jniRegisterNativeMethods(env, &com/android/server/SystemServer&,
&&&&&&&&&&&&gMethods, NELEM(gMethods));
3.2、实例化SystemSensorManager
SystemSensorManager.java
public class SystemSensorManager extends SensorManager&{
&&&&public SystemSensorManager(Context context, Looper mainLooper) {
&&&&&&&&mMainLooper = mainL
&&&&&&&&mTargetSdkLevel = context.getApplicationInfo().targetSdkV
&&&&&&&&synchronized(sSensorModuleLock) {
&&&&&&&&&&&&if (!sSensorModuleInitialized) {
&&&&&&&&&&&&&&&&sSensorModuleInitialized =
&&&&&&&&&&&&&&&&nativeClassInit();//编号3.2.1
&&JNI调用android_hardware_SensorManager.cpp中的方法
&&&&&&&&&&&&&&&&// initialize the sensor list
&&&&&&&&&&&&&&&&final ArrayList&Sensor& fullList = sFullSensorsL
&&&&&&&&&&&&&&&&int i = 0;
&&&&&&&&&&&&&&&&do {
&&&&&&&&&&&&&&&&&&&&Sensor sensor = new Sensor();
&&&&&&&&&&&&&&&&&&&&i = nativeGetNextSensor(sensor, i);//编号3.2.2&&&JNI调用android_hardware_SensorManager.cpp中的方法;并最终将sensor列表保存在sHandleToSensor变量中
&&&&&&&&&&&&&&&&&&&&if (i&=0) {
&&&&&&&&&&&&&&&&&&&&&&&&//Log.d(TAG, &found sensor: & + sensor.getName() +
&&&&&&&&&&&&&&&&&&&&&&&&// &&&&&&&&, handle=& + sensor.getHandle());
&&&&&&&&&&&&&&&&&&&&&&&&fullList.add(sensor);
&&&&&&&&&&&&&&&&&&&&&&&&sHandleToSensor.append(sensor.getHandle(), sensor);
&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&} while (i&0);
&&&&&&&&&&&&}
android_hardware_SensorManager.cpp
static JNINativeMethod gSystemSensorManagerMethods[] = {
&&&&{&nativeClassInit&,
&&&&&&&&&&&&&()V&,
&&&&&&&&&&&&(void*)nativeClassInit },
&&&&{&nativeGetNextSensor&,
&&&&&&&&&&&&&(Landroid/hardware/SI)I&,
&&&&&&&&&&&&(void*)nativeGetNextSensor },
android_hardware_SensorManager.cpp
struct&SensorOffsets
&&&&jfieldID &&&
&&&&jfieldID &&&
&&&&jfieldID &&&
&&&&jfieldID &&&
&&&&jfieldID &&&
&&&&jfieldID &&&
&&&&jfieldID &&&
&&&&jfieldID &&&
&&&&jfieldID &&&minD
&&&&jfieldID &&&fifoReservedEventC
&&&&jfieldID &&&fifoMaxEventC
&&&&jfieldID &&&stringT
&&&&jfieldID &&&requiredP
&&&&jfieldID &&&maxD
&&&&jfieldID &&&
} gSensorO//用于保存java类中数据域的FieldID,而非具体java对象的ID
static&void
nativeClassInit&(JNIEnv *_env, jclass _this)
&&&&jclass sensorClass = _env-&FindClass(&android/hardware/Sensor&);//Sensor.java
&&&&SensorOffsets& sensorOffsets = gSensorO//这里使用的是C++的引用,即下面是对gSensorOffsets的赋值
&&&&sensorOffsets.name &&&&&&&= _env-&GetFieldID(sensorClass, &mName&, &&&&&&Ljava/lang/S&);
&&&&sensorOffsets.vendor &&&&&= _env-&GetFieldID(sensorClass, &mVendor&, &&&&Ljava/lang/S&);
&&&&sensorOffsets.version &&&&= _env-&GetFieldID(sensorClass, &mVersion&, &&&I&);
&&&&sensorOffsets.handle &&&&&= _env-&GetFieldID(sensorClass, &mHandle&, &&&&I&);
&&&&sensorOffsets.type &&&&&&&= _env-&GetFieldID(sensorClass, &mType&, &&&&&&I&);
&&&&sensorOffsets.range &&&&&&= _env-&GetFieldID(sensorClass, &mMaxRange&, &&F&);
&&&&sensorOffsets.resolution &= _env-&GetFieldID(sensorClass, &mResolution&,&F&);
&&&&sensorOffsets.power &&&&&&= _env-&GetFieldID(sensorClass, &mPower&, &&&&&F&);
&&&&sensorOffsets.minDelay &&&= _env-&GetFieldID(sensorClass, &mMinDelay&, &&I&);
&&&&sensorOffsets.fifoReservedEventCount =
&&&&&&&&&&&&_env-&GetFieldID(sensorClass, &mFifoReservedEventCount&, &&I&);
&&&&sensorOffsets.fifoMaxEventCount = _env-&GetFieldID(sensorClass, &mFifoMaxEventCount&, &&I&);
&&&&sensorOffsets.stringType = _env-&GetFieldID(sensorClass, &mStringType&, &Ljava/lang/S&);
&&&&sensorOffsets.requiredPermission = _env-&GetFieldID(sensorClass, &mRequiredPermission&,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&Ljava/lang/S&);
&&&&sensorOffsets.maxDelay &&&= _env-&GetFieldID(sensorClass, &mMaxDelay&, &&I&);
&&&&sensorOffsets.flags = _env-&GetFieldID(sensorClass, &mFlags&, &&I&);
Sensor.java
public&final&class&Sensor&{
/* Some of these fields are set only by the native bindings in
&&&&&* SensorManager.
&&&&private&String &mN
&&&&private&String &mV
&&&&private&int&&&&&mV
&&&&private&int&&&&&mH
&&&&private&int&&&&&mT
&&&&private&float&&&mMaxR
&&&&private&float&&&mR
&&&&private&float&&&mP
&&&&private&int&&&&&mMinD
&&&&private&int&&&&&mFifoReservedEventC
&&&&private&int&&&&&mFifoMaxEventC
&&&&private&String &mStringT
&&&&private&String &mRequiredP
&&&&private&int&&&&&mMaxD
&&&&private&int&&&&&mF
android_hardware_SensorManager.cpp
static&jint
nativeGetNextSensor(JNIEnv *env, jclass clazz, jobject sensor, jint next)
&&&&SensorManager& mgr(SensorManager::getInstance());
&&&&Sensor const*const*
&&&&size_t count = mgr.getSensorList(&sensorList);//通过SensorManager获取sensor列表,SensorManager的列表是在SensorManager初始化时从SensorService获得到的
&&&&if&(size_t(next) &= count)
&&&&&&&&return&-1;
&&&&Sensor const*const&list
= sensorList[next];
&&&&const&SensorOffsets& sensorOffsets(gSensorOffsets);
&&&&jstring name = env-&NewStringUTF(list-&getName().string());
&&&&jstring vendor = env-&NewStringUTF(list-&getVendor().string());
&&&&jstring stringType = env-&NewStringUTF(list-&getStringType().string());
&&&&jstring requiredPermission = env-&NewStringUTF(list-&getRequiredPermission().string());
&&&&env-&SetObjectField(sensor, sensorOffsets.name, &&&&&name);
&&&&env-&SetObjectField(sensor, sensorOffsets.vendor, &&&vendor);
&&&&env-&SetIntField(sensor, sensorOffsets.version, &&&&&list-&getVersion());
&&&&env-&SetIntField(sensor, sensorOffsets.handle, &&&&&&list-&getHandle());
&&&&env-&SetIntField(sensor, sensorOffsets.type, &&&&&&&&list-&getType());
&&&&env-&SetFloatField(sensor, sensorOffsets.range, &&&&&list-&getMaxValue());
&&&&env-&SetFloatField(sensor, sensorOffsets.resolution, list-&getResolution());
&&&&env-&SetFloatField(sensor, sensorOffsets.power, &&&&&list-&getPowerUsage());
&&&&env-&SetIntField(sensor, sensorOffsets.minDelay, &&&&list-&getMinDelay());
&&&&env-&SetIntField(sensor, sensorOffsets.fifoReservedEventCount,
&&&&&&&&&&&&&&&&&&&&&list-&getFifoReservedEventCount());
&&&&env-&SetIntField(sensor, sensorOffsets.fifoMaxEventCount,
&&&&&&&&&&&&&&&&&&&&&list-&getFifoMaxEventCount());
&&&&env-&SetObjectField(sensor, sensorOffsets.stringType, stringType);
&&&&env-&SetObjectField(sensor, sensorOffsets.requiredPermission,
&&&&&&&&&&&&&&&&&&&&&&&&requiredPermission);
&&&&env-&SetIntField(sensor, sensorOffsets.maxDelay, list-&getMaxDelay());
&&&&env-&SetIntField(sensor, sensorOffsets.flags, list-&getFlags());
&&&&next++;
&&&&return&size_t(next) & count ? next : 0;
4、服务端的初始化流程
//启动过程类似于,可参考3.1节中前3步的流程
com_android_server_SystemServer.cpp
static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz)&{
&&&&char propBuf[PROPERTY_VALUE_MAX];
&&&&property_get(&system_init.startsensorservice&, propBuf, &1&);//property_get()是c/c++的接口,对应的java接口是SystemProperties_get*(),读取build.prop中的值
&&&&if (strcmp(propBuf, &1&) == 0) {//判断是否要启动服务,默认是启动
&&&&&&&&// Start the sensor service
&&&&&&&&SensorService::instantiate();&//SensorService继承了模板类BinderService&SensorService&,instantiate就是模板类的方法
BinderService.h
template&typename SERVICE&
class BinderService
static status_t publish(bool allowIsolated = false) {
sp&IServiceManager& sm(defaultServiceManager());//defaultServiceManager()定义在IServiceManager.cpp中
return sm-&addService(String16(SERVICE::getServiceName()), new SERVICE(), allowIsolated);
//new了一个SensorService的实例,并将其添加到系统服务管理器中
//这样就可以用defaultServiceManager:getService()获取到Sensor服务的实例
static void instantiate() { publish(); }
IServiceManager.h
sp&IServiceManager& defaultServiceManager();//这是原型定义,实体在IServiceManager.cpp中
template&typename INTERFACE&
status_t getService(const String16& name, sp&INTERFACE&* outService)
const sp&IServiceManager& sm = defaultServiceManager();
if (sm != NULL) {
*outService = interface_cast&INTERFACE&(sm-&getService(name));//getService与addService都是接口IServiceManager中定义的方法
if ((*outService) != NULL) return NO_ERROR;
return NAME_NOT_FOUND;
SensorService.h
class SensorService&:
public BinderService&SensorService&,
public BnSensorServer,
protected Thread//线程类,在SensorService::onFirstRef()中由run方法启动
// ISensorServer interface
&&&&virtual Vector&Sensor& getSensorList();//sensor列表,在SensorService::getSensorList()中获取,在SensorService::onFirstRef()中赋值
&&&&virtual sp&ISensorEventConnection& createSensorEventConnection();
SensorService.cpp
Vector&Sensor& SensorService::getSensorList()
&&&&char value[PROPERTY_VALUE_MAX];
&&&&property_get(&debug.sensors&, value, &0&);
&&&&const Vector&Sensor&& initialSensorList = (atoi(value)) ?//atoi是字符串转整型的意思
&&&&&&&&&&&&mUserSensorListDebug : mUserSensorL//在SensorService::onFirstRef()中赋值
&&&&Vector&Sensor& accessibleSensorL
&&&&for (size_t i = 0; i & initialSensorList.size(); i++) {
&&&&&&&&Sensor sensor = initialSensorList[i];
&&&&&&&&if (canAccessSensor(sensor)) {
&&&&&&&&&&&&accessibleSensorList.add(sensor);
&&&&&&&&} else {
&&&&&&&&&&&&String8 infoM
&&&&&&&&&&&&infoMessage.appendFormat(
&&&&&&&&&&&&&&&&&&&&&Skipped sensor %s because it requires permission %s&,
&&&&&&&&&&&&&&&&&&&&sensor.getName().string(),
&&&&&&&&&&&&&&&&&&&&sensor.getRequiredPermission().string());
&&&&&&&&&&&&ALOGI(infoMessage.string());
&&&&return accessibleSensorL
void SensorService::onFirstRef()
&&&&ALOGD(&nuSensorService starting...&);
&&&&SensorDevice& dev(SensorDevice::getInstance());//编号4.1 &&单例创建SensorDevice
&&&&if (dev.initCheck() == NO_ERROR) {//获得sensor列表
&&&&&&&&sensor_t const*
&&&&&&&&ssize_t count = dev.getSensorList(&list);
&&&&&&&&if (count & 0) {
&&&&&&&&&&&&ssize_t orientationIndex = -1;
&&&&&&&&&&&&bool hasGyro =//硬件上是否有陀螺仪的标志
&&&&&&&&&&&&uint32_t virtualSensorsNeeds =//是否需要记录某些sensor的标志
&&&&&&&&&&&&&&&&&&&&(1&&SENSOR_TYPE_GRAVITY) |
&&&&&&&&&&&&&&&&&&&&(1&&SENSOR_TYPE_LINEAR_ACCELERATION) |
&&&&&&&&&&&&&&&&&&&&(1&&SENSOR_TYPE_ROTATION_VECTOR);
&&&&&&&&&&&&mLastEventSeen.setCapacity(count);
&&&&&&&&&&&&for (ssize_t i=0 ; i& i++) {//扫描sensor列表
&&&&&&&&&&&&&&&&registerSensor( new HardwareSensor(list[i]) );
&&&&&&&&&&&&&&&&switch (list[i].type) {
&&&&&&&&&&&&&&&&&&&&case SENSOR_TYPE_ORIENTATION:
&&&&&&&&&&&&&&&&&&&&&&&&orientationIndex =
&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&case SENSOR_TYPE_GYROSCOPE:
&&&&&&&&&&&&&&&&&&&&case SENSOR_TYPE_GYROSCOPE_UNCALIBRATED:
&&&&&&&&&&&&&&&&&&&&&&&&hasGyro =
&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&case SENSOR_TYPE_GRAVITY:
&&&&&&&&&&&&&&&&&&&&case SENSOR_TYPE_LINEAR_ACCELERATION:
&&&&&&&&&&&&&&&&&&&&case SENSOR_TYPE_ROTATION_VECTOR:
&&&&&&&&&&&&&&&&&&&&&&&&virtualSensorsNeeds &= ~(1&&list[i].type);
&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&}
&&&&&&&&&&&&// it's safe to instantiate the SensorFusion object here
&&&&&&&&&&&&// (it wants to be instantiated after h/w sensors have been
&&&&&&&&&&&&// registered)
&&&&&&&&&&&&const SensorFusion& fusion(SensorFusion::getInstance());//单例创建SensorFusion
&&&&&&&&&&&&// build the sensor list returned to users
&&&&&&&&&&&&mUserSensorList = mSensorL//Sensor列表赋值
//如果有陀螺仪设备,则先注册和陀螺仪有关的虚拟传感器设备
//旋转,重力,加速器,方向等,这些设备都对应同一个物理硬件――陀螺仪
//这些逻辑上存在,物理上不存在的设备叫虚拟设备
&&&&&&&&&&&&if (hasGyro) {
&&&&&&&&&&&&&&&&Sensor aS
&&&&&&&&&&&&&&&&// Add Android virtual sensors if they're not already
&&&&&&&&&&&&&&&&// available in the HAL
&&&&&&&&&&&&&&&&aSensor = registerVirtualSensor( new RotationVectorSensor() );//虚拟旋转传感器
&&&&&&&&&&&&&&&&if (virtualSensorsNeeds & (1&&SENSOR_TYPE_ROTATION_VECTOR)) {
&&&&&&&&&&&&&&&&&&&&mUserSensorList.add(aSensor);
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&aSensor = registerVirtualSensor( new GravitySensor(list, count) );//虚拟重力传感器
&&&&&&&&&&&&&&&&if (virtualSensorsNeeds & (1&&SENSOR_TYPE_GRAVITY)) {
&&&&&&&&&&&&&&&&&&&&mUserSensorList.add(aSensor);
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&aSensor = registerVirtualSensor( new LinearAccelerationSensor(list, count) );//虚拟线性加速度传感器器
&&&&&&&&&&&&&&&&if (virtualSensorsNeeds & (1&&SENSOR_TYPE_LINEAR_ACCELERATION)) {
&&&&&&&&&&&&&&&&&&&&mUserSensorList.add(aSensor);
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&aSensor = registerVirtualSensor( new OrientationSensor() );//虚拟方向传感器
&&&&&&&&&&&&&&&&if (virtualSensorsNeeds & (1&&SENSOR_TYPE_ROTATION_VECTOR)) {
&&&&&&&&&&&&&&&&&&&&// if we are doing our own rotation-vector, also add
&&&&&&&&&&&&&&&&&&&&// the orientation sensor and remove the HAL provided one.
&&&&&&&&&&&&&&&&&&&&mUserSensorList.replaceAt(aSensor, orientationIndex);
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&// virtual debugging sensors are not added to mUserSensorList//虚拟调试传感器不被添加到mUserSensorList中
&&&&&&&&&&&&&&&&registerVirtualSensor( new CorrectedGyroSensor(list, count) );//修正陀螺传感器
&&&&&&&&&&&&&&&&registerVirtualSensor( new GyroDriftSensor() );//虚拟陀螺测漂传感器
&&&&&&&&&&&&}
&&&&&&&&&&&&// debugging sensor list
&&&&&&&&&&&&mUserSensorListDebug = mSensorL
&&&&&&&&&&&&......
&&&&&&&&&&&&mWakeLockAcquired =
&&&&&&&&&&&&mLooper = new Looper(false);
&&&&&&&&&&&&const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
&&&&&&&&&&&&mSensorEventBuffer = new sensors_event_t[minBufferSize];
&&&&&&&&&&&&mSensorEventScratch = new sensors_event_t[minBufferSize];
&&&&&&&&&&&&mMapFlushEventsToConnections = new SensorEventConnection const * [minBufferSize];
&&&&&&&&&&&&mAckReceiver = new SensorEventAckReceiver(this);
&&&&&&&&&&&&mAckReceiver-&run(&SensorEventAckReceiver&, PRIORITY_URGENT_DISPLAY);
&&&&&&&&&&&&mInitCheck = NO_ERROR;
&&&&&&&&&&&&run(&SensorService&, PRIORITY_URGENT_DISPLAY);//编号4.2开始运行SensorService线程,即启动SensorService::threadLoop()方法
Sensor SensorService::registerVirtualSensor(SensorInterface* s)
&&&&Sensor sensor = registerSensor(s);
&&&&mVirtualSensorList.add( s );//记录虚拟sensor
Sensor SensorService::registerSensor(SensorInterface* s)
&&&&sensors_event_
&&&&memset(&event, 0, sizeof(event));
const Sensor sensor(s-&getSensor());
//添加到Sensor列表,给客户端使用
&&&&// add to the sensor list (returned to clients)
&&&&mSensorList.add(sensor);
&&&&// add to our handle-&SensorInterface mapping
&&&&mSensorMap.add(sensor.getHandle(), s);
&&&&// create an entry in the mLastEventSeen array
&&&&mLastEventSeen.add(sensor.getHandle(), event);
SensorDevice.cpp
SensorDevice::SensorDevice()
&&&&: &mSensorDevice(0),
&&&&&&&mSensorModule(0)
&&&&status_t err = hw_get_module(SENSORS_HARDWARE_MODULE_ID,
&&&&&&&&&&&&(hw_module_t const**)&mSensorModule);//调用HAL层的hw_get_modele()方法,加载Sensor模块so文件
&&&&ALOGE_IF(err, &couldn't load %s module (%s)&,
&&&&&&&&&&&&SENSORS_HARDWARE_MODULE_ID, strerror(-err));
&&&&if (mSensorModule) {
&&&&&&&&err = sensors_open_1(&mSensorModule-&common, &mSensorDevice);//调用sensor.h的sensors_open方法打开设备
&&&&&&&&ALOGE_IF(err, &couldn't open device for module %s (%s)&,
&&&&&&&&&&&&&&&&SENSORS_HARDWARE_MODULE_ID, strerror(-err));
&&&&&&&&if (mSensorDevice) {
&&&&&&&&&&&&if (mSensorDevice-&common.version == SENSORS_DEVICE_API_VERSION_1_1 ||
&&&&&&&&&&&&&&&&mSensorDevice-&common.version == SENSORS_DEVICE_API_VERSION_1_2) {
&&&&&&&&&&&&&&&&ALOGE(&&&&& WARNING &&& Upgrade sensor HAL to version 1_3&);
&&&&&&&&&&&&}
&&&&&&&&&&&&sensor_t const*
&&&&&&&&&&&&ssize_t count = mSensorModule-&get_sensors_list(mSensorModule, &list);
&&&&&&&&&&&&mActivationCount.setCapacity(count);
&&&&&&&&&&&&I
&&&&&&&&&&&&for (size_t i=0 ; i&size_t(count) ; i++) {
&&&&&&&&&&&&&&&&mActivationCount.add(list[i].handle, model);
&&&&&&&&&&&&&&&&mSensorDevice-&activate(
&&&&&&&&&&&&&&&&&&&&&&&&reinterpret_cast&struct sensors_poll_device_t *&(mSensorDevice),//调用sensors_poll_device_t-&activate()对Sensor模块使能
&&&&&&&&&&&&&&&&&&&&&&&&list[i].handle, 0);
&&&&&&&&&&&&}
SensorService.cpp
bool SensorService::threadLoop()
&&&&ALOGD(&nuSensorService thread starting...&);
&&&&const size_t minBufferSize = SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT;
&&&&const size_t numEventMax = minBufferSize / (1 + mVirtualSensorList.size());
&&&&SensorDevice& device(SensorDevice::getInstance());
&&&&const size_t vcount = mVirtualSensorList.size();
&&&&const int halVersion = device.getHalDeviceVersion();
&&&&&&&&ssize_t count = device.poll(mSensorEventBuffer, numEventMax);//轮询
&&&&&&&&if (count & 0) {
&&&&&&&&&&&&ALOGE(&sensor poll failed (%s)&, strerror(-count));
&&&&&&&&&&&&
&&&&&&&&// Reset sensors_event_t.flags to zero for all events in the buffer.
&&&&&&&&for (int i = 0; i & i++) {
&&&&&&&&&&&&&mSensorEventBuffer[i].flags = 0;
&&&&&&&&SortedVector& sp&SensorEventConnection& & activeC
&&&&&&&&populateActiveConnections(&activeConnections);
&&&&&&&&Mutex::Autolock _l(mLock);
&&&&&&&&bool bufferHasWakeUpEvent =
&&&&&&&&for (int i = 0; i & i++) {
&&&&&&&&&&&&if (isWakeUpSensorEvent(mSensorEventBuffer[i])) {
&&&&&&&&&&&&&&&&bufferHasWakeUpEvent =
&&&&&&&&&&&&&&&&
&&&&&&&&&&&&}
&&&&&&&&if (bufferHasWakeUpEvent && !mWakeLockAcquired) {
&&&&&&&&&&&&setWakeLockAcquiredLocked(true);
&&&&&&&&recordLastValueLocked(mSensorEventBuffer, count);
&&&&&&&&// handle virtual sensors
//从底层读上来的应该都是物理存在的sensor的信息,但上层使用的sensor有一部分是虚拟的(陀螺仪派生的),所以需要先处理一下
&&&&&&&&if (count && vcount) {
&&&&&&&&&&&&sensors_event_t const * const event = mSensorEventB
&&&&&&&&&&&&const size_t activeVirtualSensorCount = mActiveVirtualSensors.size();
&&&&&&&&&&&&if (activeVirtualSensorCount) {
&&&&&&&&&&&&&&&&size_t k = 0;
&&&&&&&&&&&&&&&&SensorFusion& fusion(SensorFusion::getInstance());
&&&&&&&&&&&&&&&&if (fusion.isEnabled()) {
&&&&&&&&&&&&&&&&&&&&for (size_t i=0 ; i&size_t(count) ; i++) {
&&&&&&&&&&&&&&&&&&&&&&&&fusion.process(event[i]);
&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&for (size_t i=0 ; i&size_t(count) && k&minBufferS i++) {
&&&&&&&&&&&&&&&&&&&&for (size_t j=0 ; j&activeVirtualSensorC j++) {
&&&&&&&&&&&&&&&&&&&&&&&&if (count + k &= minBufferSize) {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&ALOGE(&buffer too small to hold all events: &
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&count=%zd, k=%zu, size=%zu&,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&count, k, minBufferSize);
&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&&&&&sensors_event_
&&&&&&&&&&&&&&&&&&&&&&&&SensorInterface* si = mActiveVirtualSensors.valueAt(j);
&&&&&&&&&&&&&&&&&&&&&&&&if (si-&process(&out, event[i])) {
&&&&&&&&&&&&&&&&&&&&&&&&&&&&mSensorEventBuffer[count + k] =
&&&&&&&&&&&&&&&&&&&&&&&&&&&&k++;
&&&&&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&&&&&if (k) {
&&&&&&&&&&&&&&&&&&&&// record the last synthesized values
&&&&&&&&&&&&&&&&&&&&recordLastValueLocked(&mSensorEventBuffer[count], k);
&&&&&&&&&&&&&&&&&&&&count +=
&&&&&&&&&&&&&&&&&&&&// sort the buffer by time-stamps
&&&&&&&&&&&&&&&&&&&&sortEventBuffer(mSensorEventBuffer, count);
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&}
&&&&&&&&// handle backward compatibility for RotationVector sensor
&&&&&&&&if (halVersion & SENSORS_DEVICE_API_VERSION_1_0) {
&&&&&&&&&&&&for (int i = 0; i & i++) {
&&&&&&&&&&&&&&&&if (mSensorEventBuffer[i].type == SENSOR_TYPE_ROTATION_VECTOR) {
&&&&&&&&&&&&&&&&&&&&// All the 4 components of the quaternion should be available
&&&&&&&&&&&&&&&&&&&&// No heading accuracy. Set it to -1
&&&&&&&&&&&&&&&&&&&&mSensorEventBuffer[i].data[4] = -1;
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&}
&&&&&&&&for (int i = 0; i & ++i) {
&&&&&&&&&&&&mMapFlushEventsToConnections[i] = NULL;
&&&&&&&&&&&&if (mSensorEventBuffer[i].type == SENSOR_TYPE_META_DATA) {
&&&&&&&&&&&&&&&&const int sensor_handle = mSensorEventBuffer[i].meta_data.
&&&&&&&&&&&&&&&&SensorRecord* rec = mActiveSensors.valueFor(sensor_handle);
&&&&&&&&&&&&&&&&if (rec != NULL) {
&&&&&&&&&&&&&&&&&&&&mMapFlushEventsToConnections[i] = rec-&getFirstPendingFlushConnection();
&&&&&&&&&&&&&&&&&&&&rec-&removeFirstPendingFlushConnection();
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&}
&&&&&&&&bool needsWakeLock =
&&&&&&&&size_t numConnections = activeConnections.size();
&&&&&&&&for (size_t i=0 ; i & numC ++i) {
&&&&&&&&&&&&if (activeConnections[i] != 0) {
&&&&&&&&&&&&&&&&activeConnections[i]-&sendEvents(mSensorEventBuffer, count, mSensorEventScratch,
&&&&&&&&&&&&&&&&&&&&&&&&mMapFlushEventsToConnections);//将数据写到管道中
&&&&&&&&&&&&&&&&needsWakeLock |= activeConnections[i]-&needsWakeLock();
&&&&&&&&&&&&&&&&// If the connection has one-shot sensors, it may be cleaned up after first trigger.
&&&&&&&&&&&&&&&&// Early check for one-shot sensors.
&&&&&&&&&&&&&&&&if (activeConnections[i]-&hasOneShotSensors()) {
&&&&&&&&&&&&&&&&&&&&cleanupAutoDisabledSensorLocked(activeConnections[i], mSensorEventBuffer,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&count);
&&&&&&&&&&&&&&&&}
&&&&&&&&&&&&}
&&&&&&&&if (mWakeLockAcquired && !needsWakeLock) {
&&&&&&&&&&&&setWakeLockAcquiredLocked(false);
&&&&} while (!Thread::exitPending());
&&&&ALOGW(&Exiting SensorService::threadLoop =& aborting...&);
&&&&abort();
4、消息传递
总结一下:
1、APP用registerListener注册回调
2、java层的客户端在SystemSensorManager.java
中的SystemSensorManager::SensorThreadRunnable::run()中
轮询服务端
3、服务端在
SensorService.cpp
中的bool SensorService::threadLoop()中
4、服务端向客户端写数据是通过管道进行的,且使用的结构体如下
./hardware/libhardware/include/hardware/sensors.h
typedef struct sensors_event_t&{
&&&&/* must be sizeof(struct sensors_event_t) */
&&&&int32_
&&&&/* sensor identifier */
&&&&int32_
&&&&/* sensor type */
&&&&int32_
&&&&/* reserved */
&&&&int32_t reserved0;
&&&&/* time is in nanosecond */
&&&&int64_
&&&&union {
&&&&&&&&union {
&&&&&&&&&&&&float &&&&&&&&&&data[16];
&&&&&&&&&&&&/* acceleration values are in meter per second per second (m/s^2) */
&&&&&&&&&&&&sensors_vec_t &&
&&&&&&&&&&&&/* magnetic vector values are in micro-Tesla (uT) */
&&&&&&&&&&&&sensors_vec_t &&
&&&&&&&&&&&&/* orientation values are in degrees */
&&&&&&&&&&&&sensors_vec_t &&
&&&&&&&&&&&&/* gyroscope values are in rad/s */
&&&&&&&&&&&&sensors_vec_t &&
&&&&&&&&&&&&/* temperature is in degrees centigrade (Celsius) */
&&&&&&&&&&&&float &&&&&&&&&&
&&&&&&&&&&&&/* distance in centimeters */
&&&&&&&&&&&&float &&&&&&&&&&
&&&&&&&&&&&&/* light in SI lux units */
&&&&&&&&&&&&float &&&&&&&&&&
&&&&&&&&&&&&/* pressure in hectopascal (hPa) */
&&&&&&&&&&&&float &&&&&&&&&&
&&&&&&&&&&&&/* relative humidity in percent */
&&&&&&&&&&&&float &&&&&&&&&&relative_
&&&&&&&&&&&&/* uncalibrated gyroscope values are in rad/s */
&&&&&&&&&&&&uncalibrated_event_t uncalibrated_
&&&&&&&&&&&&/* uncalibrated magnetometer values are in micro-Teslas */
&&&&&&&&&&&&uncalibrated_event_t uncalibrated_
&&&&&&&&&&&&/* heart rate data containing value in bpm and status */
&&&&&&&&&&&&heart_rate_event_t heart_
&&&&&&&&&&&&/* this is a special event. see SENSOR_TYPE_META_DATA above.
&&&&&&&&&&&&&* sensors_meta_data_event_t events are all reported with a type of
&&&&&&&&&&&&&* SENSOR_TYPE_META_DATA. The handle is ignored and must be zero.
&&&&&&&&&&&&&*/
&&&&&&&&&&&&meta_data_event_t meta_
&&&&&&&&};
&&&&&&&&union {
&&&&&&&&&&&&uint64_t &&&&&&&data[8];
&&&&&&&&&&&&/* step-counter */
&&&&&&&&&&&&uint64_t &&&&&&&step_
&&&&&&&&} u64;
&&&&/* Reserved flags for internal use. Set to zero. */
&&&&uint32_
&&&&uint32_t reserved1[3];
} sensors_event_t;
5、客户端从服务端读数据(通过android_hardware_SensorManager.cpp中的JNI接口sensors_data_poll)使用的结构体如下,可以看出和服务端使用的结构体基本一致,差异在联合体部分,且差异不会影响到联合体的大小
frameworks/native/include/android/sensor.h
/* NOTE: Must match hardware/sensors.h */
typedef struct ASensorEvent {
&&&&int32_ /* sizeof(struct ASensorEvent) */
&&&&int32_
&&&&int32_
&&&&int32_t reserved0;
&&&&int64_
&&&&union {
&&&&&&&&union {
&&&&&&&&&&&&float &&&&&&&&&&data[16];
&&&&&&&&&&&&ASensorVector &&
&&&&&&&&&&&&ASensorVector &&
&&&&&&&&&&&&ASensorVector &&
&&&&&&&&&&&&float &&&&&&&&&&
&&&&&&&&&&&&float &&&&&&&&&&
&&&&&&&&&&&&float &&&&&&&&&&
&&&&&&&&&&&&float &&&&&&&&&&
&&&&&&&&&&&&float &&&&&&&&&&relative_
&&&&&&&&&&&&AUncalibratedEvent uncalibrated_
&&&&&&&&&&&&AUncalibratedEvent uncalibrated_
&&&&&&&&&&&&AMetaDataEvent meta_
&&&&&&&&&&&&AHeartRateEvent heart_
&&&&&&&&};
&&&&&&&&union {
&&&&&&&&&&&&uint64_t &&&&&&&data[8];
&&&&&&&&&&&&uint64_t &&&&&&&step_
&&&&&&&&} u64;
&&&&uint32_
&&&&int32_t reserved1[3];
} ASensorE
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:9979次
排名:千里之外
(1)(1)(2)(1)(3)(1)
(window.slotbydup = window.slotbydup || []).push({
id: '4740887',
container: s,
size: '250,250',
display: 'inlay-fix'

我要回帖

更多关于 registerclass 的文章

 

随机推荐