【问题标题】:Android postDelayed Handler Inside a For Loop?For循环内的Android postDelayed处理程序?
【发布时间】:2016-08-18 17:50:28
【问题描述】:

有没有办法在循环中运行处理程序? 我有这段代码,但没有工作,因为它不等待循环,而是以正确的方式执行代码:

final Handler handler = new Handler();


        final Runnable runnable = new Runnable() {
            public void run() {

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

                //
                for (int i = 1; i < 6; i++) {

                    handler.postDelayed(this, 5000);

                }


            }
        };

        // trigger first time
        handler.postDelayed(runnable, 0);

当然,当我将帖子延迟到循环之外时,它不会迭代或执行我需要的时间:

final Handler handler = new Handler();


        final Runnable runnable = new Runnable() {
            public void run() {

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

                //
                for (int i = 1; i < 6; i++) {
                }

                // works great! but it does not do what we need
                handler.postDelayed(this, 5000);


            }
        };

        // trigger first time
        handler.postDelayed(runnable, 0);

找到解决方案:

我需要在 doInBackground 方法中使用 asyntask 和 Thread.sleep(5000):

class ExecuteAsyncTask extends AsyncTask<Object, Void, String> {


            //
            protected String doInBackground(Object... task_idx) {

                //
                String param = (String) task_idx[0];

                //
                Log.d(TAG, "xxx - iter value started task idx: " + param);

                // stop
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //
                Log.d(TAG, "xxx - iter value done " + param);
                return " done for task idx: " + param;
            }


            //
            protected void onPostExecute(String result) {
                Log.d(TAG, "xxx - task executed update ui controls: " + result);
            }

        }




        for(int i = 0; i < 6; i ++){

            //
            new ExecuteAsyncTask().execute( String.valueOf(i) );

        }

【问题讨论】:

  • 如果你调用postDelayed N 次Runnable 将运行N 次,这不是你想要的吗?
  • 是的,但它不会等待并立即触发代码,这是我不想要的
  • 5000 更改为5000 + i * 1000,因此第一个Runnable 将在5 秒后运行,第二个在6 秒后运行,以此类推... 7、8、9、...跨度>
  • 你的答案很好,但也不起作用,它不会等待。
  • 等什么?这是一个“延迟”执行,你还想等什么?

标签: java android multithreading handler


【解决方案1】:

您可以让Runnable 实例调用自身特定次数,而不是使用for 循环。这些调用将发布到 UI 线程队列,因此请记住这一点。另外,由于延迟比较大,请确保下次触发该事件时仍然需要该事件。

下面的代码应该做到这一点:

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, "Run test count: " + count);
        if (count++ < 5) {
            handler.postDelayed(this, 5000);
        }
    } 
}; 

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

【讨论】:

  • 在执行 if(count++
  • @DAVIDBALAS1 它将当前值与6进行比较,然后为下一次迭代增加值
  • 因此,如果它会比较当前值,那么您的代码将运行 0,1,2,3,4,5 意味着 6 次,而他的代码将只运行 5 次,不是吗?只是想学习..
  • @DAVIDBALAS1 true :) ...没看到...我以为他从 0 开始...谢谢
【解决方案2】:

如果有人遇到类似问题,我对此问题的解决方案:

int count = 0;
    public static void method(param1, param2, param3) {
                        Runnable r = () -> { //put method inside runnable
                        View view = listView.getChildAt(position); //action to be complete
                        if (view != null) { //if action is successfully complete
                            view.setSelected(true); //do something with this 
                        } else { //do a looper
                            if (count < 10) { //limited looper to certain number
                                count++;
                                method(param1, param2, param3); //run the method again
                        }
                };

                Handler h = new Handler(); //create a new Handler and post above thread with it
                h.postDelayed(r, 300);
             }

基本上,我创建了一个 if-else 语句,其中 else 语句再次运行与 postDelayed() 相同的方法以进行有限次数的试验。

【讨论】:

  • 你让我开心..谢谢!
【解决方案3】:

这可以是另一种解决方案

final Handler handler = new Handler();
Runnable runnable = new Runnable() {
    int i;
    public void run() {
        for (i = 1; i < 6; i++) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // need to do tasks on the UI thread
                    Log.d(TAG, "runn test");
                }
            }, 0);
            //Add some downtime
            SystemClock.sleep(5000);
        }
    }
};
new Thread(runnable).start();

【讨论】:

    【解决方案4】:

    这是我制作的一个简单逻辑,没有将for loop 移动到runnable 中。

     for(int i = 1; i<=5; i++){
        ...
        new Handler().postDelayed(() -> myFunctionToExecute() , i * 1000);
     }
    

    因此,每当循环迭代时,它只会延长处理程序延迟。这样,您就可以实现。我正在寻找类似的东西,找不到任何东西,因为在我的情况下,我已经实现了 for 循环,将它移动到 run() 中会造成混乱

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-12
      • 2016-05-01
      • 2016-06-27
      • 1970-01-01
      • 2011-05-20
      • 2021-12-12
      • 1970-01-01
      • 2018-05-07
      相关资源
      最近更新 更多