单独线程中的 SensorEventListener [英] SensorEventListener in separate thread

查看:35
本文介绍了单独线程中的 SensorEventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个基本问题,但在搜索了一段时间并尝试了之后,我已经到了需要一些帮助的地步.我想让 SensorEventListener 在与 UI 不同的线程中运行,以便在事件进入时需要进行的计算不会减慢 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.

我最近的尝试如下:

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?

推荐答案

有点晚了,但如果其他人仍然想知道,这里有一个很好的方法来实现这一点.与多线程处理一样,请确保您知道自己在做什么,并花时间正确处理,以避免出现那些奇怪的错误.玩得开心!

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!

班级成员:

private HandlerThread mSensorThread;
private Handler mSensorHandler;

在 OnCreate 或注册时:

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();

这篇关于单独线程中的 SensorEventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆