发布于 

SensorEventListener接口实现摇一摇功能

更优雅的实现摇一摇功能

定义参数
1
2
3
private long lastUpdate = 0;
private float last_x, last_y, last_z;
private static final int SHAKE_THRESHOLD = 600;
重写重力感应方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
Sensor mySensor = sensorEvent.sensor;

if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float x = sensorEvent.values[0];
float y = sensorEvent.values[1];
float z = sensorEvent.values[2];

long curTime = System.currentTimeMillis();

if ((curTime - lastUpdate) > 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;

float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

if (speed > SHAKE_THRESHOLD) {
if (isForeground(MainActivity.this, "MainActivity")) {
Intent intent = new Intent(MainActivity.this, AboutActivity.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
}

last_x = x;
last_y = y;
last_z = z;
}
}
}

@Override
public void onAccuracyChanged(Sensor sensor, int i) {

}
利用抽象类实现接口
1
2
3
SensorManager senSensorManager =(SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
senSensorManager.registerListener(this, senAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
注意细节
  • 抽象类
  • 该抽象类接口通过继承子类的implement SensorEventListener来实现
  • 清单权限
  • 重力加速度感知权限
  • android.hardware.sensor.accelerometer