【问题标题】:Is there a better way to update UI periodically有没有更好的方法来定期更新 UI
【发布时间】:2026-02-25 01:30:01
【问题描述】:

在屏幕上,我显示状态指示灯或要显示的打印机是否已连接。我很想知道以最佳性能实现它的最佳方法。

我尝试创建Handler 对象并调用postDelayed(Runnable r, long delayMillis),它按预期工作:

初始化HandlerRunnable


private static final int SOME_INTERVAL = 10000;
private Handler mHandler = new Handler();

private Runnable mPrinterUpdaterRunnable = new Runnable() {
        @Override
        public void run() {
            updatePrinterIndicator(); \\ do some stuff
            mHandler.postDelayed(this, SOME_INTERVAL);
        }
    };

private void updatePrinterIndicator() {
        // check printer status and update some view for instance ImageView
    }

之后,我需要在活动启动时启动Handler,并在用户离开活动时删除所有回调,所以我写:

@Override
public void onResume() {
    super.onResume();
    mHandler.postDelayed(mPrinterUpdaterRunnable , 0);
}

@Override
public void onPause() {
    mHandler.removeCallbacksAndMessages(null);
    super.onPause();
}

所以,如果我理解正确,mPrinterUpdaterRunnablerun() 方法中的所有代码都将在主 UI 线程中执行。

有没有更好的方法来做到这一点,或者我已经使用了最好的方法来做到这一点?不执行主 UI 线程中的所有代码,仅执行 someView.setImageResource(someID)

【问题讨论】:

    标签: java android multithreading performance android-handler


    【解决方案1】:

    您可以使用至少 3 个以下选项在后台线程中运行您的代码:

    1. 使用RxJava;
    2. 使用像this这样的自定义类;
    3. 如果使用 Kotlin,则使用协程;

    还有其他方法可以做到这一点。如果您打算大幅扩展您的项目,那么 RxJava 具有更大的长期潜力。此外,这具有更陡峭的学习曲线。

    第二种解决方案非常适合中小型项目,也是最简单的一种,与协程一起使用。

    添加 AppExecutors 类(第二个解决方案)后,您可以像这样使用它:

    new AppExecutor().diskIO().execute(new Runnable() {
            @Override
            public void run() {
                // Do your stuff
            }
        });
    

    如果我能帮上忙,请告诉我!

    【讨论】:

      最近更新 更多