文件下载之使用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
- 文件下载之使用AsyncTask并在进度对话框中显示下载进度
- AsyncTask下载网络文件,并显示下载进度
- Android中AsyncTask进行后台下载文件并在下拉菜单显示下载进度
- Android中AsyncTask进行后台下载文件并在下拉菜单显示下载进度
- Android中AsyncTask进行后台下载文件并在下拉菜单显示下载进度
- android AsyncTask下载文件并且显示进度
- 使用AsyncTask下载图片并更新进度
- android中如何下载文件并显示下载进度
- android中如何下载文件并显示下载进度
- AsyncTask下载图片、显示进度
- AsyncTask下载网络图片并显示下载进度
- NSURLConnection下载文件并显示进度
- NSURLConnection下载文件并显示进度(HEAD)
- NSURLConnection下载文件并显示进度(HEAD)
- Unity下载文件并显示进度
- Unity3d下载大型文件并显示进度
- 在Activity中获取AsyncTask中更新progress的值,可用在文件的上传和下载同步显示进度
- 运用AsyncTask下载图片并显示下载进度,下载完成后显示
- 使用Response.Write(<script language=javascript>alert的注意事项
- Solve the problem of System.IO.FileLoadException
- Count Primes 小于n的非负整数里边素数的个数
- ckeditor的详细配置(转)
- 用系统自带的定位功能拿到所在的国家,城市,区
- 文件下载之使用AsyncTask并在进度对话框中显示下载进度
- 获得汉字的首字母大写 java
- 使用java创建一个简易的视屏播放器
- js一些 难记的
- 带你彻彻底底弄懂Scroller
- java中list与数组转换
- hadoop2.5.0源码编译
- Xtrabackup 安装使用
- iOS 一般设置