Handlers in for-loop Services

2019-08-31 02:36发布

问题:

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++;
    }
};