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;

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

  • 大小: 1.3 MB
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值