二话不说直接开车:
import android.content.Intent;import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager;import android.os.Handler;import android.os.Message;import android.os.Vibrator;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.widget.Toast;import .dol.mytry.R;import .dol.mytry.asynctask.Main2Activity;/*** 手机摇一摇* */public class TsetSensorActivity extends AppCompatActivity {private SensorManager sensorManager;private Vibrator vibrator;private static final String TAG="TsetSensorActivity";private static final int SENSOR_SHAKE=10;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_tset_sensor);sensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);vibrator= (Vibrator) getSystemService(VIBRATOR_SERVICE);}@Overrideprotected void onResume() {super.onResume();if(sensorManager!=null){//注册监听器sensorManager.registerListener(sensorEventListener,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL);//第一个参数是Listener,第二个参数是所得传感器类型,第三个参数值获取传感器信息的频率}}@Overrideprotected void onStop() {super.onStop();if(sensorManager!=null){sensorManager.unregisterListener(sensorEventListener);}}/*** 重力感应监听* */private SensorEventListener sensorEventListener=new SensorEventListener() {@Overridepublic void onSensorChanged(SensorEvent event) {//传感器信息改变时执行该方法float[] values=event.values;float x=values[0]; // x轴方向的重力加速度,向右为正float y=values[1]; // y轴方向的重力加速度,向前为正float z=values[2]; // z轴方向的重力加速度,向上为正Log.i(TAG,"x轴方向的重力加速度"+x+";y轴方向的重力加速度"+y+";z轴方向重力加速度"+z);//一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态int medumValue =19;//如果不铭感请自行调低该数值,低于10的话就不行了,因为Z轴上的加速度本身就达到了10if (Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue) {vibrator.vibrate(200);Message msg = new Message();msg.what = SENSOR_SHAKE;handler.sendMessage(msg);}}@Overridepublic void onAccuracyChanged(Sensor sensor, int accuracy) {}};/**动作执行*/Handler handler=new Handler(){public void handleMessage(Message msg){super.handleMessage(msg);switch (msg.what){case SENSOR_SHAKE:Toast.makeText(TsetSensorActivity.this,"检到摇晃,执行操作",Toast.LENGTH_SHORT).show();Intent intent=new Intent(TsetSensorActivity.this, Main2Activity.class);startActivity(intent);Log.i(TAG,"检测到摇晃,执行操作");break;}}};}当然千万不要忘记权限哦:<uses-permission android:name="android.permission.VIBRATE"/>震动的权限。