微信摇一摇

代码参考:http://www.eoeandroid.com/thread-323631-1-1.html

微信摇一摇主要用了加速度传感器,代码如下:
public class MainActivity extends Activity {
private SensorManager sensorManager;
private Vibrator vibrator;

private static final String TAG = "SensorTest";
private static final int SENSOR_SHAKE = 10;
private long lastUpdateTime=-1;
private static long INTERVAL_TIME=1000;
private static int i=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
}

@Override
protected void onResume() {
super.onResume();
if (sensorManager != null) {// 注册监听器
sensorManager.registerListener(sensorEventListener, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
// 第一个参数是Listener,第二个参数是所得传感器类型,第三个参数值获取传感器信息的频率
}
}

@Override
protected void onPause() {
super.onPause();
if (sensorManager != null) {// 取消监听器
sensorManager.unregisterListener(sensorEventListener);
}
}
/**
* 重力感应监听
*/
private SensorEventListener sensorEventListener = new SensorEventListener() {

@Override
public void onSensorChanged(SensorEvent event) {
// Log.e(TAG,"onSensorChanged");
// 现在检测时间 
        long currentUpdateTime = System.currentTimeMillis(); 
       
        //第一次进入,更新lastUpdateTime
//         if(lastUpdateTime==-1){
//         lastUpdateTime=currentUpdateTime;
////         return ;
//         }
       
        // 两次检测的时间间隔 
        long timeInterval = currentUpdateTime - lastUpdateTime; 
        // 判断是否达到了检测时间间隔 
       
        if (timeInterval < INTERVAL_TIME ) 
            return; 

// 传感器信息改变时执行该方法
float[] values = event.values;
float x = values[0]; // x轴方向的重力加速度,向右为正
float y = values[1]; // y轴方向的重力加速度,向前为正
float z = values[2]; // z轴方向的重力加速度,向上为正

int medumValue = 14;
if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) {

// 现在的时间变成last时间 
lastUpdateTime = currentUpdateTime; 

Log.e(TAG, "x轴方向的重力加速度" + x +  ";y轴方向的重力加速度" + y +  ";z轴方向的重力加速度" + z);

vibrator.vibrate(200);
Message msg = new Message();
msg.what = SENSOR_SHAKE;
handler.sendMessage(msg);
}
}

@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
Log.e(TAG,"onAccuracyChanged");
}
};

/**
* 动作执行
*/
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SENSOR_SHAKE:
i++;
Toast.makeText(MainActivity.this, "检测到摇晃,执行操作! "+i, Toast.LENGTH_SHORT).show();
Log.e(TAG, "检测到摇晃,执行操作!"+i);
break;
}
}

};

}

别忘了震动权限:
<uses-permission android:name="android.permission.VIBRATE"/>

你可能感兴趣的:(android)