Android 应用程序中的睡眠/等待
我有一个活动连续调用一个线程 10 次。但是,如果网络速度慢或加载的信息过多,则会发生强制关闭。在每个线程中添加sleep是否有助于解决这个问题?或者还有其他方法可以解决吗?
public void run() {
if(thread_op.equalsIgnoreCase("xml")){
readXML();
}
else if(thread_op.equalsIgnoreCase("getImg")){
getWallpaperThumb();
}
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
int count = 0;
if (!myExampleHandler.filenames.isEmpty()){
count = myExampleHandler.filenames.size();
}
count = 5;
if(thread_op.equalsIgnoreCase("xml")){
pd.dismiss();
thread_op = "getImg";
btn_more.setBackgroundResource(R.drawable.btn_more);
}
else if(thread_op.equalsIgnoreCase("getImg")){
setWallpaperThumb();
index++;
if (index < count){
Thread thread = new Thread(GalleryWallpapers.this);
thread.start();
}
}
}
};
I had an activity which calls a thread for 10times one after another. However, if the network is slow or too much information loaded, force close will occur. Will adding sleep in each thread help to solve this problem? or is there any other ways to solve it?
public void run() {
if(thread_op.equalsIgnoreCase("xml")){
readXML();
}
else if(thread_op.equalsIgnoreCase("getImg")){
getWallpaperThumb();
}
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
int count = 0;
if (!myExampleHandler.filenames.isEmpty()){
count = myExampleHandler.filenames.size();
}
count = 5;
if(thread_op.equalsIgnoreCase("xml")){
pd.dismiss();
thread_op = "getImg";
btn_more.setBackgroundResource(R.drawable.btn_more);
}
else if(thread_op.equalsIgnoreCase("getImg")){
setWallpaperThumb();
index++;
if (index < count){
Thread thread = new Thread(GalleryWallpapers.this);
thread.start();
}
}
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一步应该是检查堆栈跟踪,这将给出有问题的行和原因。您可以使用 Logcat 来实现这一点。
First step should be to check the stack trace which will give the offending line and cause. You can use Logcat for that.
您是否收到应用程序无响应对话框 (ANR) 或者您的应用程序是否强制关闭?
当 UI Looper 线程从调用返回的时间过长时,就会出现 ANR。只要handleMessage 函数及时返回,拥有 10 或 100 个线程就不会造成任何问题。
如果您确实想限制一次运行的线程数,请查找 ExecutorService
您可以将所有 10 个作业提交到执行器服务,它们将一个接一个地运行,最多同时运行 5 个。
Are you getting the Application not responding dialog (ANR) or does your app force close?
ANR appears when the UI looper thread takes too long to return from a call. Having 10 or 100 threads should not cause any problem as long as the handleMessage function returns in a timely fashion.
If you really want to limit the number of threads that should be running in one go look up ExecutorService
You can submit all 10 jobs to the executor service and they'll run one after another with a maximum of 5 running simultaneously.