Manifest添加
<uses-permission android:name="android.permission.VIBRATE"/>
package com.example.a;
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.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends Activity {
private SensorManager smg;
private Vibrator vbt;
private static final int SENSOR_SHAKE=10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smg=(SensorManager)this.getSystemService(SENSOR_SERVICE);
vbt=(Vibrator)this.getSystemService(VIBRATOR_SERVICE);
}
@Override
public void onResume(){
super.onResume();
if(smg!=null){
smg.registerListener(sensorEventListener, smg.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),smg.SENSOR_DELAY_NORMAL);
}
}
@Override
public void onPause(){
super.onPause();
if(smg!=null){
smg.unregisterListener(sensorEventListener);
}
}
private SensorEventListener sensorEventListener =new SensorEventListener(){
public void onSensorChanged(SensorEvent event){
float[] values =event.values;
float x = values[0];
float y = values[1];
float z = values[2];
System.out.println("x:"+x+" y:"+y+" z:"+z);
int medumValue =15;
if(Math.abs(x)>medumValue||Math.abs(y)>medumValue||Math.abs(z)>medumValue){
vbt.vibrate(200);
Message msg=new Message();
msg.what=SENSOR_SHAKE;
}
}
public void onAccuracyChanged(Sensor sensor,int assuray){
}
};
Handler handler=new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
switch (msg.what){
case SENSOR_SHAKE:
Toast.makeText(getApplicationContext(), "I know you are shake your phone now", 2000).show();
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}