[英]Handlers in for-loop Services
我在Activity类中使用了以下代码,它运行良好。 但是当我在服务类中使用它时,for循环中的变量k不在等待处理程序。
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或其他工具。
为此使用Runnable。 如下。
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++;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.