首页 > 代码库 > android 加速度传感器 ---摇一摇
android 加速度传感器 ---摇一摇
package com.eboy.testyaoyiyao;
import java.text.SimpleDateFormat;
import java.util.Date;
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.os.Vibrator;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
//Sensor管理器
private SensorManager mSensorManager = null;
//震动
private Vibrator mVibrator = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mVibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent arg0) {
// TODO Auto-generated method stub
int sensorType = arg0.sensor.getType();
float[] values = arg0.values;
if (sensorType == Sensor.TYPE_ACCELEROMETER){
if (Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14 || Math.abs(values[2]) > 14){
mVibrator.vibrate(100);
//进行手机晃动的监听 ,可以在这里实现 intent 等效果
}
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
super.onStop();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
super.onPause();
}
}
android 加速度传感器 ---摇一摇