Android postDelayed Handler在For循环中?

时间:2016-08-18 17:50:29

标签: java android multithreading handler

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

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) );

        }

4 个答案:

答案 0 :(得分:12)

以下代码应该这样做:

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);

答案 1 :(得分:0)

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

@api_view(['GET'])
def search_films(request,title):
    context = {}
    species_data = []
    url = "https://swapi.co/api/?search=" + str(title)
    if request.method == "GET":
        r = requests.get(url)
        if r.status_code == 200:
            data = r.json()
            species = data['results'][0]['species']
            if species:
                for species_url in species:
                    get_request = requests.get(species_url)
                    response_data = get_request.json()
                    species_data.append(response_data)
                context['species'] = response_data
                print(context)
            return Response(species_data, status=status.HTTP_200_OK)
        else:
            return Response({"error": "Request failed"}, status=r.status_code)
    else:
        return Response({"error": "Method not allowed"}, status=status.HTTP_400_BAD_REQUEST)

基本上,我创建了一个if-else语句,其中else语句再次与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); } 运行相同的方法以进行有限的试验。

答案 2 :(得分:0)

这可以是另一种解决方案

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();

答案 3 :(得分:0)

这是我做的简单逻辑,没有在for loop内移动runnable

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

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