android 重力感应初步认识
16lz
2021-01-23
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的测试工作,以前一直用莫机器太费劲了。今天发现这个办法好使。
更多相关文章
- golang1.11改了哪里东西
- 造了一个 Redis 分布锁的轮子,没想到还学到这么多东西!!!
- 就想写个爬虫,我到底要学多少东西啊?
- 三十天写三十个网站后,我学到的东西[每日前端夜话0x3C]
- 之所以被裁也许是少了这些东西 [每日前端夜话(0x0A)]
- 花了3天总结的RabbitMQ实用技巧,有点东西!
- 面试前需要了解的东西
- 老大说:谁要再用double定义商品金额,就自己收拾东西走
- Js/Html/Css 我好像写了个奇怪的东西