下载大量数据时无响应的应用程序 [英] Non responsive app when downloading lots of data
本文介绍了下载大量数据时无响应的应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个应用程序,必须在应用程序启动时从服务器下载几MB(1MB-10MB)的数据.
I have an app that has to download a few MB (1MB - 10MB) of data from a server on app startup.
问题在于该应用程序:
-
在开始下载之前没有显示主
TextView
(屏幕保持黑色)
或多或少没有反应
这是代码:
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DoIt();
}
private void DoIt() {
HttpClient httpClient = new DefaultHttpClient();
TextView tv = (TextView)findViewById(R.id.textView);
tv.setText("Starting app...");
try {
for (int i=1; i<100; i++) {
HttpPost request2 = new HttpPost("http://192.168.1.12:3000/bytes/data" + i);
HttpResponse response2 = httpClient.execute(request2);
// Do something with data. In some cases, it has to download 1MB data
}
}
// catch + finally ...
}
}
如何防止应用无响应?
推荐答案
您的应用变得不负责任,因为您正在主线程中下载文件,因此应使用这样的后台线程
Your app become irresponsible because you are downloading files in main thread you should use background thread like this
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView)findViewById(R.id.textView);
tv.setText("Starting app...");
new Thread(new Runnable() {
@Override
public void run() {
DoIt();
}
}).start();
}
private void DoIt() {
HttpClient httpClient = new DefaultHttpClient();
try {
for (int i=1; i<100; i++) {
HttpPost request2 = new HttpPost("http://192.168.1.12:3000/bytes/data" + i);
HttpResponse response2 = httpClient.execute(request2);
// Do something with data. In some cases, it has to download 1MB data
}
}
// catch + finally ...
}
我认为这应该有效
这篇关于下载大量数据时无响应的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文