可能重复:
Download a file with Android, and showing the progress in a ProgressDialogAndroid:使用“进度”GUI在后台线程中从网络加载数据?
我想从一个Web服务器的信息加载到我的应用程序。目前,我正在主线程中执行此操作,我读过的操作非常糟糕(如果请求花费的时间超过5秒,则应用程序崩溃)。
因此,我想了解如何将此操作移至后台线程。这是否涉及某种服务?
下面是代码的样本,我做服务器的请求:
// send data
URL url = new URL("http://www.myscript.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line + "\n");
}
wr.close();
rd.close();
String result = sb.toString();
Intent i = new Intent(searchEventActivity.this, searchResultsActivity.class);
i.putExtra("result", result);
startActivity(i);
我等待着要建立一个JSON字符串的响应,那么我传递一个字符串到一个新的活动。这是一个及时的操作,而不是悬挂用户界面,我想向用户展示某种好的“进度”栏(即使其中一个圆形灯具旋转灯也亮),而此URL业务正在发生后台线程。
感谢您的任何帮助或指导教程的链接。
[与答案相同的问题(http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-progress-in-a-progressdialog)...已经有数百个(好的,很多)类似/相同的问题。 –