android 利用重力感应监测手机摇晃,做出相应反应

moira 2011-02-21

这个是利用手机摇晃,做出一定反应。具体功能自己开发

packagecom.ray.test;

importandroid.R.integer;

importandroid.app.Activity;

importandroid.hardware.Sensor;

importandroid.hardware.SensorEvent;

importandroid.hardware.SensorEventListener;

importandroid.hardware.SensorListener;

importandroid.hardware.SensorManager;

importandroid.os.Bundle;

publicclassSensorTestextendsActivityimplementsSensorListener{

//privateSensorManagersensorMgr;

//Sensorsensor=sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

privatefloatx,y,z,last_x,last_y,last_z;

privatelonglastUpdate;

protectedvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

SensorManagersensorMgr=(SensorManager)getSystemService(SENSOR_SERVICE);

Sensorsensor=sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

sensorMgr.registerListener(this,SensorManager.SENSOR_ACCELEROMETER,

SensorManager.SENSOR_DELAY_GAME);

}

publicvoidonAccuracyChanged(intsensor,intaccuracy){

//TODOAuto-generatedmethodstub

}

privatestaticfinalintSHAKE_THRESHOLD=5000;

//这个控制精度,越小表示反应越灵敏

publicvoidonSensorChanged(intsensor,float[]values){

//TODOAuto-generatedmethodstub

if(sensor==SensorManager.SENSOR_ACCELEROMETER){

longcurTime=System.currentTimeMillis();

//每100毫秒检测一次

if((curTime-lastUpdate)>100){

longdiffTime=(curTime-lastUpdate);

lastUpdate=curTime;

x=values[SensorManager.DATA_X];

y=values[SensorManager.DATA_Y];

z=values[SensorManager.DATA_Z];

floatspeed=Math.abs(x+y+z-last_x-last_y-last_z)/diffTime*10000;

if(speed>SHAKE_THRESHOLD){

//这里写上自己的功能代码

setTitle("x="+(int)x+","+"y="+(int)y+","+"z="+(int)z);

}

last_x=x;

last_y=y;

last_z=z;

}

}

}

}

相关推荐