android的重力感应测试
由于重力感应是与手机硬件相关的,所以测试起来比较麻烦,有木有办法在模拟器上模拟测试呢?这也是本人比较关心的问题,还好,确实有。那就是sensorsimulator组件。
首先介绍下测试平台:
模拟器:android2.3.3
组件:sensorsimulator1.1.1(见附件)
步骤如下:
1.安装APK,在bin目录下有个SensorSimulatorSettings-1.1.1.apk文件,可通过adb install SensorSimulatorSetting-1.1.1.apk命令安装。
2.设置SensorSimulatorSetting,安装成功后,启动模拟器,进入SensorSimulatorSetting界面,如下:
设置IP:
设置测试模式配置:
有几种重力感应模式:
Fastest:最快更新率(范围在8ms-30ms)
Game:适合游戏的更新率(40ms)
Normal:系统默认值,适合于屏幕方向的变化的更新率(大约200ms)
UI:适合于用户界面的更新率(350ms)
本人在测试游戏的时候选择了game模式,也可以选其它模式试试。
3.第三步是关键,剩下的就是怎么把这个组件应用到实际应用中去了。
先要加上权限,在android的主xml中加入以下代码:
<uses-permission android:name="android.permission.INTERNET"/>
import android.content.Context;import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager;public class AccelerometerHandler implements SensorEventListener {float accelX;float accelY;float accelZ;public AccelerometerHandler(Context context) {SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);if (manager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() != 0) {Sensor accelerometer = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);manager.registerListener(this, accelerometer,SensorManager.SENSOR_DELAY_GAME);}}@Overridepublic void onAccuracyChanged(Sensor sensor, int accuracy) {// nothing to do here}@Overridepublic void onSensorChanged(SensorEvent event) {accelX = event.values[0];accelY = event.values[1];accelZ = event.values[2];}public float getAccelX() {return accelX;}public float getAccelY() {return accelY;}public float getAccelZ() {return accelZ;}}
import org.openintents.sensorsimulator.hardware.Sensor;import org.openintents.sensorsimulator.hardware.SensorEvent;import org.openintents.sensorsimulator.hardware.SensorEventListener;import org.openintents.sensorsimulator.hardware.SensorManagerSimulator;import android.content.Context;import android.hardware.SensorManager;public class AccelerometerSimulatorHandler implements SensorEventListener {float accelX;float accelY;float accelZ;public AccelerometerSimulatorHandler(Context context) {SensorManagerSimulator mSensorManager = SensorManagerSimulator.getSystemService(context,Context.SENSOR_SERVICE);if(mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)!=null){mSensorManager.connectSimulator();Sensor accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);mSensorManager.registerListener(this, accelerometer,SensorManager.SENSOR_DELAY_GAME);}}@Overridepublic void onAccuracyChanged(Sensor sensor, int accuracy) {}@Overridepublic void onSensorChanged(SensorEvent event) {accelX = event.values[0];accelY = event.values[1];accelZ = event.values[2];}public float getAccelX() {return accelX;}public float getAccelY() {return accelY;}public float getAccelZ() {return accelZ;}}