0

我需要从互联网上下载一个文件来更新路径中的一些资源文件

"/data/data/" + context.getPackageName() + "/databases/"

方法

public static void updateDB(){
removeOldCopies();
//how to download a file in a specific directory without open browser????
}

应该在没有用户干预的情况下执行此操作,只显示一个进度对话框

我怎么能这样做?

4

1 回答 1

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;
         }
}
于 2013-01-10T05:17:01.867 回答