復制代碼 代碼如下:
package com.eboy.testyaoyiyao;
import java.text.SimpleDateFormat;
import java.util.Date;
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.Vibrator;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener {
//Sensor管理器
private SensorManager mSensorManager = null;
//震動
private Vibrator mVibrator = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mVibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent arg0) {
// TODO Auto-generated method stub
int sensorType = arg0.sensor.getType();
float[] values = arg0.values;
if (sensorType == Sensor.TYPE_ACCELEROMETER){
if (Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14 || Math.abs(values[2]) > 14){
mVibrator.vibrate(100);
TextView tv1 = (TextView)findViewById(R.id.textView1);
SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
tv1.setText(f.format(new Date()) + "手機搖動了...");
}
}
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
super.onStop();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
mSensorManager.unregisterListener(this);
super.onPause();
}
}