本文介绍了for-loop服务中的处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Activity类中使用了以下代码,它工作正常.K已相应更新.但是当我在服务类中使用它时,for循环中的变量k不在等待处理程序.
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
如果我尝试通过处理程序中的索引访问数组,它将给出错误ArrayOutOfBoundException.有什么解决办法吗,或者我必须使用JobSheduler或其他工具.
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.
推荐答案
为此使用Runnable.如下.
use Runnable for that. As Following.
int k = 0;
Handler mHandler = new Handler();
初次使用
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++;
}
};
这篇关于for-loop服务中的处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!