Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

android - SensorEventListener in separate thread

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
        }
    }

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A little late, but if others still want to know, here is a good way to achieve this. As always when multithreading, make sure you know what you are doing and take the time to so it right, to avoid those weird errors. Have fun!

Class members:

private HandlerThread mSensorThread;
private Handler mSensorHandler;

in OnCreate or when registering:

mSensorThread = new HandlerThread("Sensor thread", Thread.MAX_PRIORITY);
mSensorThread.start();
mSensorHandler = new Handler(mSensorThread.getLooper()) //Blocks until looper is prepared, which is fairly quick
yourSensorManager.registerListener(yourListener, yourSensor, interval, mSensorHandler);

When unregistering, also do:

mSensorThread.quitSafely();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...