SensorEventListener在单独的线程线程、SensorEventListener

由网友(你不必长高因为我会弯腰i)分享简介:这似乎是一个基本的问题,但寻找了一会儿,与它玩耍后,我来的地步,一些帮助,将AP preciated。我想在从UI一个单独的线程SensorEventListener运行,使那些需要的计算,当事件进来不会减慢UI发生。 This seems like a basic question, but after searc...

这似乎是一个基本的问题,但寻找了一会儿,与它玩耍后,我来的地步,一些帮助,将AP preciated。我想在从UI一个单独的线程SensorEventListener运行,使那些需要的计算,当事件进来不会减慢UI发生。

This seems like a basic question, but after searching for a while and playing with it, I've come to the point where some help would be appreciated. I would like to have a SensorEventListener run in a separate thread from the UI, so that computations that need to occur when events come in won't slow down the UI.

我的最新尝试是这样的:

My latest attempt looks like:

class SensorThread extends Thread {
    SensorManager mSensorManager;
    Sensor mSensor;

    public void run() {
        Log.d( "RunTag", Thread.currentThread().getName() ); // To display thread
        mSensorManager = (SensorManager)getSystemService( SENSOR_SERVICE  );
        mSensor = mSensorManager.getDefaultSensor( Sensor.TYPE_ACCELEROMETER );
        MySensorListener msl = new MySensorListener();
        mSensorManager.registerListener(msl, mSensor, SensorManager.SENSOR_DELAY_UI );
    }

    private class MySensorListener implements SensorEventListener {
        public void onAccuracyChanged (Sensor sensor, int accuracy) {}
        public void onSensorChanged(SensorEvent sensorEvent) {
            Log.d( "ListenerTag", Thread.currentThread().getName() ); // To display thread
        }
    }

在活动的(或服务的)的onCreate(),我创建了一个SensorThread对象,并调用它的start()方法。正如你所期望的,调试日志显示了在新线程的RunTag条目。但onSensorChanged()的ListenerTag在主线程中运行,即使它的对象被实例化的新线程。我要如何改变这种状况?

In the activity's (or service's) onCreate(), I create a SensorThread object and call its start() method. As you would expect, the debug log shows the "RunTag" entry in the new thread. But onSensorChanged()'s "ListenerTag" is running in the main thread, even though its object is instantiated in the new thread. How do I change that?

推荐答案

您可以在后台线程接收传感器事件。而不是

You can receive sensor event in a background thread. Instead of

mSensorManager.registerListener(msl, mSensor, SensorManager.SENSOR_DELAY_UI );

您可以用处理器指的是辅助线程声明它。一个线程的运行循环是这样的:

you can declare it with a handler referring to a secondary thread. The run loop of a thread looks like this:

...
run {
    Looper.prepare;
    Handler handler = new Handler();
    ...
    mSensorManager.registerListener(msl, mSensor, SensorManager.SENSOR_DELAY_UI, handler );
    Looper.loop();
}
...
阅读全文

相关推荐

最新文章