Android重力感应

android中的很多游戏的游戏都使用了重力感应的技术,就研究了一下重力感应
以屏幕的左下方为原点,箭头指向的方向为正。从-10到10,以浮点数为等级单位,想象以下情形:

手机屏幕向上(z轴朝天)水平放置的时侯,(x,y,z)的值分别为(0,0,10);
手机屏幕向下(z轴朝地)水平放置的时侯,(x,y,z)的值分别为(0,0,-10);
手机屏幕向左侧放(x轴朝天)的时候,(x,y,z)的值分别为(10,0,0);
手机竖直(y轴朝天)向上的时候,(x,y,z)的值分别为(0,10,0);
其他的如此类推,规律就是:朝天的就是正数,朝地的就是负数。
利用x,y,z三个值求三角函数,就可以精确检测手机的运动状态了。

代码实例:
AndroidManifest.xml

<uses-permission android:name="android.hardware.sensor.accelerometer"/>

代码很简单
Java Code:

package com.learn.sunboy;  
  
import android.app.Activity;  
import android.hardware.Sensor;  
import android.hardware.SensorEvent;  
import android.hardware.SensorEventListener;  
import android.hardware.SensorManager;  
import android.os.Bundle;  
import android.view.MotionEvent;  
import android.widget.Toast;  
  
public class TestSensor extends Activity{  
   
   private SensorManager mSensorManager = null;  
   private Sensor mSensor = null;  
   private float x, y, z;  
   
   @Override  
   protected void onCreate(Bundle savedInstanceState){  
   super.onCreate(savedInstanceState);  
   
   mSensorManager = (SensorManager)this.getSystemService(SENSOR_SERVICE);        
   mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);  
   }  
   
   
   SensorEventListener lsn = new SensorEventListener() {  
   
   @Override  
   public void onSensorChanged(SensorEvent event) {  
   x = event.values[SensorManager.DATA_X];  
   y = event.values[SensorManager.DATA_Y];  
   z = event.values[SensorManager.DATA_Z];  
   }  
   
   @Override  
   public void onAccuracyChanged(Sensor sensor, int accuracy) {  
   // TODO Auto-generated method stub  
   
   }  
   };  
   
   @Override  
   public boolean onTouchEvent(MotionEvent event){  
  
   if(event.getAction() == MotionEvent.ACTION_DOWN){  
   
   mSensorManager.registerListener(lsn, mSensor, SensorManager.SENSOR_DELAY_GAME);  
   
   String str = "x=" + x + "; y=" + y + "; z=" + z;  
   Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();  
   }  
   
   return super.onTouchEvent(event);  
   }  
   
   @Override  
   public void onResume(){  
   mSensorManager.registerListener(lsn, mSensor, SensorManager.SENSOR_DELAY_GAME);  
   
   super.onResume();  
   }  
   
   
   @Override  
   public void onPause(){  
   mSensorManager.unregisterListener(lsn);  
   
   super.onPause();  
   }  
   
}