这里我们利用手机自带的传感器实现一个简单的电子罗盘小实例,大家可以学习到SensorManager类、SensorEventListener 及其覆写方法的使用。
首先我们创建一个布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="@string/hello"
android:textSize="16sp"
android:textColor="@android:color/black" >
</TextView>
</RelativeLayout>
接着Activity文件:
package com.yayun.activity;
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.widget.TextView;
public class SensorDemo extends Activity
{
private TextView mShowTextView;
private SensorManager mSensorManager;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mShowTextView = (TextView) findViewById(R.id.tv_show);
/* 取得SensorManager */
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
@Override
protected void onResume()
{
super.onResume();
/* 取得方守性的Sensor,并注册SensorEventListener */
mSensorManager.registerListener(mSensorEventListener, mSensorManager
.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause()
{
/* 取消注册SensorEventListener */
mSensorManager.unregisterListener(mSensorEventListener);
super.onPause();
}
private final SensorEventListener mSensorEventListener = new SensorEventListener()
{
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
@Override
public void onSensorChanged(SensorEvent event)//变换
{
/* 判断Sensor的种类 */
if (event.sensor.getType() == Sensor.TYPE_ORIENTATION)
{
/* 取得X值资料 */
float x_data =