文件下载之使用AsyncTask并在进度对话框中显示下载进度

来源:互联网 发布:淘宝评论看不见 编辑:程序博客网 时间:2024/04/28 01:00

这种方式的优势是你可以在后台执行下载任务的同时,也可以更新UI(这里我们用progress bar来更新下载进度)

1,新建Activity,并在onCreate方法中定义对话框并绑定相应的事件

// declare the dialog as a member field of your activityProgressDialog mProgressDialog;// instantiate it within the onCreate methodmProgressDialog = new ProgressDialog(YourActivity.this);mProgressDialog.setMessage("A message");mProgressDialog.setIndeterminate(true);mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);mProgressDialog.setCancelable(true);// execute this when the downloader must be firedfinal DownloadTask downloadTask = new DownloadTask(YourActivity.this);downloadTask.execute("the url to the file you want to download");mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {    @Override    public void onCancel(DialogInterface dialog) {        downloadTask.cancel(true);    }});

2.DownloadTask继承自AsyncTask,按照如下框架定义,你需要将代码中的某些参数替换成你自己的。

 private class DownloadTask extends AsyncTask<String, Integer, String> {        private Context context;        private PowerManager.WakeLock mWakeLock;        public DownloadTask(Context context) {            this.context = context;        }        /**         * Override this method to perform a computation on a background thread. The         * specified parameters are the parameters passed to {@link #execute}         * by the caller of this task.         * <p/>         * This method can call {@link #publishProgress} to publish updates         * on the UI thread.         *         * @param sUrl The parameters of the task.         * @return A result, defined by the subclass of this task.         * @see #onPreExecute()         * @see #onPostExecute         * @see #publishProgress         */        @Override        protected String doInBackground(String... sUrl) {            InputStream input = null;            OutputStream output = null;            HttpURLConnection connection = null;            try {                URL url = new URL(sUrl[0]);                connection = (HttpURLConnection) url.openConnection();                connection.connect();                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {                    return "server returned HTTP:" + connection.getResponseCode() +                            "" + connection.getResponseMessage();                }                int fileLength = connection.getContentLength();                input = connection.getInputStream();                output = new FileOutputStream("/sdcard/test.apk");                byte data[] = new byte[4096];                long total = 0;                int count;                while ((count = input.read(data)) != -1) {                    if (isCancelled()) {                        input.close();                        return null;                    }                    total += count;                    if (fileLength > 0) {                        //publishing hte progress...                        publishProgress((int)(total*100/fileLength));                        output.write(data, 0, count);                    }                }            } catch (Exception e) {                return e.toString();            } finally {                try {                    if (output != null) {                        output.close();                    }                    if (input != null) {                        input.close();                    }                } catch (IOException e) {                    e.printStackTrace();                }                if (connection != null) {                    connection.disconnect();                }            }            return null;        }        @Override        protected void onPreExecute() {            super.onPreExecute();            PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,getClass().getName());            mWakeLock.acquire();            mProgressDialog.show();        }        @Override        protected void onProgressUpdate(Integer... progress) {            super.onProgressUpdate(progress);            mProgressDialog.setIndeterminate(false);            mProgressDialog.setMax(100);            mProgressDialog.setProgress(progress[0]);        }        @Override        protected void onPostExecute(String result) {            super.onPostExecute(result);            mWakeLock.release();            mProgressDialog.dismiss();            if(result != null){                Toast.makeText(getApplicationContext(),"Download error:"+result,Toast.LENGTH_SHORT).show();            }else{                Toast.makeText(getApplicationContext(),"File download",Toast.LENGTH_SHORT).show();            }        }    }

上面的代码包含了doInBackground,这是执行后台任务的代码块,不能在这里做任何的UI操作,但是onProgressUpdate和onPreExecute是运行在UI线程中的,所以我们应该在这两个方法中更新progress bar。

3.注意添加如下权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission><uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


另外,别人总结的比较好的文章有http://blog.csdn.net/huadonggmail/article/details/7872214

0 0
原创粉丝点击