您可以使用 AsyncTask 在 PreExecute() 方法中显示进度对话框,并在 PostExecute() 方法中隐藏/关闭它。
ProgressDialog prog = new ProgressDialog(this); // Create Progress Dialog
private class DownloadFile extends AsyncTask<Void, Integer, Void>{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Display progressDialog before download starts
prog.show();
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prog.hide(); //Hide Progress Dialog else use dismiss() to dismiss the dialog
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
InternetManager in = new InternetManager("http://url-to-download");
in.fileRequest();
return null;
}
}
in.fileRequest()
将为您提供您打算下载的文件,然后使用FileOutputStream.write(bytes[])将其写入文件。
最后AsyncTask
打通电话,
DownloadFile dd = new DownloadFile();
dd.execute();
InternetManager
执行互联网相关任务的类。
public class InternetManager {
HttpClient httpclient;
HttpGet httpget;
HttpResponse httpresponse;
HttpEntity httpentity;
String url;
String response = null;
byte[] data = null;
public InternetManager(String url) {
this.url = url;
}
public byte[] fileRequest() {
httpclient = new DefaultHttpClient();
httpget = new HttpGet(url);
try {
httpresponse = httpclient.execute(httpget);
httpentity = httpresponse.getEntity();
data = EntityUtils.toByteArray(httpentity);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("", "File downloaded URL: " + url);
return data;
}
}