如果智能手机倒置,我正在尝试从传感器事件侦听器启动子活动。我写的初始代码是这样的:
public class MySensorListener implements SensorEventListener{
boolean mIsStarted = false;
public void start(Context context) {
mIsStarted = false;
SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
manager.registerListener(this, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
public void stop(Context context) {
mIsStarted = false;
SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
manager.unregisterListener(this);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float z = event.values[2];
if (z < -8f) {
if (!mIsStarted) {
mIsStarted = true;
// start child activity
}
} else if (z > -7f) {
if (mIsStarted) {
mIsStarted = false;
// stop child activity
}
}
}
}
}
现在我遇到了问题,Android 4 设备启动活动大约是三次而不是一次。我认为这是因为 onSensorChanged 方法在很短的时间内被频繁调用。所以我尝试同步它:
public class MySensorListener implements SensorEventListener{
// ...
public synchronized void onSensorChanged(SensorEvent event) {
// ...
}
}
那没有用,所以我尝试了更多方法:
-同步“this”对象
public class MySensorListener implements SensorEventListener{
// ...
public void onSensorChanged(SensorEvent event) {
synchronized(this){
// ...
}
}
}
- 同步 isStarted 变量:
public class MySensorListener implements SensorEventListener{
Boolean mIsStarted = false;
// ...
public void onSensorChanged(SensorEvent event) {
synchronized(mIsStarted){
// ...
}
}
}
- 使用 AtomicBoolean:
public class MySensorListener implements SensorEventListener{
public AtomicBoolean mIsStarted = new AtomicBoolean(false);
// ...
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float z = event.values[2];
if (z < -8f) {
if (mIsStarted.compareAndSet(false, true)) {
// start child activity
}
} else if (z > -7f) {
if (mIsStarted.compareAndSet(true, false)) {
// stop child activity
}
}
}
}
}
这些方法都不起作用,所以我想知道为什么会发生这种情况以及我如何改变它并使其工作?
先感谢您!