Android之传感器(二)之电子罗盘

电子罗盘:

1.  /* 取得SensorManager */
    SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 

 

2.   /* 取得需要的Sensor,并注册SensorEventListener */

    mSensorManager.registerListener(mSensorEventListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),SensorManager.SENSOR_DELAY_NORMAL); 

 

3.   /*实现监听器,并重写其中的方法*/

private final SensorEventListener mSensorEventListener = new SensorEventListener()

  {
public void onAccuracyChanged(Sensor sensor, int accuracy)    {       }    

public void onSensorChanged(SensorEvent event)    {

/* 判断Sensor的种类 */     

if (event.sensor.getType() == Sensor.TYPE_ORIENTATION)      {       

/* 取得X值资料        

 * x_data是水平值     

 * 由于分成8个方向,所以每个方向为45°

 * */       

float x_data = event.values[SensorManager.DATA_X];       

//北方为337.5°至22.5°       

if ((x_data > 0 && x_data <= 22.5) || x_data > 337.5)        {

TextView01.setText("北方" + String.valueOf(x_data));        }        

//东北方为22.5°至67.5°       

else if (x_data > 22.5 && x_data <= 67.5)        {         

TextView01.setText("东北方" + String.valueOf(x_data));        }        

//东方为67.5°至112.5°       

else if (x_data > 67.5 && x_data <= 112.5)        {         

TextView01.setText("东方" + String.valueOf(x_data));        }        

//东南方为112.5°至157.5°       

else if (x_data > 112.5 && x_data <= 157.5)        {         

TextView01.setText("东南方" + String.valueOf(x_data));        }        

//南方为157.5°至202.5°       

else if (x_data > 157.5 && x_data <= 202.5)        {         

TextView01.setText("南方" + String.valueOf(x_data));        }        

//西南方为202.5°至247.5°       

else if (x_data > 202.5 && x_data <= 247.5)        {         

TextView01.setText("西南方" + String.valueOf(x_data));        }        

//西方为247.5°至292.5°       

else if (x_data > 247.5 && x_data <= 292.5)        {         

TextView01.setText("西方" + String.valueOf(x_data));        }        

//西北方为292.5°至337.5°       

else if (x_data > 292.5 && x_data <= 337.5)        {         

TextView01.setText("西北方" + String.valueOf(x_data));        }      }    }  };

 

 

posted on 2012-06-24 18:41  lee0oo0  阅读(2214)  评论(0编辑  收藏  举报