重力感应主要应用于游戏开发中,这个效果非常棒!主要是3个轴,简单理解:那个朝上,值为正,朝下值为负!这个效果我测试过了,由于在手机上才能实现重力感应,所以没有效果图。见谅!转载请标明出处:http://blog.csdn.net/wdaming1986/article/details/6752232
一、MainActivity。java的代码:
package com.ray.test;
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 MainActivity extends Activity{
private SensorManager sensorMgr;
private TextView show_TextView;
Sensor sensor;
private float x, y, z;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
show_TextView = (TextView)findViewById(R.id.text_view);
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
SensorEventListener lsn = new SensorEventListener()
{
@Override
public void onSensorChanged(SensorEvent e) {
// TODO Auto-generated method stub
x = e.values[SensorManager.DATA_X];
y = e.values[SensorManager.DATA_Y];
z = e.values[SensorManager.DATA_Z];
setTitle("x="+(int)x+","+"y="+(int)y+","+"z="+(int)z);
show_TextView.setText("x="+(int)x+", "+"y="+(int)y+", "+"z="+(int)z);
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
}; //注册listener,第三个参数是检测的精确度
sensorMgr.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_GAME);
}
}
二、main.xml的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25pt"
/>
</LinearLayout>