【问题标题】:Updating UI from Runnable with parameters使用参数从 Runnable 更新 UI
【发布时间】:2020-12-11 17:07:49
【问题描述】:

我在 Stackoverflow 上找到了多个执行此操作的选项,但仍然没有找到使用参数执行此操作的好方法。就我而言,我有一个线程需要不断更新 UI 主线程的日志信息(我没有使用 Asynctask;我正在从 Google Maps 实现 TileProvider 接口)

这就是我在我的线程中运行的东西,它可以工作:

Handler mainHandler = new Handler(Looper.getMainLooper());
...

public void debugMsg(final String msg)
{
   Runnable myRunnable = (new Runnable()
   {
     @Override
     public void run()
     {
        Log.Add(msg); // static function that update the UI in the main thread
     }
   });
 
  mainHandler.post(myRunnable);
}

问题是如果我理解正确的话,每次我调用debugMsg,都会实例化一个新的Runnable对象。我不认为这是一个很好的做法,特别是因为它会被大量完成,所以我想知道是否有办法在我的线程中重用该可运行文件。或者也许有更好的方法......

【问题讨论】:

    标签: java android multithreading user-interface


    【解决方案1】:

    如果您想重用Runnable,您可以轻松地将其存储为成员变量。

    private Runnable myRunnable = new Runnable() {
        @Override
        public void run() { ... };
    }
    

    你可能会想,如果有参数,你可以使用消费者。

    private Consumer<String> myConsumer = (str) - > { Log.d("tag", str); };
    

    然后在 debugMsg 中

    mainHandler.post(() -> { myConsumer.accept(msg); });
    

    但是,您的 lambda 仍将是每次运行 debugMsg 时实例化的功能接口对象。但不会重新创建主逻辑,myConsumer会被重用。

    更新:

    你可以自己实现 Runnable 接口,比如

    public abstract class ParameterisedRunnable implements Runnable {
        
        public String param = "";
    
        public void setParam(String str) {
            param = str;
        }
    }
    

    然后像常规的 Runnable 一样创建 ParameterisedRunnable 的实例(覆盖 run 方法)。

    private ParameterisedRunnable myRunnable = new ParameterisedRunnable() {
        @Override
        public void run() {
            Log.d("tag", param);
        }
    }
    

    你可以这样使用它。

    myRunnable.setParam(msg);
    mainHandler.post(myRunnable);
    

    【讨论】:

    • 谢谢,它看起来是一个不错的解决方案,但是我的应用与 API 16 设备兼容,并且“接受”需要 24。有替代方案吗?
    • 另外,如果有使用 Runnable 的替代方法,我也可以试试。我知道我可以使用消息,但我希望使用更简单的东西。
    • 使用字段实现 Runnable,并在其中存储参数。
    • @LEM 我更新了我的答案,它显示了 Alexei 提出的方法
    • @LEM 是的,你是对的,我打错了,我很高兴它对你有所帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2013-04-27
    相关资源
    最近更新 更多