Android 压力传感器获取当前压强

1)压力传感器返回当前的压强,单位是百帕斯卡hectopascal(hPa)。

2)具体代码如下

package com.example.androidapp;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	private SensorManager mSensorManager=null;
	private Sensor mSensor=null;
	private TextView textView1=null;
	private Button button1=null;
	private Button button2=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		textView1=(TextView)findViewById(R.id.textView1);
		/*获取系统服务(SENSOR_SERVICE)返回一个SensorManager对象*/
		mSensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
		/*通过SensorManager获取相应的(压力传感器)Sensor类型对象*/
		mSensor=mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
		/*注册相应的SensorService*/
		button1=(Button)findViewById(R.id.button1);
		button1.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				mSensorManager.registerListener(mSensorEventListener, mSensor
						, SensorManager.SENSOR_DELAY_NORMAL);
			}
		});
		/* 销毁相应的SensorService
		 * 很关键的部分,注意,说明文档中提到,即使Activity不可见的时候,感应器依然会继续工作
		 * 所以一定要关闭触发器,否则将消耗用户大量电量*/
		button2=(Button)findViewById(R.id.button2);
		button2.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mSensorManager.unregisterListener(mSensorEventListener, mSensor);
			}
		});
	}
	/*声明一个SensorEventListener对象用于侦听Sensor事件,并重载onSensorChanged方法*/
	private final SensorEventListener mSensorEventListener=new SensorEventListener() {
		
		@Override
		public void onSensorChanged(SensorEvent event) {
			if(event.sensor.getType()==Sensor.TYPE_PRESSURE){
				/*压力传感器返回当前的压强,单位是百帕斯卡hectopascal(hPa)。*/
				float pressure=event.values[0];
				textView1.setText(String.valueOf(pressure)+"hPa");
			}
		}
		
		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub
			
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}


你可能感兴趣的:(android,压力传感器,当前压强,TYPE_PRESSURE)