zoukankan      html  css  js  c++  java
  • *Android 多线程下载 仿下载助手

    今天带来一个多线程下载的 样例。先看一下效果。点击 下载 開始下载,同一时候显示下载进度。完成下载,变成程 安装,点击安装 提示 安装应用。

    界面效果

    这里写图片描写叙述

    线程池 ThreadPoolExecutor

        在以下介绍实现下载原理的时候。我想尝试倒着来说。这样是否好理解一点? 
        我们都知道。下载助手,比方360, 百度的 手机助手,下载APP 的时候 ,都能够同一时候下载多个。所以,下载肯定是多线程的。所以我们就须要一个线程工具类 来管理我们的线程,这个工具类的核心,就是 线程池。

     
    线程池ThreadPoolExecutor ,先简单学习下这个线程池的使用

    1. /** 
    2.        * Parameters: 
    3.           corePoolSize  
    4.              the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set 
    5.           maximumPoolSize  
    6.               the maximum number of threads to allow in the pool 
    7.           keepAliveTime 
    8.               when the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating. 
    9.           unit  
    10.               the time unit for the keepAliveTime argument 
    11.           workQueue  
    12.               the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted                   by the execute method. 
    13.           handler  
    14.              the handler to use when execution is blocked because the thread bounds and queue capacities are reached 
    15.         Throws: 
    16.           IllegalArgumentException - if one of the following holds: 
    17.           corePoolSize < 0 
    18.           keepAliveTime < 0 
    19.           maximumPoolSize <= 0 
    20.           maximumPoolSize < corePoolSize 
    21.           NullPointerException - if workQueue or handler is null 
    22.        */  
    23.       ThreadPoolExecutor threadpool=new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler)  

        上面是 ThreadPoolExecutor的參数介绍。 

        第一个參数 corePoolSize : 空暇时 存在的线程数目、 
        第二个參数 maximumPoolSize :同意同一时候存在的最大线程数、 
        第三个參数 keepAliveTime: 这个參数是 同意空暇线程存活的时间、 
        第四个參数 unit : 是 时间的单位 、 
        第五个參数 workQueue :这个是一个容器,它里面存放的是、 threadpool.execute(new Runnable()) 运行的线程.new Runnable()、 
        第六个參数 handler:当运行被堵塞时,该处理程序将被堵塞。由于线程的边界和队列容量达到了 。

    工具类 ThreadManager

    介绍完了 线程池參数,那我们就先创建一个线程管理的工具类 ThreadManager

    1. public class ThreadManager {  
    2.     public static final String DEFAULT_SINGLE_POOL_NAME = "DEFAULT_SINGLE_POOL_NAME";  
    3.   
    4.     private static ThreadPoolProxy mLongPool = null;  
    5.     private static Object mLongLock = new Object();  
    6.   
    7.     private static ThreadPoolProxy mShortPool = null;  
    8.     private static Object mShortLock = new Object();  
    9.   
    10.     private static ThreadPoolProxy mDownloadPool = null;  
    11.     private static Object mDownloadLock = new Object();  
    12.   
    13.     private static Map<String, ThreadPoolProxy> mMap = new HashMap<String, ThreadPoolProxy>();  
    14.     private static Object mSingleLock = new Object();  
    15.   
    16.     /** 获取下载线程 */  
    17.     public static ThreadPoolProxy getDownloadPool() {  
    18.         synchronized (mDownloadLock) {  
    19.             if (mDownloadPool == null) {  
    20.                 mDownloadPool = new ThreadPoolProxy(33, 5L);  
    21.             }  
    22.             return mDownloadPool;  
    23.         }  
    24.     }  
    25.   
    26.     /** 获取一个用于运行长耗时任务的线程池。避免和短耗时任务处在同一个队列而堵塞了重要的短耗时任务。通经常使用来联网操作 */  
    27.     public static ThreadPoolProxy getLongPool() {  
    28.         synchronized (mLongLock) {  
    29.             if (mLongPool == null) {  
    30.                 mLongPool = new ThreadPoolProxy(55, 5L);  
    31.             }  
    32.             return mLongPool;  
    33.         }  
    34.     }  
    35.   
    36.     /** 获取一个用于运行短耗时任务的线程池。避免由于和耗时长的任务处在同一个队列而长时间得不到运行,通经常使用来运行本地的IO/SQL */  
    37.     public static ThreadPoolProxy getShortPool() {  
    38.         synchronized (mShortLock) {  
    39.             if (mShortPool == null) {  
    40.                 mShortPool = new ThreadPoolProxy(22, 5L);  
    41.             }  
    42.             return mShortPool;  
    43.         }  
    44.     }  
    45.   
    46.     /** 获取一个单线程池。全部任务将会被依照加入的顺序运行,免除了同步开销的问题 */  
    47.     public static ThreadPoolProxy getSinglePool() {  
    48.         return getSinglePool(DEFAULT_SINGLE_POOL_NAME);  
    49.     }  
    50.   
    51.     /** 获取一个单线程池。全部任务将会被依照加入的顺序运行,免除了同步开销的问题 */  
    52.     public static ThreadPoolProxy getSinglePool(String name) {  
    53.         synchronized (mSingleLock) {  
    54.             ThreadPoolProxy singlePool = mMap.get(name);  
    55.             if (singlePool == null) {  
    56.                 singlePool = new ThreadPoolProxy(11, 5L);  
    57.                 mMap.put(name, singlePool);  
    58.             }  
    59.             return singlePool;  
    60.         }  
    61.     }  
    62.   
    63.     public static class ThreadPoolProxy {  
    64.         private ThreadPoolExecutor mPool;  
    65.         private int mCorePoolSize;  
    66.         private int mMaximumPoolSize;  
    67.         private long mKeepAliveTime;  
    68.   
    69.         private ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long keepAliveTime) {  
    70.             mCorePoolSize = corePoolSize;  
    71.             mMaximumPoolSize = maximumPoolSize;  
    72.             mKeepAliveTime = keepAliveTime;  
    73.         }  
    74.   
    75.         /** 运行任务,当线程池处于关闭,将会又一次创建新的线程池 */  
    76.         public synchronized void execute(Runnable run) {  
    77.             if (run == null) {  
    78.                 return;  
    79.             }  
    80.             if (mPool == null || mPool.isShutdown()) {  
    81.                 mPool = new ThreadPoolExecutor(mCorePoolSize, mMaximumPoolSize, mKeepAliveTime, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory(), new AbortPolicy());  
    82.             }  
    83.             mPool.execute(run);  
    84.         }  
    85.   
    86.         /** 取消线程池中某个还未运行的任务 */  
    87.         public synchronized void cancel(Runnable run) {  
    88.             if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {  
    89.                 mPool.getQueue().remove(run);  
    90.             }  
    91.         }  
    92.   
    93.         /** 取消线程池中某个还未运行的任务 */  
    94.         public synchronized boolean contains(Runnable run) {  
    95.             if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {  
    96.                 return mPool.getQueue().contains(run);  
    97.             } else {  
    98.                 return false;  
    99.             }  
    100.         }  
    101.   
    102.         /** 立马关闭线程池,而且正在运行的任务也将会被中断 */  
    103.         public void stop() {  
    104.             if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {  
    105.                 mPool.shutdownNow();  
    106.             }  
    107.         }  
    108.   
    109.         /** 平缓关闭单任务线程池,可是会确保全部已经加入的任务都将会被运行完成才关闭 */  
    110.         public synchronized void shutdown() {  
    111.             if (mPool != null && (!mPool.isShutdown() || mPool.isTerminating())) {  
    112.                 mPool.shutdownNow();  
    113.             }  
    114.         }  
    115.   
    116.     }  
    117. }  

        个线程池工具类 主要就是 生成一个线程池。 以及 取消线程池中的任务,查询线程池中是否包括某一任务。

    下载任务 DownloadTask

        我们的如今线程 DownloadTask 就 通过 ThreadManager .getDownloadPool().execute() 方法 交给线程池去管理。

        有了线程池管理我们的线程。 那我们下一步 就是 DownloadTask 这个类去下载了。

    1. /** 下载任务 */  
    2.   public class DownloadTask implements Runnable {  
    3.       private DownloadInfo info;  
    4.   
    5.       public DownloadTask(DownloadInfo info) {  
    6.           this.info = info;  
    7.       }  
    8.   
    9.       @Override  
    10.       public void run() {  
    11.           info.setDownloadState(STATE_DOWNLOADING);// 先改变下载状态  
    12.           notifyDownloadStateChanged(info);  
    13.           File file = new File(info.getPath());// 获取下载文件  
    14.           HttpResult httpResult = null;  
    15.           InputStream stream = null;  
    16.           if (info.getCurrentSize() == 0 || !file.exists()  
    17.                   || file.length() != info.getCurrentSize()) {  
    18.               // 假设文件不存在,或者进度为0,或者进度和文件长度不相符。就须要又一次下载  
    19.   
    20.               info.setCurrentSize(0);  
    21.               file.delete();  
    22.           }  
    23.           httpResult = HttpHelper.download(info.getUrl());  
    24.           // else {  
    25.           // // //文件存在且长度和进度相等。採用断点下载  
    26.           // httpResult = HttpHelper.download(info.getUrl() + "&range=" +  
    27.           // info.getCurrentSize());  
    28.           // }  
    29.           if (httpResult == null  
    30.                   || (stream = httpResult.getInputStream()) == null) {  
    31.               info.setDownloadState(STATE_ERROR);// 没有下载内容返回,改动为错误状态  
    32.               notifyDownloadStateChanged(info);  
    33.           } else {  
    34.               try {  
    35.                   skipBytesFromStream(stream, info.getCurrentSize());  
    36.               } catch (Exception e1) {  
    37.                   e1.printStackTrace();  
    38.               }  
    39.   
    40.               FileOutputStream fos = null;  
    41.               try {  
    42.                   fos = new FileOutputStream(file, true);  
    43.                   int count = -1;  
    44.                   byte[] buffer = new byte[1024];  
    45.                   while (((count = stream.read(buffer)) != -1)  
    46.                           && info.getDownloadState() == STATE_DOWNLOADING) {  
    47.                       // 每次读取到数据后,都须要推断是否为下载状态。假设不是。下载须要终止,假设是,则刷新进度  
    48.                       fos.write(buffer, 0, count);  
    49.                       fos.flush();  
    50.                       info.setCurrentSize(info.getCurrentSize() + count);  
    51.                       notifyDownloadProgressed(info);// 刷新进度  
    52.                   }  
    53.               } catch (Exception e) {  
    54.                   info.setDownloadState(STATE_ERROR);  
    55.                   notifyDownloadStateChanged(info);  
    56.                   info.setCurrentSize(0);  
    57.                   file.delete();  
    58.               } finally {  
    59.                   IOUtils.close(fos);  
    60.                   if (httpResult != null) {  
    61.                       httpResult.close();  
    62.                   }  
    63.               }  
    64.   
    65.               // 推断进度是否和app总长度相等  
    66.               if (info.getCurrentSize() == info.getAppSize()) {  
    67.                   info.setDownloadState(STATE_DOWNLOADED);  
    68.                   notifyDownloadStateChanged(info);  
    69.               } else if (info.getDownloadState() == STATE_PAUSED) {// 推断状态  
    70.                   notifyDownloadStateChanged(info);  
    71.               } else {  
    72.                   info.setDownloadState(STATE_ERROR);  
    73.                   notifyDownloadStateChanged(info);  
    74.                   info.setCurrentSize(0);// 错误状态须要删除文件  
    75.                   file.delete();  
    76.               }  
    77.           }  
    78.           mTaskMap.remove(info.getId());  
    79.       }  
    80.   }  

        下载的原理 非常easy。就是 通过 目标的URL 拿到流,然后写到本地。

     

        由于下载在 run() 里面运行,这个DownloadTask 类 我们就看run() 方法的实现,所以 关键代码 就是以下一点点

    1. fos = new FileOutputStream(file, true);  
    2.           int count = -1;  
    3.           byte[] buffer = new byte[1024];  
    4.           while (((count = stream.read(buffer)) != -1)  
    5.                   && info.getDownloadState() == STATE_DOWNLOADING) {  
    6.               // 每次读取到数据后。都须要推断是否为下载状态,假设不是,下载须要终止,假设是。则刷新进度  
    7.               fos.write(buffer, 0, count);  
    8.               fos.flush();  
    9.               info.setCurrentSize(info.getCurrentSize() + count);  
    10.               notifyDownloadProgressed(info);// 刷新进度  
    11.           }  

       个在我们刚接触Java 的时候 肯定都写过了。 这就是往本地写数据的代码。所以run()方法中的 前面 就是拿到 stream 输入流, 以及 把file 创建出来。

    刷新进度。状态

        关于控制 button中text 显示 暂停 ,下载。还是进度,就靠 notifyDownloadProgressed(info);和 notifyDownloadStateChanged(info)两个方法, 这两个方法 实际上调用的是两个接口,仅仅要我们在我们须要改变界面的类里 实现这两个接口,就能够接收到 包括最新信息的info对象。而我们在哪个类里改变button 上面 显示的文字呢? 当然是在 我们的adapter 里面了,大家都知道 是在 adapter 的getView() 方法里面 载入的每一条数据的布局。

        那就一起看下是不是这样子呢?

    1. public class RecommendAdapter extends BaseAdapter implements  
    2.         DownloadManager.DownloadObserver {  
    3.   
    4.     ArrayList<AppInfo> list;  
    5.     private List<ViewHolder> mDisplayedHolders;  
    6.     private FinalBitmap finalBitmap;  
    7.     private Context context;  
    8.   
    9.     public RecommendAdapter(ArrayList<AppInfo> list, FinalBitmap finalBitmap,  
    10.             Context context) {  
    11.         this.list = list;  
    12.         this.context = context;  
    13.         this.finalBitmap = finalBitmap;  
    14.         mDisplayedHolders = new ArrayList<ViewHolder>();  
    15.     }  
    16.   
    17.   
    18.   
    19.     public void startObserver() {  
    20.         DownloadManager.getInstance().registerObserver(this);  
    21.     }  
    22.   
    23.     public void stopObserver() {  
    24.         DownloadManager.getInstance().unRegisterObserver(this);  
    25.     }  
    26.   
    27.     @Override  
    28.     public int getCount() {  
    29.         return list.size();  
    30.     }  
    31.   
    32.     @Override  
    33.     public Object getItem(int position) {  
    34.         return list.get(position);  
    35.     }  
    36.   
    37.     @Override  
    38.     public long getItemId(int position) {  
    39.         return position;  
    40.     }  
    41.   
    42.     @Override  
    43.     public View getView(int position, View convertView, ViewGroup parent) {  
    44.         final AppInfo appInfo = list.get(position);  
    45.         final ViewHolder holder;  
    46.   
    47.         if (convertView == null) {  
    48.             holder = new ViewHolder(context);  
    49.         } else {  
    50.             holder = (ViewHolder) convertView.getTag();  
    51.         }  
    52.         holder.setData(appInfo);  
    53.         mDisplayedHolders.add(holder);  
    54.         return holder.getRootView();  
    55.     }  
    56.   
    57.     @Override  
    58.     public void onDownloadStateChanged(DownloadInfo info) {  
    59.         refreshHolder(info);  
    60.     }  
    61.   
    62.     @Override  
    63.     public void onDownloadProgressed(DownloadInfo info) {  
    64.         refreshHolder(info);  
    65.   
    66.     }  
    67.   
    68.     public List<ViewHolder> getDisplayedHolders() {  
    69.         synchronized (mDisplayedHolders) {  
    70.             return new ArrayList<ViewHolder>(mDisplayedHolders);  
    71.         }  
    72.     }  
    73.   
    74.     public void clearAllItem() {  
    75.         if (list != null){  
    76.             list.clear();  
    77.         }  
    78.         if (mDisplayedHolders != null) {  
    79.             mDisplayedHolders.clear();  
    80.         }  
    81.     }  
    82.   
    83.     public void addItems(ArrayList<AppInfo> infos) {  
    84.         list.addAll(infos);  
    85.     }  
    86.   
    87.     private void refreshHolder(final DownloadInfo info) {  
    88.         List<ViewHolder> displayedHolders = getDisplayedHolders();  
    89.         for (int i = 0; i < displayedHolders.size(); i++) {  
    90.             final ViewHolder holder = displayedHolders.get(i);  
    91.             AppInfo appInfo = holder.getData();  
    92.             if (appInfo.getId() == info.getId()) {  
    93.                 AppUtil.post(new Runnable() {  
    94.                     @Override  
    95.                     public void run() {  
    96.                         holder.refreshState(info.getDownloadState(),  
    97.                                 info.getProgress());  
    98.                     }  
    99.                 });  
    100.             }  
    101.         }  
    102.   
    103.     }  
    104.   
    105.     public class ViewHolder {  
    106.         public TextView textView01;  
    107.         public TextView textView02;  
    108.         public TextView textView03;  
    109.         public TextView textView04;  
    110.         public ImageView imageView_icon;  
    111.         public Button button;  
    112.         public LinearLayout linearLayout;  
    113.   
    114.         public AppInfo mData;  
    115.         private DownloadManager mDownloadManager;  
    116.         private int mState;  
    117.         private float mProgress;  
    118.         protected View mRootView;  
    119.         private Context context;  
    120.         private boolean hasAttached;  
    121.   
    122.         public ViewHolder(Context context) {  
    123.             mRootView = initView();  
    124.             mRootView.setTag(this);  
    125.             this.context = context;  
    126.   
    127.   
    128.         }  
    129.   
    130.         public View getRootView() {  
    131.             return mRootView;  
    132.         }  
    133.   
    134.         public View initView() {  
    135.             View view = AppUtil.inflate(R.layout.item_recommend_award);  
    136.   
    137.             imageView_icon = (ImageView) view  
    138.                     .findViewById(R.id.imageview_task_app_cion);  
    139.   
    140.             textView01 = (TextView) view  
    141.                     .findViewById(R.id.textview_task_app_name);  
    142.             textView02 = (TextView) view  
    143.                     .findViewById(R.id.textview_task_app_size);  
    144.             textView03 = (TextView) view  
    145.                     .findViewById(R.id.textview_task_app_desc);  
    146.             textView04 = (TextView) view  
    147.                     .findViewById(R.id.textview_task_app_love);  
    148.             button = (Button) view.findViewById(R.id.button_task_download);  
    149.             linearLayout = (LinearLayout) view  
    150.                     .findViewById(R.id.linearlayout_task);  
    151.   
    152.             button.setOnClickListener(new OnClickListener() {  
    153.                 @Override  
    154.                 public void onClick(View v) {  
    155.                     System.out.println("mState:173    "+mState);  
    156.                     if (mState == DownloadManager.STATE_NONE  
    157.                             || mState == DownloadManager.STATE_PAUSED  
    158.                             || mState == DownloadManager.STATE_ERROR) {  
    159.   
    160.                         mDownloadManager.download(mData);  
    161.                     } else if (mState == DownloadManager.STATE_WAITING  
    162.                             || mState == DownloadManager.STATE_DOWNLOADING) {  
    163.                         mDownloadManager.pause(mData);  
    164.                     } else if (mState == DownloadManager.STATE_DOWNLOADED) {  
    165. //                      tell2Server();  
    166.                         mDownloadManager.install(mData);  
    167.                     }  
    168.                 }  
    169.             });  
    170.             return view;  
    171.         }  
    172.   
    173.   
    174.         public void setData(AppInfo data) {  
    175.   
    176.             if (mDownloadManager == null) {  
    177.                 mDownloadManager = DownloadManager.getInstance();  
    178.   
    179.             }  
    180.              String filepath= FileUtil.getDownloadDir(AppUtil.getContext()) + File.separator + data.getName() + ".apk";  
    181.   
    182.                 boolean existsFile = FileUtil.isExistsFile(filepath);  
    183.                 if(existsFile){  
    184.                     int fileSize = FileUtil.getFileSize(filepath);  
    185.   
    186.                     if(data.getSize()==fileSize){  
    187.                         DownloadInfo downloadInfo = DownloadInfo.clone(data);  
    188.                         downloadInfo.setCurrentSize(data.getSize());  
    189.                         downloadInfo.setHasFinished(true);  
    190.                         mDownloadManager.setDownloadInfo(data.getId(),downloadInfo );  
    191.                     }  
    192. //                  else if(fileSize>0){  
    193. //                      DownloadInfo downloadInfo = DownloadInfo.clone(data);  
    194. //                      downloadInfo.setCurrentSize(data.getSize());  
    195. //                      downloadInfo.setHasFinished(false);  
    196. //                      mDownloadManager.setDownloadInfo(data.getId(),downloadInfo );  
    197. //                  }  
    198.   
    199.                 }  
    200.   
    201.             DownloadInfo downloadInfo = mDownloadManager.getDownloadInfo(data  
    202.                     .getId());  
    203.             if (downloadInfo != null) {  
    204.   
    205.                 mState = downloadInfo.getDownloadState();  
    206.                 mProgress = downloadInfo.getProgress();  
    207.             } else {  
    208.   
    209.                 mState = DownloadManager.STATE_NONE;  
    210.                 mProgress = 0;  
    211.             }  
    212.             this.mData = data;  
    213.             refreshView();  
    214.         }  
    215.   
    216.         public AppInfo getData() {  
    217.             return mData;  
    218.         }  
    219.   
    220.         public void refreshView() {  
    221.             linearLayout.removeAllViews();  
    222.             AppInfo info = getData();  
    223.             textView01.setText(info.getName());  
    224.             textView02.setText(FileUtil.FormetFileSize(info.getSize()));  
    225.             textView03.setText(info.getDes());  
    226.             textView04.setText(info.getDownloadNum() + "下载量);  
    227.             finalBitmap.display(imageView_icon, info.getIconUrl());  
    228.   
    229.   
    230.             if (info.getType().equals("0")) {  
    231. //              mState = DownloadManager.STATE_READ;  
    232.                 textView02.setVisibility(View.GONE);  
    233.             }else{  
    234.                 String  path=FileUtil.getDownloadDir(AppUtil.getContext()) + File.separator + info.getName() + ".apk";  
    235.                 hasAttached = FileUtil.isValidAttach(path, false);  
    236.   
    237.                 DownloadInfo downloadInfo = mDownloadManager.getDownloadInfo(info  
    238.                         .getId());  
    239.                 if (downloadInfo != null && hasAttached) {  
    240.                     if(downloadInfo.isHasFinished()){  
    241.   
    242.                         mState = DownloadManager.STATE_DOWNLOADED;  
    243.                     }else{  
    244.                         mState = DownloadManager.STATE_PAUSED;  
    245.   
    246.                     }  
    247.   
    248.                 } else {  
    249.                     mState = DownloadManager.STATE_NONE;  
    250.                     if(downloadInfo !=null){  
    251.                         downloadInfo.setDownloadState(mState);  
    252.                     }  
    253.                 }  
    254.             }  
    255.   
    256.             refreshState(mState, mProgress);  
    257.         }  
    258.   
    259.         public void refreshState(int state, float progress) {  
    260.             mState = state;  
    261.             mProgress = progress;  
    262.             switch (mState) {  
    263.             case DownloadManager.STATE_NONE:  
    264.                 button.setText(R.string.app_state_download);  
    265.                 break;  
    266.             case DownloadManager.STATE_PAUSED:  
    267.                 button.setText(R.string.app_state_paused);  
    268.                 break;  
    269.             case DownloadManager.STATE_ERROR:  
    270.                 button.setText(R.string.app_state_error);  
    271.                 break;  
    272.             case DownloadManager.STATE_WAITING:  
    273.                 button.setText(R.string.app_state_waiting);  
    274.                 break;  
    275.             case DownloadManager.STATE_DOWNLOADING:  
    276.                 button.setText((int) (mProgress * 100) + "%");  
    277.                 break;  
    278.             case DownloadManager.STATE_DOWNLOADED:  
    279.                 button.setText(R.string.app_state_downloaded);  
    280.                 break;  
    281. //          case DownloadManager.STATE_READ:  
    282. //              button.setText(R.string.app_state_read);  
    283. //              break;  
    284.             default:  
    285.                 break;  
    286.             }  
    287.         }  
    288.     }  
    289. }  

    何时 注冊 监听observer

        里面代码有点多,那就看startObserver()方法做了什么。

    1. public void startObserver() {  
    2.        DownloadManager.getInstance().registerObserver(this);  
    3.    }  

    里 是 注冊了observer, Observer 是什么东西?在DownloadManager 中我们定义了 

    public interface DownloadObserver {
    
        public void onDownloadStateChanged(DownloadInfo info);
    
        public void onDownloadProgressed(DownloadInfo info);
    }

        一个接口,里面有两个抽象方法 一个是 进度。还有一个是下载状态。 那回过头来,屡一下。 我们在 下载的关键代码里面调用了 

        DownloadObserver onDownloadProgressed() 

        DownloadObserver.onDownloadStateChanged()

        两个抽象方法,而我们在 adapter实现了 这两个方法 就能够轻松的控制 去 刷新 和改变 下载状态了。

    1. @Override  
    2.   public void onDownloadStateChanged(DownloadInfo info) {  
    3.       refreshHolder(info);  
    4.   }  
    5.   
    6.   @Override  
    7.   public void onDownloadProgressed(DownloadInfo info) {  
    8.       refreshHolder(info);  
    9.   
    10.   }  

        细心的朋友 也许 发现问题了,对,我们还没有注冊Observer,就在 DownloadManager 中去调用了。 

    这里 在看下DownloadManager 中 调用的方法

    /** 当下载状态发送改变的时候回调 */
    public void notifyDownloadStateChanged(DownloadInfo info) {
        synchronized (mObservers) {
            for (DownloadObserver observer : mObservers) {
                observer.onDownloadStateChanged(info);
            }
        }
    }
    
    /** 当下载进度发送改变的时候回调 */
    public void notifyDownloadProgressed(DownloadInfo info) {
        synchronized (mObservers) {
            for (DownloadObserver observer : mObservers) {
                observer.onDownloadProgressed(info);
            }
        }
    }

        是的。这里我们遍历一个observer容器。然后去刷新 。所以我们还须要把Observer对象加入到集合mObservers中,所以肯定有这样一个方法将observer加入到集合中 。 

    /* 注冊观察者 / 
    public void registerObserver(DownloadObserver observer) { 
    synchronized (mObservers) { 
    if (!mObservers.contains(observer)) { 
    mObservers.add(observer); 
    } 
    } 
    }


    /** 反注冊观察者 */
    public void unRegisterObserver(DownloadObserver observer) {
        synchronized (mObservers) {
            if (mObservers.contains(observer)) {
                mObservers.remove(observer);
            }
        }
    }

         所以最后一步,由于 adapter 方法中有 startObserver, 所以 我们在 主界面 MainActivity 的类中调用 adapter.startObser() 将 实现了 接口的adapter 对象 加入到 Observer 容器中 就能够了。

        OK。大功告成。

    =============================================

    DownloadManager 代码

        这里 贴一下DownloadManager 代码

    1. public class DownloadManager {  
    2.     public static final int STATE_NONE = 0;  
    3.     /** 等待中 */  
    4.     public static final int STATE_WAITING = 1;  
    5.     /** 下载中 */  
    6.     public static final int STATE_DOWNLOADING = 2;  
    7.     /** 暂停 */  
    8.     public static final int STATE_PAUSED = 3;  
    9.     /** 完成下载 */  
    10.     public static final int STATE_DOWNLOADED = 4;  
    11.     /** 下载失败 */  
    12.     public static final int STATE_ERROR = 5;  
    13.   
    14.     // public static final int STATE_READ = 6;  
    15.   
    16.     private static DownloadManager instance;  
    17.   
    18.     private DownloadManager() {  
    19.     }  
    20.   
    21.     /** 用于记录下载信息。假设是正式项目,须要持久化保存 */  
    22.     private Map<Long, DownloadInfo> mDownloadMap = new ConcurrentHashMap<Long, DownloadInfo>();  
    23.     /** 用于记录观察者。当信息发送了改变,须要通知他们 */  
    24.     private List<DownloadObserver> mObservers = new ArrayList<DownloadObserver>();  
    25.     /** 用于记录全部下载的任务,方便在取消下载时,通过id能找到该任务进行删除 */  
    26.     private Map<Long, DownloadTask> mTaskMap = new ConcurrentHashMap<Long, DownloadTask>();  
    27.   
    28.     public static synchronized DownloadManager getInstance() {  
    29.         if (instance == null) {  
    30.             instance = new DownloadManager();  
    31.         }  
    32.         return instance;  
    33.     }  
    34.   
    35.     /** 注冊观察者 */  
    36.     public void registerObserver(DownloadObserver observer) {  
    37.         synchronized (mObservers) {  
    38.             if (!mObservers.contains(observer)) {  
    39.                 mObservers.add(observer);  
    40.             }  
    41.         }  
    42.     }  
    43.   
    44.     /** 反注冊观察者 */  
    45.     public void unRegisterObserver(DownloadObserver observer) {  
    46.         synchronized (mObservers) {  
    47.             if (mObservers.contains(observer)) {  
    48.                 mObservers.remove(observer);  
    49.             }  
    50.         }  
    51.     }  
    52.   
    53.     /** 当下载状态发送改变的时候回调 */  
    54.     public void notifyDownloadStateChanged(DownloadInfo info) {  
    55.         synchronized (mObservers) {  
    56.             for (DownloadObserver observer : mObservers) {  
    57.                 observer.onDownloadStateChanged(info);  
    58.             }  
    59.         }  
    60.     }  
    61.   
    62.     /** 当下载进度发送改变的时候回调 */  
    63.     public void notifyDownloadProgressed(DownloadInfo info) {  
    64.         synchronized (mObservers) {  
    65.             for (DownloadObserver observer : mObservers) {  
    66.                 observer.onDownloadProgressed(info);  
    67.             }  
    68.         }  
    69.     }  
    70.   
    71.     /** 下载。须要传入一个appInfo对象 */  
    72.     public synchronized void download(AppInfo appInfo) {  
    73.         // 先推断是否有这个app的下载信息  
    74.         DownloadInfo info = mDownloadMap.get(appInfo.getId());  
    75.         if (info == null) {// 假设没有,则依据appInfo创建一个新的下载信息  
    76.             info = DownloadInfo.clone(appInfo);  
    77.             mDownloadMap.put(appInfo.getId(), info);  
    78.         }  
    79.         // 推断状态是否为STATE_NONE、STATE_PAUSED、STATE_ERROR。仅仅有这3种状态才干进行下载,其它状态不予处理  
    80.         if (info.getDownloadState() == STATE_NONE  
    81.                 || info.getDownloadState() == STATE_PAUSED  
    82.                 || info.getDownloadState() == STATE_ERROR) {  
    83.             // 下载之前。把状态设置为STATE_WAITING,由于此时并没有产開始下载,仅仅是把任务放入了线程池中,当任务真正開始运行时。才会改为STATE_DOWNLOADING  
    84.             info.setDownloadState(STATE_WAITING);  
    85.             notifyDownloadStateChanged(info);// 每次状态发生改变。都须要回调该方法通知全部观察者  
    86.             DownloadTask task = new DownloadTask(info);// 创建一个下载任务,放入线程池  
    87.             mTaskMap.put(info.getId(), task);  
    88.             ThreadManager.getDownloadPool().execute(task);  
    89.         }  
    90.     }  
    91.   
    92.     /** 暂停下载 */  
    93.     public synchronized void pause(AppInfo appInfo) {  
    94.         stopDownload(appInfo);  
    95.         DownloadInfo info = mDownloadMap.get(appInfo.getId());// 找出下载信息  
    96.         if (info != null) {// 改动下载状态  
    97.             info.setDownloadState(STATE_PAUSED);  
    98.             notifyDownloadStateChanged(info);  
    99.         }  
    100.     }  
    101.   
    102.     /** 取消下载。逻辑和暂停相似,仅仅是须要删除已下载的文件 */  
    103.     public synchronized void cancel(AppInfo appInfo) {  
    104.         stopDownload(appInfo);  
    105.         DownloadInfo info = mDownloadMap.get(appInfo.getId());// 找出下载信息  
    106.         if (info != null) {// 改动下载状态并删除文件  
    107.             info.setDownloadState(STATE_NONE);  
    108.             notifyDownloadStateChanged(info);  
    109.             info.setCurrentSize(0);  
    110.             File file = new File(info.getPath());  
    111.             file.delete();  
    112.         }  
    113.     }  
    114.   
    115.     /** 安装应用 */  
    116.     public synchronized void install(AppInfo appInfo) {  
    117.         stopDownload(appInfo);  
    118.         DownloadInfo info = mDownloadMap.get(appInfo.getId());// 找出下载信息  
    119.         if (info != null) {// 发送安装的意图  
    120.             Intent installIntent = new Intent(Intent.ACTION_VIEW);  
    121.             installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    122.             installIntent.setDataAndType(Uri.parse("file://" + info.getPath()),  
    123.                     "application/vnd.android.package-archive");  
    124.             AppUtil.getContext().startActivity(installIntent);  
    125.         }  
    126.         notifyDownloadStateChanged(info);  
    127.     }  
    128.   
    129.     /** 启动应用,启动应用是最后一个 */  
    130.     public synchronized void open(AppInfo appInfo) {  
    131.         try {  
    132.             Context context = AppUtil.getContext();  
    133.             // 获取启动Intent  
    134.             Intent intent = context.getPackageManager()  
    135.                     .getLaunchIntentForPackage(appInfo.getPackageName());  
    136.             context.startActivity(intent);  
    137.         } catch (Exception e) {  
    138.         }  
    139.     }  
    140.   
    141.     /** 假设该下载任务还处于线程池中,且没有运行,先从线程池中移除 */  
    142.     private void stopDownload(AppInfo appInfo) {  
    143.         DownloadTask task = mTaskMap.remove(appInfo.getId());// 先从集合中找出下载任务  
    144.         if (task != null) {  
    145.             ThreadManager.getDownloadPool().cancel(task);// 然后从线程池中移除  
    146.         }  
    147.     }  
    148.   
    149.     /** 获取下载信息 */  
    150.     public synchronized DownloadInfo getDownloadInfo(long id) {  
    151.         return mDownloadMap.get(id);  
    152.     }  
    153.   
    154.     public synchronized void setDownloadInfo(long id, DownloadInfo info) {  
    155.         mDownloadMap.put(id, info);  
    156.     }  
    157.   
    158.     /** 下载任务 */  
    159.     public class DownloadTask implements Runnable {  
    160.         private DownloadInfo info;  
    161.   
    162.         public DownloadTask(DownloadInfo info) {  
    163.             this.info = info;  
    164.         }  
    165.   
    166.         @Override  
    167.         public void run() {  
    168.             info.setDownloadState(STATE_DOWNLOADING);// 先改变下载状态  
    169.             notifyDownloadStateChanged(info);  
    170.             File file = new File(info.getPath());// 获取下载文件  
    171.             HttpResult httpResult = null;  
    172.             InputStream stream = null;  
    173.             if (info.getCurrentSize() == 0 || !file.exists()  
    174.                     || file.length() != info.getCurrentSize()) {  
    175.                 // 假设文件不存在,或者进度为0,或者进度和文件长度不相符。就须要又一次下载  
    176.   
    177.                 info.setCurrentSize(0);  
    178.                 file.delete();  
    179.             }  
    180.             httpResult = HttpHelper.download(info.getUrl());  
    181.             // else {  
    182.             // // //文件存在且长度和进度相等。採用断点下载  
    183.             // httpResult = HttpHelper.download(info.getUrl() + "&range=" +  
    184.             // info.getCurrentSize());  
    185.             // }  
    186.             if (httpResult == null  
    187.                     || (stream = httpResult.getInputStream()) == null) {  
    188.                 info.setDownloadState(STATE_ERROR);// 没有下载内容返回。改动为错误状态  
    189.                 notifyDownloadStateChanged(info);  
    190.             } else {  
    191.                 try {  
    192.                     skipBytesFromStream(stream, info.getCurrentSize());  
    193.                 } catch (Exception e1) {  
    194.                     e1.printStackTrace();  
    195.                 }  
    196.   
    197.                 FileOutputStream fos = null;  
    198.                 try {  
    199.                     fos = new FileOutputStream(file, true);  
    200.                     int count = -1;  
    201.                     byte[] buffer = new byte[1024];  
    202.                     while (((count = stream.read(buffer)) != -1)  
    203.                             && info.getDownloadState() == STATE_DOWNLOADING) {  
    204.                         // 每次读取到数据后,都须要推断是否为下载状态,假设不是。下载须要终止。假设是,则刷新进度  
    205.                         fos.write(buffer, 0, count);  
    206.                         fos.flush();  
    207.                         info.setCurrentSize(info.getCurrentSize() + count);  
    208.                         notifyDownloadProgressed(info);// 刷新进度  
    209.                     }  
    210.                 } catch (Exception e) {  
    211.                     info.setDownloadState(STATE_ERROR);  
    212.                     notifyDownloadStateChanged(info);  
    213.                     info.setCurrentSize(0);  
    214.                     file.delete();  
    215.                 } finally {  
    216.                     IOUtils.close(fos);  
    217.                     if (httpResult != null) {  
    218.                         httpResult.close();  
    219.                     }  
    220.                 }  
    221.   
    222.                 // 推断进度是否和app总长度相等  
    223.                 if (info.getCurrentSize() == info.getAppSize()) {  
    224.                     info.setDownloadState(STATE_DOWNLOADED);  
    225.                     notifyDownloadStateChanged(info);  
    226.                 } else if (info.getDownloadState() == STATE_PAUSED) {// 推断状态  
    227.                     notifyDownloadStateChanged(info);  
    228.                 } else {  
    229.                     info.setDownloadState(STATE_ERROR);  
    230.                     notifyDownloadStateChanged(info);  
    231.                     info.setCurrentSize(0);// 错误状态须要删除文件  
    232.                     file.delete();  
    233.                 }  
    234.             }  
    235.             mTaskMap.remove(info.getId());  
    236.         }  
    237.     }  
    238.   
    239.     public interface DownloadObserver {  
    240.   
    241.         public abstract void onDownloadStateChanged(DownloadInfo info);  
    242.   
    243.         public abstract void onDownloadProgressed(DownloadInfo info);  
    244.     }  
    245.   
    246.     /* 重写了Inpustream 中的skip(long n) 方法,将数据流中起始的n 个字节跳过 */  
    247.     private long skipBytesFromStream(InputStream inputStream, long n) {  
    248.         long remaining = n;  
    249.         // SKIP_BUFFER_SIZE is used to determine the size of skipBuffer  
    250.         int SKIP_BUFFER_SIZE = 10000;  
    251.         // skipBuffer is initialized in skip(long), if needed.  
    252.         byte[] skipBuffer = null;  
    253.         int nr = 0;  
    254.         if (skipBuffer == null) {  
    255.             skipBuffer = new byte[SKIP_BUFFER_SIZE];  
    256.         }  
    257.         byte[] localSkipBuffer = skipBuffer;  
    258.         if (n <= 0) {  
    259.             return 0;  
    260.         }  
    261.         while (remaining > 0) {  
    262.             try {  
    263.                 long skip = inputStream.skip(10000);  
    264.                 nr = inputStream.read(localSkipBuffer, 0,  
    265.                         (int) Math.min(SKIP_BUFFER_SIZE, remaining));  
    266.             } catch (IOException e) {  
    267.                 e.printStackTrace();  
    268.             }  
    269.             if (nr < 0) {  
    270.                 break;  
    271.             }  
    272.             remaining -= nr;  
    273.         }  
    274.         return n - remaining;  
    275.     }  
    276. }  

        两点 须要说明。关于 点击暂停后。再继续下载 有两种方式能够实现

        第一种 点击暂停的时候 记录下载了 多少,然后 再点击 继续下载 时,告诉服务器, 让服务器接着 上次的数据 往本地传递,

        代码 就是 我们 DownloadTask 下载时候,推断一下

    1. // //文件存在且长度和进度相等,採用断点下载  
    2.             httpResult = HttpHelper.download(info.getUrl() + "&range=" + info.getCurrentSize());  
        通过 range 来区分 当前的下载size.

        服务器 处理的代码 也非常easy 就是一句话

        String range = req.getParameter(“range”); 拿到 range 推断 range 存在不存在。 
        假设不存在

    1. FileInputStream stream = new FileInputStream(file);  
    2.           int count = -1;  
    3.           byte[] buffer = new byte[1024];  
    4.           while ((count = stream.read(buffer)) != -1) {  
    5.               SystemClock.sleep(20);  
    6.               out.write(buffer, 0, count);  
    7.               out.flush();  
    8.           }  
    9.           stream.close();  
    10.           out.close();  

      果存在 那么跳过range 个字节

    1. RandomAccessFile raf = new RandomAccessFile(file, "r");  
    2.             raf.seek(Long.valueOf(range));    
    3.             int count = -1;  
    4.             byte[] buffer = new byte[1024];  
    5.             while ((count = raf.read(buffer)) != -1) {  
    6.                 SystemClock.sleep(10);  
    7.                 out.write(buffer, 0, count);  
    8.                 out.flush();  
    9.             }  
    10.             raf.close();  
    11.             out.close();  

        还有一种方式是本地处理,这个demo 中就是本地处理的, 可是有一个问题。 由于 Java api的原因 。inputStream.skip() 方法 并不能准确的 跳过多少个字节。

    而是 小于你想要跳过的字节,所以 你要去遍历 一直到 满足你要跳过的字节 在继续写。 由于 这个方案有一个缺点。就是在下载非常大的文件,

    比方文件大小20M ,当已经下载了15M 此时你去暂停。在继续下载,那么要跳过前面的15M 将会话费非常多时间。

        所以这个仅限于学习。实际中 假设要下载大的文件。不能用这个方案。

    完美版 过几天 再发。

        代码下载 : 
        AndroidStudio 版 
        Eclipse 版

    -------------------------------------------各级格机格机格机--------------------------------------



    -------------------------------改进版 :点击打开链接------------------------

        谢谢认真观读本文的每一位小伙伴,衷心欢迎小伙伴给我指出文中的错误,也欢迎小伙伴与我交流学习。

        欢迎爱学习的小伙伴加群一起进步:230274309 。

  • 相关阅读:
    20165320 第四次实验 Android开发
    20165320 第十周课上测试补做
    20165320 第九周课下测试补做
    20165320 Java实验三:敏捷开发与XP实践
    20165320 第九周学习总结
    20165320 第八周课下补做
    20165320 结对编程第二周
    20165320 第八周学习总结
    20165329 Java实验二:面向对象编程
    第十周课上测试补做
  • 原文地址:https://www.cnblogs.com/jhcelue/p/6817483.html
Copyright © 2011-2022 走看看