带循环的 postDelayed 处理程序

postDelayed handler with loop

我做了一些研究并尝试了一些代码,包括下面来自 的代码。

final Handler handler = new Handler(); 


    int count = 0;
    final Runnable runnable = new Runnable() {
        public void run() { 

            // need to do tasks on the UI thread 
            Log.d(TAG, "runn test");


            if (count++ < 5)
                handler.postDelayed(this, 5000);

        } 
    }; 

    // trigger first time 
    handler.post(runnable);

但是计数变量会显示错误,因为它是在内部 class 中访问的。我该如何解决这个问题?

变量 'count' 从内部 class 中访问,需要是最终的或有效的最终的

您需要将 count 转换为最终的单元素数组

final Handler handler = new Handler();

final int[] count = {0};        //<--changed here
final Runnable runnable = new Runnable() {
    public void run() {

        // need to do tasks on the UI thread
        Log.d(TAG, "runn test");


        if (count[0]++ < 5)     //<--changed here
            handler.postDelayed(this, 5000);

    }
};

// trigger first time
handler.post(runnable);