我需要从互联网上下载文件以更新路径中的一些资源文件
"/data/data/" + context.getPackageName() + "/databases/"
方法
public static void updateDB(){
removeOldCopies();
//how to download a file in a specific directory without open browser????
}
应该在没有用户干预的情况下执行此操作,仅显示进度对话框
我怎么能这样做?
答案 0 :(得分:1)
您可以使用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;
}
}