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); }