//感應管理器
private SensorManager mSensorManager;
//震動器
private Vibrator vibrator;
//Active Manager
ActivityManager activityManager ;
//1獲得硬體資訊
mSensorManager = (SensorManager) getSystemService(SENSOR_
SERVICE);
vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//2 判斷當前手機是否帶加速度感應器,如果不帶,直接結束,不啟動服務
List<Sensor> sensors = mSensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(sensors!=null)
if(sensors.size()==0)
return;
//3產生感應偵聽事件
SensorEventListener sensorelistener=new SensorEventListener(){
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
//感應器發生改變
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
int sensorType = event.sensor.getType();
//讀取搖一搖敏感值
int shakeSenseValue=Integer.parseInt(getResources().getString(R.string.shakeSenseValue)); ;
//values[0]:X軸,values[1]:Y軸,values[2]:Z軸
float[] values = event.values;
if(sensorType == Sensor.TYPE_ACCELEROMETER){
if((Math.abs(values[0])>shakeSenseValue||Math.abs(values[1])>shakeSenseValue||Math.abs(values[2])>shakeSenseValue)){
//觸發事件,執行開啟應用行為
vibrator.vibrate(500);
}
}
}
};
//4註冊偵聽事件
mSensorManager.registerListener(sensorelistener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}