利用Sensor实现android手机类似于微信摇一摇

Mr傅 2012-06-11

传感器有几种类型:

方向传感器:Sensor.TYPE_ORIENTATION

加速度(重力)传感器:Sensor.TYPE_ACCELEROMETER

光线传感器:Sensor.TYPE_LIGHT

磁场传感器:Sensor.TYPE_MAGNETIC_FIELD

距离(临近性)传感器:Sensor.TYPE_PROXIMITY

温度传感器: Sensor.TYPE_TEMPERATURE

这里我们利用的是加速度传感器

package com.jamin.sensor;

import android.app.Activity;
import android.app.Service;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SensorTestActivity extends Activity implements SensorEventListener{
	/** Called when the activity is first created. */


	TextView tv = null;
	Button button = null;
	SensorManager sensorManager = null;
	Vibrator vibrator = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		button = (Button) findViewById(R.id.button1);
		tv = (TextView) findViewById(R.id.textview1);
		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// TODO Auto-generated method stub
				tv.setText("文本复原");	
			}
		});

		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);


	}






	@Override
	protected void onPause() {

		// TODO Auto-generated method stub
		super.onPause();
		sensorManager.unregisterListener(this);
	}






	@Override
	protected void onResume() {

		// TODO Auto-generated method stub
		super.onResume();
		sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);

	}






	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		//当传感器精度改变时回调该方法,Do nothing.
	}



	@Override
	public void onSensorChanged(SensorEvent event) {

		
		int sensorType = event.sensor.getType();
		//values[0]:X轴,values[1]:Y轴,values[2]:Z轴
		float[] values = event.values;
		if(sensorType == Sensor.TYPE_ACCELEROMETER){			
			if((Math.abs(values[0])>17||Math.abs(values[1])>17||Math.abs(values[2])>17)){
				Log.d("sensor ", "============ values[0] = " + values[0]);
				Log.d("sensor ", "============ values[1] = " + values[1]);
				Log.d("sensor ", "============ values[2] = " + values[2]);
				tv.setText("摇一摇");
				//摇动手机后,再伴随震动提示~~
				vibrator.vibrate(500);
			}


		}
	}







}
 记得在onresume和onpause的时候开关sensor的监听事件。

如果想调整sensor的敏感程度,就去修改,value[0,1,2] 大于的上限。

相关推荐