Android简单的重力感应DEMO

好多天都没日志了,感觉有点过意不去,然后就写这一篇,反正也是为下一次日报做准备,上代码:

package com.main;

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.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private String info = new String();
	
	private TextView textView1;
	private TextView textView2;
	private TextView textView3;
	private TextView textView4;
	
    // 感应器管理器
    private SensorManager sensorMgr;
     
    // 得到加速感应器
    Sensor sensor;
     
    // 定义各坐标轴上的重力加速度
    private float x, y, z;
 
    // 创建activity
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        
        // 得到当前手机传感器管理对象
        sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
         
        // 加速重力感应对象
        sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
         
        
        
        // 实例化一个监听器
        SensorEventListener lsn = new SensorEventListener() {
            // 实现接口的方法
            public void onSensorChanged(SensorEvent e) {
                // 得到各轴上的重力加速度
                x = e.values[SensorManager.DATA_X];
                y = e.values[SensorManager.DATA_Y];
                z = e.values[SensorManager.DATA_Z];
                
                textView1.setText("X:" + x);
                textView2.setText("Y:" + y);
                textView3.setText("Z:" + z);
                
                info = "X:" + x + "," + "Y:" + y + "," + "Z:" + z;
                Log.e("信息", info);
                
                if (x < 5) {
					textView4.setText("请保持手机的垂直放置");
				}else {
					if (y > 1) {
						textView4.setText("目前的方向是向右拐");
					}else if(y < -1){
						textView4.setText("目前的方向是向左拐");
					}else if (y <= 1 && y >= -1) {
						textView4.setText("目前的方向是直走.");
					}
				}
            }
 
            public void onAccuracyChanged(Sensor s, int accuracy) {}
        };
        // 注册listener,第三个参数是检测的精确度
        sensorMgr.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_GAME);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    private void findViews() {
		textView1 = (TextView)findViewById(R.id.textView1);
		textView2 = (TextView)findViewById(R.id.textView2);
		textView3 = (TextView)findViewById(R.id.textView3);
		textView4 = (TextView)findViewById(R.id.textView4);
	}
}

就是这样,然后你的手机就基本上是一个方向盘了,如果需要发送给某个嵌入式设备,就直接用socket好了,加个线程什么的,也不是很麻烦.就这样了,

 

Leave a Reply

Your email address will not be published. Required fields are marked *