Android中AsyncTask进行后台下载文件并在下拉菜单显示下载进度

在开发过程中,总会需要从网络上下载文件,有时候还需要将下载进度显示在下拉菜单中。

现在写了一个Demo,封装了AsyncTask下载文件和进度显示的代码,以后在做项目的时候能够直接进行使用。

效果图:



主界面只有一个按钮,比较简单:

/ layout / activity_main.xml :

[html]  view plain  copy
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent" >  
  5.   
  6.     <Button  
  7.         android:id="@+id/button"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_alignParentLeft="true"  
  11.         android:layout_alignParentTop="true"  
  12.         android:text="点击下载" />  
  13.   
  14. </RelativeLayout>  


MainActivity:其中的思路解释均在代码中:

[java]  view plain  copy
  1. import android.app.Activity;  
  2. import android.os.Bundle;  
  3. import android.os.Handler;  
  4. import android.view.View;  
  5. import android.view.View.OnClickListener;  
  6. import android.widget.Button;  
  7.   
  8. public class MainActivity extends Activity {  
  9.   
  10.     private Handler mHandler = new Handler();  
  11.       
  12.     private AsyncTaskUtil mDownloadAsyncTask;  
  13.       
  14.     private Button mButton;  
  15.       
  16.     @Override  
  17.     protected void onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.activity_main);  
  20.           
  21.         mButton = (Button) findViewById(R.id.button);  
  22.         mButton.setOnClickListener(new OnClickListener() {  
  23.               
  24.             @Override  
  25.             public void onClick(View v) {  
  26.                 //AsyncTask异步下载任务  
  27.                 mDownloadAsyncTask = new AsyncTaskUtil(MainActivity.this, mHandler);  
  28.                 mDownloadAsyncTask.execute("http://apps.wandoujia.com/apps/com.sec.print.mobileprint/download""Mobile Print.apk");//必须传入两个参数——参数1:url;参数2:文件名(可以为null)  
  29.             }  
  30.         });  
  31.     }  
  32. }  

以上只要通过新建一个AsyncTaskUtil的对象,传入url和文件名便能后台下载文件病显示下载进度,是不是很方面?具体的代码解析如下:


AsyncTaskRunnable:用于handler.post(Runnable)方法来更新UI,下载进度主要通过NotificationManager、Notification和RemoteView来显示、更新下载的进度,不懂的同学需要google一下~

[java]  view plain  copy
  1. import java.text.DecimalFormat;  
  2.   
  3. import android.app.Notification;  
  4. import android.app.NotificationManager;  
  5. import android.content.Context;  
  6. import android.util.Log;  
  7. import android.widget.RemoteViews;  
  8. import android.widget.Toast;  
  9.   
  10. public class AsyncTaskRunnable implements Runnable{  
  11.   
  12.     public static final String TAG = "AsyncTaskRunnable";  
  13.     //主线程的activity  
  14.     private Context mContext;  
  15.     //notification的状态:更新 or 失败 or 成功  
  16.     private int mStatus;  
  17.     //notification的下载比例  
  18.     private float mSize;  
  19.     //管理下拉菜单的通知信息  
  20.     private NotificationManager mNotificationManager;  
  21.     //下拉菜单的通知信息  
  22.     private Notification mNotification;  
  23.     //下拉菜单的通知信息的view  
  24.     private RemoteViews mRemoteViews;  
  25.     //下拉菜单的通知信息的种类id  
  26.     private static final int NOTIFICATION_ID = 1;  
  27.       
  28.     //设置比例和数据  
  29.     public void setDatas(int status , float size) {  
  30.         this.mStatus = status;  
  31.         this.mSize = size;  
  32.     }  
  33.     //初始化  
  34.     public AsyncTaskRunnable(Context context) {  
  35.         this.mContext = context;  
  36.         mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);  
  37.         //初始化下拉菜单的通知信息  
  38.         mNotification = new Notification();  
  39.         mNotification.icon = R.drawable.ic_launcher;//设置下载进度的icon  
  40.         mNotification.tickerText = mContext.getResources().getString(R.string.app_name); //设置下载进度的title  
  41.           
  42.         mRemoteViews = new RemoteViews(mContext.getPackageName(), R.layout.down_notification);//对于RemoteView的使用,不懂的需要查找google  
  43.         mRemoteViews.setImageViewResource(R.id.id_download_icon, R.drawable.ic_launcher);  
  44.     }  
  45.       
  46.     @Override  
  47.     public void run() {//通过判断不同的状态:更新中/下载失败/下载成功 更新下拉菜单的通知信息  
  48.         switch (mStatus) {  
  49.         case AsyncTaskUtil.NOTIFICATION_PROGRESS_FAILED://下载失败  
  50.             mNotificationManager.cancel(NOTIFICATION_ID);  
  51.             break;  
  52.   
  53.         case AsyncTaskUtil.NOTIFICATION_PROGRESS_SUCCEED://下载成功  
  54.             mRemoteViews.setTextViewText(R.id.id_download_textview, "Download completed ! ");  
  55.             mRemoteViews.setProgressBar(R.id.id_download_progressbar, 100100false);  
  56.             mNotification.contentView = mRemoteViews;  
  57.             mNotificationManager.notify(NOTIFICATION_ID, mNotification);  
  58.             mNotificationManager.cancel(NOTIFICATION_ID);  
  59.             Toast.makeText(mContext, "Download completed ! ", Toast.LENGTH_SHORT).show();  
  60.             break;  
  61.               
  62.         case AsyncTaskUtil.NOTIFICATION_PROGRESS_UPDATE://更新中  
  63.             DecimalFormat format = new DecimalFormat("0.00");//数字格式转换  
  64.             String progress = format.format(mSize);  
  65.             Log.d(TAG, "the progress of the download " + progress);  
  66.             mRemoteViews.setTextViewText(R.id.id_download_textview, "Download completed : " + progress + " %");  
  67.             mRemoteViews.setProgressBar(R.id.id_download_progressbar, 100, (int)mSize, false);  
  68.             mNotification.contentView = mRemoteViews;  
  69.             mNotificationManager.notify(NOTIFICATION_ID, mNotification);  
  70.             break;  
  71.         }  
  72.     }  
  73.   
  74. }  
其中需要建立一个下载进度的布局文件,如下:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <LinearLayout  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:gravity="center"  
  11.         android:orientation="horizontal"  
  12.         android:background="@android:color/white" >  
  13.   
  14.         <ImageView  
  15.             android:id="@+id/id_download_icon"  
  16.             android:layout_width="wrap_content"  
  17.             android:layout_height="wrap_content"  
  18.             android:layout_marginRight="10dp"  
  19.             android:layout_marginLeft="10dp"  
  20.             android:src="@drawable/ic_launcher" />  
  21.   
  22.         <LinearLayout  
  23.             android:layout_width="wrap_content"  
  24.             android:layout_height="wrap_content"  
  25.             android:layout_marginRight="10dip"  
  26.             android:layout_weight="1"  
  27.             android:orientation="vertical" >  
  28.   
  29.             <TextView  
  30.                 android:layout_width="wrap_content"  
  31.                 android:layout_height="wrap_content"  
  32.                 android:text="@string/app_name"  
  33.                 android:textColor="@android:color/black"  
  34.                 android:textSize="18dip"  
  35.                 android:textStyle="bold" />  
  36.   
  37.             <ProgressBar  
  38.                 android:id="@+id/id_download_progressbar"  
  39.                 style="?android:attr/progressBarStyleHorizontal"  
  40.                 android:layout_width="fill_parent"  
  41.                 android:layout_height="wrap_content"  
  42.                 android:layout_marginTop="5dp"  
  43.                 android:max="100"  
  44.                 android:progress="0"  
  45.                 android:secondaryProgress="0" />  
  46.   
  47.             <TextView  
  48.                 android:id="@+id/id_download_textview"  
  49.                 android:layout_width="wrap_content"  
  50.                 android:layout_height="wrap_content"  
  51.                 android:text="Download completed : "   
  52.                 android:textColor="@android:color/black"  
  53.                 android:textSize="12dip"  
  54.                 android:textStyle="bold" />  
  55.         </LinearLayout>  
  56.     </LinearLayout>  
  57.   
  58. </LinearLayout>  


异步下载类:AsyncTaskUtil用于下载文件:
[java]  view plain  copy
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.InputStream;  
  4. import java.net.URL;  
  5. import java.net.URLConnection;  
  6. import java.util.Timer;  
  7. import java.util.TimerTask;  
  8.   
  9. import android.content.Context;  
  10. import android.os.AsyncTask;  
  11. import android.os.Environment;  
  12. import android.os.Handler;  
  13. import android.util.Log;  
  14. import android.widget.Toast;  
  15.   
  16. public class AsyncTaskUtil extends AsyncTask<String, Double, Boolean> {  
  17.   
  18.     public static final String TAG = "AsyncTaskUtil";  
  19.       
  20.     public static final int NOTIFICATION_PROGRESS_UPDATE = 0x10;//用于更新下载进度的标志  
  21.     public static final int NOTIFICATION_PROGRESS_SUCCEED = 0x11;//表示下载成功  
  22.     public static final int NOTIFICATION_PROGRESS_FAILED = 0x12;//表示下载失败  
  23.   
  24.     //URL  
  25.     private String mUrl;  
  26.     //activity  
  27.     private Context mContext;  
  28.     //任务定时器  
  29.     private Timer mTimer;  
  30.     //定时任务  
  31.     private TimerTask mTask;  
  32.     //主线程传递过来的handler  
  33.     private Handler  mHandler;  
  34.     //所要下载的文件大小  
  35.     private long mFileSize;  
  36.     //已下载的文件大小  
  37.     private long mTotalReadSize;  
  38.     //AsyncTaskRunnable实现了Runnable接口,用于更新下载进度的显示  
  39.     private AsyncTaskRunnable mRunnable;  
  40.   
  41.     //构造方法  
  42.     public AsyncTaskUtil(Context context, Handler handler) {  
  43.         mContext = context;  
  44.         mHandler = handler;  
  45.   
  46.         mTimer = new Timer();  
  47.         mTask = new TimerTask() {//在run方法中执行定时的任务  
  48.             @Override  
  49.             public void run() {  
  50.                 //size表示下载进度的百分比  
  51.                 float size = (float) mTotalReadSize * 100 / (float) mFileSize;  
  52.                 //通过AsyncTaskRunnable的setDatas方法下载的进度和状态(更新中、失败、成功)  
  53.                 mRunnable.setDatas(NOTIFICATION_PROGRESS_UPDATE, size);  
  54.                 //更新进度  
  55.                 mHandler.post(mRunnable);  
  56.             }  
  57.         };  
  58.         mRunnable = new AsyncTaskRunnable(mContext);  
  59.     }  
  60.   
  61.       
  62.     // 执行耗时操作,params[0]为url,params[1]为文件名(空则写入null)  
  63.     @Override  
  64.     protected Boolean doInBackground(String... params) {  
  65.           
  66.         //任务定时器一定要启动  
  67.         mTimer.schedule(mTask, 0500);  
  68.           
  69.         try {  
  70.             mUrl = params[0];  
  71.             //建立链接  
  72.             URLConnection connection = new URL(mUrl).openConnection();  
  73.             //获取文件大小  
  74.             mFileSize = connection.getContentLength();  
  75.             Log.d(TAG, "the count of the url content length is : " + mFileSize);  
  76.   
  77.             //获得输入流  
  78.             InputStream is = connection.getInputStream();  
  79.             //先建立文件夹  
  80.             File fold = new File(getFolderPath());  
  81.             if (!fold.exists()) {  
  82.                 fold.mkdirs();  
  83.             }  
  84.               
  85.             String fileName = "";  
  86.             //判断文件名:用户自定义或由url获得  
  87.             if(params[1] != null){  
  88.                 fileName = params[1];  
  89.             } else{  
  90.                 fileName = getFileName(params[0]);  
  91.             }  
  92.             //文件输出流  
  93.             FileOutputStream fos = new FileOutputStream(new File(getFolderPath()  
  94.                             + fileName));  
  95.   
  96.             byte[] buff = new byte[1024];  
  97.             int len;  
  98.             while ((len = is.read(buff)) != -1) {  
  99.                 mTotalReadSize += len;  
  100.                 fos.write(buff, 0, len);  
  101.             }  
  102.             fos.flush();  
  103.             fos.close();  
  104.   
  105.         } catch (Exception e) {  
  106.             //异常,下载失败  
  107.             mRunnable.setDatas(NOTIFICATION_PROGRESS_FAILED, 0);  
  108.             //发送显示下载失败  
  109.             mHandler.post(mRunnable);  
  110.             if(mTimer != null && mTask != null){  
  111.                 mTimer.cancel();  
  112.                 mTask.cancel();  
  113.             }  
  114.             e.printStackTrace();  
  115.             return false;  
  116.         }  
  117.         //下载成功  
  118.         mRunnable.setDatas(NOTIFICATION_PROGRESS_SUCCEED, 0);  
  119.         mHandler.post(mRunnable);  
  120.         if(mTimer != null && mTask != null){  
  121.             mTimer.cancel();  
  122.             mTask.cancel();  
  123.         }  
  124.         return true;  
  125.     }  
  126.   
  127.     //由url获得文件名  
  128.     private String getFileName(String string) {  
  129.         return string.substring(string.lastIndexOf("/") + 1);  
  130.     }  
  131.   
  132.     //下载文件夹路径  
  133.     private String getFolderPath() {  
  134.         return Environment.getExternalStorageDirectory().toString() + "/AsyncTaskDownload/";  
  135.     }  
  136.   
  137.   
  138.     // doInBackground方法之前调用,初始化UI  
  139.     @Override  
  140.     protected void onPreExecute() {  
  141.         super.onPreExecute();  
  142.     }  
  143.   
  144.     // 在doInBackground方法之后调用  
  145.     @Override  
  146.     protected void onPostExecute(Boolean result) {  
  147.         super.onPostExecute(result);  
  148.         if (result) {  
  149.             Toast.makeText(mContext, "Download Completed ! ", Toast.LENGTH_SHORT).show();  
  150.         } else {  
  151.             Toast.makeText(mContext, "Download Failed ! ", Toast.LENGTH_SHORT).show();  
  152.         }  
  153.     }  
  154.   
  155.     @Override  
  156.     protected void onProgressUpdate(Double... values) {  
  157.         super.onProgressUpdate(values);  
  158.     }  
  159.   
  160. }  

好了,以上就是今天分享的内容~~是时候(~﹃~)~zZ

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值