Handlers in for-loop Services

北慕城南 提交于 2019-12-11 18:12:28

问题


I used the following code in Activity class, it was working fine.K was updated accordingly. But when I used it in service class, the variable k in for-loop is not waiting for handler.

    for( k=0;k<personsToSend.length;k++) {
                Log.e(TAG,"outside k = "+k);
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        Log.e(TAG,"Inside k = "+k);
                    }
                }, 1000);
    }

Logcat:

outside  k = 0
outside k = 1
outside  k = 2
outside k = 3
outside k = 4
Inside k = 5
Inside k = 5
Inside k = 5
Inside k = 5
Inside k = 5

If I try to access array by index inside handler, it gives error ArrayOutOfBoundException. Is there any solution for this or I have to use JobSheduler or something else.


回答1:


use Runnable for that. As Following.

int k = 0;
Handler mHandler = new Handler();

First time use

mHandler.post(runnable);

Runnable runnable=new Runnable() {
    @Override
    public void run() {
        Log.e(TAG,"outside k = "+k);
        if (k == personsToSend.length) {

        }else {
            mHandler.postDelayed(runnable,1000);
        }
        k++;
    }
};


来源:https://stackoverflow.com/questions/50965818/handlers-in-for-loop-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!