码迷,mamicode.com
首页 > 移动开发 > 详细

Android传感器应用之:摇一摇小例子

时间:2015-04-10 15:30:00      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:android开发   传感器   

public class MainActivity extends Activity {
/**SensorManager对象*/
private SensorManager mSensorManager;
/**Vibrator对象*/
private Vibrator mVibrator;
/**定义一个常量值*/
private static final int SENSOR_VALUE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**取得系统感应管理器服务SensorManager*/
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
/**获取震动服务mVibrator*/
mVibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
}

@Override
protected void onResume() {
super.onResume();
/**在onResume中注册监听*/
if (mSensorManager != null) {
mSensorManager.registerListener(mSensorEventListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
}


@Override
protected void onPause() {
super.onPause();
/**取消注册监听事件*/
if (mSensorManager != null) {
mSensorManager.unregisterListener(mSensorEventListener);
}
}
/**监听手机摇晃的监听器实现*/
private SensorEventListener mSensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
/**传感器数据变动*/
/**获取手机上三个方向上的感应坐标*/
float[] values = event.values;
float x = values[0]; 
float y = values[1]; 
float z = values[2]; 
int sensorValue = 20;
if (Math.abs(x) > sensorValue || Math.abs(y) > sensorValue || Math.abs(z) > sensorValue) {
/**产生震动,时间200毫秒*/
mVibrator.vibrate(200);
/**hanler发信息出去,等待处理*/
Message msg = new Message();
msg.what = SENSOR_VALUE;
handler.sendMessage(msg);
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
/**
* 这里指传感器精度发生改变:这种情况中,系统会调用onAccuracyChanged()方法,它提供了你要引用的发生精度变化的Sensor对象。
* 精度使用以下四个状态常量之一来代表的:
* SENSOR_STATUS_ACCURACY_LOW
* SENSOR_STATUS_ACCURACY_MEDIUM
* SENSOR_STATUS_ACCURACY_HIGH
* SENSOR_STATUS_UNRELIABLE
*/
}
};


@SuppressLint("HandlerLeak")
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SENSOR_VALUE:
Toast.makeText(MainActivity.this, "手机摇晃了....", Toast.LENGTH_SHORT).show();
break;
}
}


};


}

Android传感器应用之:摇一摇小例子

标签:android开发   传感器   

原文地址:http://blog.csdn.net/true100/article/details/44980203

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!