我是 Java Android 编程的菜鸟(实际上我是整个计算机编程的菜鸟)。我打算在与服务主线程分开的线程中制作加速度计传感器的 SensorEventListener。onSencorChanged 方法在单独的线程中运行良好,但是在运行 Service 后不久,就会发生 ANR。尽管发生了 ANR,但如果我没有在 ANR 发生时终止并按“等待”以保持应用程序运行,那么应用程序会按我的预期运行。长期以来,我一直试图找到解决问题的方法,但我最终无法让我的应用程序停止发生 ANR。
这是我使用 HandleThread 的代码。
public class SwingArmSensorService extends Service {
private SensorManager mSensorManager;
private Sensor mSensor;
private AccelerometerListenerInService listener;
private HandlerThread mSensorThread;
private Handler mSensorHandler;
private static SuperActivityUsingServiceMain activity;
private int mSteps;
private final String SWING_SENSOR_INTENT_STEP_DATA_NAME = "steps";
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Looper.myLooper() == null) {
Looper.prepare();
}
mSensorThread = new HandlerThread("Sensor Thread", Thread.MAX_PRIORITY); //
mSensorThread.start(); //
mSensorHandler = new Handler(mSensorThread.getLooper());
listener = new AccelerometerListenerInService();
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(listener, mSensor, SensorManager.SENSOR_DELAY_NORMAL, mSensorHandler);
mSteps = intent.getIntExtra(SWING_SENSOR_INTENT_STEP_DATA_NAME, 0);
Looper.loop();
...
}
private class AccelerometerListenerInService implements SensorEventListener {
private Handler mainHandler;
private float previousY, currentY;
private float x, y, z;
private final float THRESHOLD = 10f;
public AccelerometerListenerInService() {
mainHandler = new Handler(Looper.getMainLooper());
}
@Override
public void onSensorChanged(SensorEvent event) {
x = event.values[0];
y = event.values[1];
z = event.values[2];
currentY = y;
if (Math.abs(currentY - previousY) > THRESHOLD) {
mSteps++;
// Handle UI at main thread here
mainHandler.post(new Runnable() {
@Override
public void run() {
activity.setTextView(mSteps);
}
});
}
previousY = y;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
}
}
我打算只向您展示与代码问题相关的部分,但这是第一次发布问题堆栈溢出,所以如果我的代码太长,我很抱歉。