android 重力感应初步认识
android? 重力感应初步认识,写了个测试demo,来认识android 的重力感应。
上代码:
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 ASe extends Activity {private int xx, yy, zz;SensorManager sensorMgr;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);final TextView t = (TextView) findViewById(R.id.te);Sensor sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);SensorEventListener lsn = new SensorEventListener() {public void onSensorChanged(SensorEvent e) {float x = e.values[SensorManager.DATA_X];float y = e.values[SensorManager.DATA_Y];float z = e.values[SensorManager.DATA_Z];xx = (int) x;yy = (int) y;zz = (int) z;String re = controlCar(xx, yy);// t.setText("x=" + (int) x + "," + "y=" + (int) y + "," + "z="// + (int) z+"-------"+re);t.setText(xx + " " + yy + "-------" + re);}public void onAccuracyChanged(Sensor s, int accuracy) {}};// 注册listener,第三个参数是检测的精确度sensorMgr.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_GAME);}public String controlCar(int xx, int yy) {String flag = "";if (yy < 0) {// 前方if (xx >= -3 && xx <= 3) {// 向正前方前进flag = "向正前方前进";} else {if (xx < 0) {// 右前flag = "右前";} else {// 左前flag = "左前";}}} else if (yy > 0) {// 后方if (xx >= -3 && xx <= 3) {// 向正后方前进flag = "向正后方前进";} else {if (xx < 0) {// 右后flag = "右后";} else {// 左后flag = "左后";}}} else {if (xx == 0) {// xx=0,yy=0,此时车停止flag = "停止";} else {// y=0,此时只有正左,正右转向if (xx < 0) {// 正右flag = "正右";} else {// 正左flag = "正左";}}}return flag;}}
?
?
AndroidManifest.xml 和 main.xml 就不贴了没什么东西,main.xml里面没什么东西 就一个TextView,id命名为te
?
另外:(是我太笨了一直没有这个办法) 发现可以直接把手机连接在电脑上,通过eclipse直接把程序发布到手机上进行android的测试工作,以前一直用莫机器太费劲了。今天发现这个办法好使。