主要 Ui 冻结

Main Ui Freezes

我正在尝试让摄像头以不同的速度闪烁。

为此,我使用搜索栏来更改闪烁速度。

当我第一次更改 seekbar 的值时它开始闪烁

private fun startFlashLightBlink(context: Context,blinkSpeed: Int) {

        isBlinkFlashLight=true
     flashLightBlinkThread = Thread{

                Looper.prepare()
                while (isBlinkFlashLight){
                    val blinkInterval:Long=blinkSpeed*100L
                    //getMainLooper() handler is associated "with the Looper for the current thread" ... which is currently the main(UI) thread
                    val handler = Handler()

                    var runnable:Runnable = Runnable{
                        toggleFlashLight()
                    }
                    handler.postDelayed(runnable,blinkInterval)
                }

                Looper.loop()

            }
            flashLightBlinkThread?.start()

    }

但它冻结了主要 UI 所以现在我无法使用搜索栏更改值并收到 ANR 消息。 我应该怎么办?我不能使用 asynkTask。 服务也不是一个好的选择。我认为。

尽量不要使用单独的Thread和Looper。处理程序足以满足您的需求。像这样循环:

private static final long POST_DELAY = 100;
private final Handler handler = new Handler();
private final Runnable cycleRunnable = new Runnable() {
    public void run() {
        if (isCycling) {
            // make your cycle body here
            handler.postDelayed(cycleRunnable, POST_DELAY);
        }
    }
};

private boolean isCycling = false;

public void startCycle() {
    if (!isCycling) {
        isCycling = true;
        handler.postDelayed(cycleRunnable, POST_DELAY);
    }
}

public void stopCycle() {
    if (isCycling) {
        isCycling = false;
        handler.removeCallbacks(cycleRunnable);
    }
}