【问题标题】:Can I get a non-blocking Looper?我可以得到一个非阻塞的 Looper 吗?
【发布时间】:2012-09-08 22:53:16
【问题描述】:

我有一个带有消息循环器的线程,用于一些位置计算。 为此,我呼吁:

LocationManager.requestLocationUpdates(mProvider, mMinTime, mMinDistance, (LocationListener)this, looper);

为了得到一个有效的 Looper 对象,我像这样准备我的线程:

    Looper.prepare();
    mLooper = Looper.myLooper();
    handler = [...]
    Looper.loop();

但是是否有可能在同一个线程中有一个额外的while循环用于数据处理?

也许我可以以某种方式派生出自己的 Looper 并手动处理消息,但是如何?

【问题讨论】:

    标签: android multithreading looper


    【解决方案1】:

    这种事没必要。

    当您调用 Looper.loop() 时,线程会运行它的处理程序的消息队列。因此,Handler 收到的任何消息或帖子都会在 Looper 线程上进行处理。

    像这样:

    Thread t1 = new Thread(new Runnable()
    {
        @Override
        public void run() {
    
        Looper.prepare();
    
        final Handler h = new Handler();
            final boolean isRunning = true;
    
            Thread t2 = new Thread(new Runnable() {
    
                @Override
                public void run()
                {
                    //Do stuff like download
    
    
                    h.post(new Runnable() {
    
                         @Override
                         public void run() {
    
                             //Post stuff to Thread t1
    
                         }
                    });
    
                    isRunning = false;
                    h.getLooper().quit();
                }
            }
    
        while(isRunning)
        {
                //This will ensure that the messages sent by the Handler, be called inside the Thread
        Looper.loop();
        }
        }
    }   
    

    这样可以确保线程在响应处理程序帖子和回调所需的时间内保持运行。您还可以使用自己的 handleMessage 方法扩展 Handler,它们也会在 Thread t1 中被调用。

    希望对你有帮助。

    【讨论】:

    • Q1:如何将最终布尔值 isRunning 设置为 false? Q2:当它被定义在一个封闭类型中时,你如何设置最终的布尔 isRunning? Q3:不启动线程如何使用? Q4:如何处理线程 t1 中的消息并更新线程 t2 中的变量:例如处理程序接收到“停止运行”消息,该消息在 handleMessage 方法中处理,线程 t2 中的无限循环 - while(!stopped) - 是通过将线程 t2 的停止布尔值设置为 false 来停止; ??我无法让它工作:(
    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 2015-11-27
    • 1970-01-01
    • 2014-11-01
    • 2012-04-30
    • 2011-12-13
    • 1970-01-01
    • 2018-06-11
    相关资源
    最近更新 更多