android重力感应初步认识

xiaoxiao2021-03-01  16

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; @Override public 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的测试工作,以前一直用莫机器太费劲了。今天发现这个办法好使。

相关资源:敏捷开发V1.0.pptx
转载请注明原文地址: https://www.6miu.com/read-3450181.html

最新回复(0)