android downloadmanager

项目本来开始使用的是友盟的自动提示更新功能,现在由于应用市场,系统厂商,运营商等多方面对友盟自动更新服务的限制,友盟将于2016年10月份停止所有应用的自动更新服务,这就让我倒霉了,得自己在客户端写自动更新的功能,目前所用到的是Android中DownLoadManager。

        DownLoadManager也不是什么新鲜玩意了,从Android2.3(API level 9)开始Android用系统服务(Service)的方式提供了Download Manager来优化处理长时间的下载操作。Download Manager处理HTTP连接并监控连接中的状态变化以及系统重启来确保每一个下载任务顺利完成。当然写这片文章也借鉴了不少网上的类似的文章,但是还是会有一些干货存在的,希望大家认真看下去,并且有什么不对的地方大家可以指出来。

        在本文中,我将所有有关的操作全部写在一个DownLoadUtil类里面,并且附有很详细的注释。

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. import java.io.File;  
  2. import android.app.DownloadManager;  
  3. import android.app.DownloadManager.Request;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.content.pm.PackageInfo;  
  7. import android.content.pm.PackageManager;  
  8. import android.database.Cursor;  
  9. import android.net.Uri;  
  10. import android.os.Environment;  
  11. import android.text.TextUtils;  
  12. import android.webkit.MimeTypeMap;  
  13.   
  14. /** 
  15.  * 下载更新的util 主要是负责 版本的相关更新工作 
  16.  * 实际 下载更新的具体步骤: 
  17.  * 1.将自己应用的版本号传递给服务器  服务器与自己最新的app版本号对比(文件命名添加版本号的后缀) 
  18.  * 如果服务器版本号>本地所传递过去的版本号  服务器传递版本号和URL地址过来 本地下载更新 
  19.  * 将下载返回的ID存放在sharedPreference中 
  20.  * 2.如果用户的不正当操作使得下载终止:A:检查数据库中下载的文件状态是否为200(成功) 
  21.  * 如果成功就直接跳转到安装界面   
  22.  * 如果不成功  就将remove(long... ids)当前下载任务remove掉  文件也删除   sp中也数据 清零开启新的下载任务 
  23.  *  
  24.  */  
  25. public class DownLoadUtil {  
  26.     private Context context;  
  27.     private String url;  
  28.     private String notificationTitle;  
  29.     private String notificationDescription;  
  30.     private DownloadManager downLoadManager;  
  31.       
  32.     public static final String DOWNLOAD_FOLDER_NAME = "app/apk/download";  
  33.     public static final String DOWNLOAD_FILE_NAME   = "test.apk";  
  34.       
  35.       
  36.     public String getNotificationTitle() {  
  37.         return notificationTitle;  
  38.     }  
  39.   
  40.     public void setNotificationTitle(String notificationTitle) {  
  41.         this.notificationTitle = notificationTitle;  
  42.     }  
  43.   
  44.     public String getNotificationDescription() {  
  45.         return notificationDescription;  
  46.     }  
  47.   
  48.     public void setNotificationDescription(String notificationDescription) {  
  49.         this.notificationDescription = notificationDescription;  
  50.     }  
  51.   
  52.     public DownLoadUtil(Context context) {  
  53.         this.context = context;  
  54.         downLoadManager = (DownloadManager) this.context  
  55.                 .getSystemService(Context.DOWNLOAD_SERVICE);  
  56.     }  
  57.       
  58.     //得到当前应用的版本号  
  59.     public int getVersionName() throws Exception {  
  60.         //getPackageName()是你当前类的包名,0代表是获取版本信息    
  61.         PackageManager packageManager = context.getPackageManager();  
  62.         PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(),  
  63.                 0);  
  64.         return packInfo.versionCode;  
  65.     }  
  66.       
  67.     /** 
  68.      * 服务端的版本号与客户端的版本号对比 
  69.      * @param localVersion  本地版本号 
  70.      * @param serverVersion  服务器版本号 
  71.      * @return  true 可以下载更新  false 不能下载更新 
  72.      */  
  73.     public boolean canUpdate(int localVersion,int serverVersion){  
  74.         if(localVersion <=0 || serverVersion<=0)  
  75.             return false;  
  76.         if(localVersion>=serverVersion){  
  77.             return false;  
  78.         }  
  79.         return true;  
  80.     }  
  81.       
  82.     public void downLoad(String url){  
  83.         Request request=new Request(Uri.parse(url));  
  84.         //设置状态栏中显示Notification  
  85.         request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  
  86.         if(!TextUtils.isEmpty(getNotificationTitle())){    
  87.             request.setTitle(getNotificationTitle());  
  88.         }  
  89.         if(!TextUtils.isEmpty(getNotificationDescription())){  
  90.             request.setDescription(getNotificationDescription());  
  91.         }  
  92.         //设置可用的网络类型  
  93.         request.setAllowedNetworkTypes(Request.NETWORK_MOBILE  | Request.NETWORK_WIFI);   
  94.         //不显示下载界面    
  95.         request.setVisibleInDownloadsUi(false);   
  96.           
  97.         //创建文件的下载路径  
  98.         File folder = Environment.getExternalStoragePublicDirectory(DOWNLOAD_FOLDER_NAME);  
  99.         if (!folder.exists() || !folder.isDirectory()) {  
  100.             folder.mkdirs();  
  101.         }  
  102.         //指定下载的路径为和上面创建的路径相同  
  103.         request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME, DOWNLOAD_FILE_NAME);  
  104.           
  105.       //设置文件类型    
  106.         MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();    
  107.         String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));    
  108.         request.setMimeType(mimeString);  
  109.         //将请求加入请求队列会 downLoadManager会自动调用对应的服务执行者个请求  
  110.         downLoadManager.enqueue(request);    
  111.     }  
  112.       
  113.     //文件的安装 方法  
  114.     public static boolean install(Context context, String filePath) {  
  115.         Intent intent = new Intent(Intent.ACTION_VIEW);  
  116.         File file = new File(filePath);  
  117.         if (file != null && file.length() > 0 && file.exists() && file.isFile()) {  
  118.             intent.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");  
  119.             intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  120.             context.startActivity(intent);  
  121.             return true;  
  122.         }  
  123.         return false;  
  124.     }  
  125. }  

在DownloadUtil中包括了请求的方法,比较版本号,安装最新版本的apk文件的方法。

代码59-65行中,定义了一个得到本地apk版本号的方法。

代码68-80行,比较本地版本号和服务器apk的版本号,返回是否需要更新的布尔值。在实际项目中,你的应用可能需要在你每次登陆进去的时候,访问网络请求,得到服务器的apk的最新版本号,与自己本地的版本号对比,来控制是否立即更新或者稍后再说的dialog的显示。

在代码的85-91行中,设置了下载文件是Notifiction的显示状况和样式。setNotificationVisibility用来控制什么时候显示notification甚至隐藏。主要有以下几个参数:

Request.VISIBILITY_VISIBLE:在下载进行的过程中,通知栏中会一直显示该下载的Notification,当下载完成时,该Notification会被移除,这是默认的参数值。
Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED:在下载过程中通知栏会一直显示该下载的Notification,在下载完成后该Notification会继续显示,直到用户点击该Notification或者消除该Notification。
Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION:只有在下载完成后该Notification才会被显示。
Request.VISIBILITY_HIDDEN:不显示该下载请求的Notification。如果要使用这个参数,需要在应用的清单文件中加上DOWNLOAD_WITHOUT_NOTIFICATION权限。

在代码中的110行将请求加入到请求队列中,如果文件下载完成,就会向系统发送一个广播。

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. import android.app.DownloadManager;  
  2. import android.content.BroadcastReceiver;  
  3. import android.content.Context;  
  4. import android.content.Intent;  
  5. /** 
  6.  * 运用downloadManager下载完成之后 通知系统我下载完成 
  7.  * 
  8.  */  
  9. public class DownLoadReceiver extends BroadcastReceiver {  
  10.   
  11.     @Override  
  12.     public void onReceive(Context context, Intent intent) {  
  13.         if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){  
  14.               
  15.         }  
  16.   
  17.     }  
  18.   
  19. }  

其实自己可以简单的定义一个广播接收者,来接收对应Action的广播。当我们接受到的广播的Action为ACTION_DOWNLOAD_COMPLETE的时候我们可以 进行最新版本的APK的安装操作,也就是上面DownloadUtil类中的install方法。

 

 

其实系统的DownLoadManager是用ContentProvider来实现的。看看上面DownUtil类中download方法中最后一句代码,downloadManager.enqueue(request)我们看源代码

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. public long enqueue(Request request) {  
  2.        ContentValues values = request.toContentValues(mPackageName);  
  3.        Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);  
  4.        long id = Long.parseLong(downloadUri.getLastPathSegment());  
  5.        return id;  
  6.    }  

看到我们熟悉的代码mResolver.insert方法 只实际就是我们的访问contentProvider对象,可以去查看相应的URI参数public static final Uri CONTENT_URI =Uri.parse("content://downloads/my_downloads");这个正是,我们的系统源代码downloadProvider中的URI,DownloadProvicer源代码位于Android源码中的packages/providers下面 可以自行下载查看

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. static {  
  2.     sURIMatcher.addURI("downloads", "my_downloads", MY_DOWNLOADS);  
  3.     sURIMatcher.addURI("downloads", "my_downloads/#", MY_DOWNLOADS_ID);  
  4.     sURIMatcher.addURI("downloads", "all_downloads", ALL_DOWNLOADS);  
  5.     sURIMatcher.addURI("downloads", "all_downloads/#", ALL_DOWNLOADS_ID);  
  6.     sURIMatcher.addURI("downloads",  
  7.             "my_downloads/#/" + Downloads.Impl.RequestHeaders.URI_SEGMENT,  
  8.             REQUEST_HEADERS_URI);  
  9.     sURIMatcher.addURI("downloads",  
  10.             "all_downloads/#/" + Downloads.Impl.RequestHeaders.URI_SEGMENT,  
  11.             REQUEST_HEADERS_URI);  
  12.     // temporary, for backwards compatibility  
  13.     sURIMatcher.addURI("downloads", "download", MY_DOWNLOADS);  
  14.     sURIMatcher.addURI("downloads", "download/#", MY_DOWNLOADS_ID);  
  15.     sURIMatcher.addURI("downloads",  
  16.             "download/#/" + Downloads.Impl.RequestHeaders.URI_SEGMENT,  
  17.             REQUEST_HEADERS_URI);  
  18.     sURIMatcher.addURI("downloads",  
  19.             Downloads.Impl.PUBLICLY_ACCESSIBLE_DOWNLOADS_URI_SEGMENT + "/#",  
  20.             PUBLIC_DOWNLOAD_ID);  
  21. }  

这样就可以访问我们的DownloadProvider了,我们仔细去查看downloadProvider中的insert方法

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.     * Inserts a row in the database 
  3.     */  
  4.    @Override  
  5.    public Uri insert(final Uri uri, final ContentValues values) {  
  6.        checkInsertPermissions(values);  
  7.        SQLiteDatabase db = mOpenHelper.getWritableDatabase();  
  8.   
  9.        // note we disallow inserting into ALL_DOWNLOADS  
  10.        int match = sURIMatcher.match(uri);  
  11.        if (match != MY_DOWNLOADS) {  
  12.            Log.d(Constants.TAG, "calling insert on an unknown/invalid URI: " + uri);  
  13.            throw new IllegalArgumentException("Unknown/Invalid URI " + uri);  
  14.        }  
  15.     //.......中间代码省略  
  16.       
  17.        Context context = getContext();  
  18.        if (values.getAsInteger(Downloads.Impl.COLUMN_DESTINATION) ==  
  19.                Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) {  
  20.            // don't start downloadservice because it has nothing to do in this case.  
  21.            // but does a completion notification need to be sent?  
  22.            if (Downloads.Impl.isNotificationToBeDisplayed(vis)) {  
  23.                DownloadNotification notifier = new DownloadNotification(context, mSystemFacade);  
  24.                notifier.notificationForCompletedDownload(rowID,  
  25.                        values.getAsString(Downloads.Impl.COLUMN_TITLE),  
  26.                        Downloads.Impl.STATUS_SUCCESS,  
  27.                        Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD,  
  28.                        lastMod);  
  29.            }  
  30.        } else {  
  31.            context.startService(new Intent(context, DownloadService.class));  
  32.        }  
  33.       
  34.        notifyContentChanged(uri, match);  
  35.        return ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, rowID);  
  36.    }  

代码中的18-29行其实简单得说就是检查我们数据库中是否有东西要下载有事可做 ,没有事情可做就执行else的操作,在else操作中启动了我们的DownloadService的服务,在跟进DownloadService,在DownloadService的onCreate方法中就进行了一些数据的初始化操作。我们看onStartCommend方法中的具体操作和实现

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. @Override  
  2.    public int onStartCommand(Intent intent, int flags, int startId) {  
  3.        int returnValue = super.onStartCommand(intent, flags, startId);  
  4.        if (Constants.LOGVV) {  
  5.            Log.v(Constants.TAG, "Service onStart");  
  6.        }  
  7.        updateFromProvider();  
  8.        return returnValue;  
  9.    }  

看这个方法最重要的方法也就是执行upDateFromProvider方法,再继续跟进

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. private void updateFromProvider() {  
  2.       synchronized (this) {  
  3.           mPendingUpdate = true;  
  4.           if (mUpdateThread == null) {  
  5.               mUpdateThread = new UpdateThread();  
  6.               mSystemFacade.startThread(mUpdateThread);  
  7.           }  
  8.       }  
  9.   }  

启动了一个UpdateThread的线程,是线程我们就来看看他的run方法都干了些什么。

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. public void run() {  
  2.           Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);  
  3.           boolean keepService = false;  
  4.           // for each update from the database, remember which download is  
  5.           // supposed to get restarted soonest in the future  
  6.           long wakeUp = Long.MAX_VALUE;  
  7.           for (;;) {  
  8.               synchronized (DownloadService.this) {  
  9.                   if (mUpdateThread != this) {  
  10.                       throw new IllegalStateException(  
  11.                               "multiple UpdateThreads in DownloadService");  
  12.                   }  
  13.                   if (!mPendingUpdate) {  
  14.                       mUpdateThread = null;  
  15.                       if (!keepService) {  
  16.                           stopSelf();  
  17.                       }  
  18.                       if (wakeUp != Long.MAX_VALUE) {  
  19.                           scheduleAlarm(wakeUp);  
  20.                       }  
  21.                       return;  
  22.                   }  
  23.                   mPendingUpdate = false;  
  24.               }  
  25.   
  26.               long now = mSystemFacade.currentTimeMillis();  
  27.               boolean mustScan = false;  
  28.               keepService = false;  
  29.               wakeUp = Long.MAX_VALUE;  
  30.               Set<Long> idsNoLongerInDatabase = new HashSet<Long>(mDownloads.keySet());  
  31.   
  32.               Cursor cursor = getContentResolver().query(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,  
  33.                       null, null, null, null);  
  34.               if (cursor == null) {  
  35.                   continue;  
  36.               }  
  37.               try {  
  38.                   DownloadInfo.Reader reader =  
  39.                           new DownloadInfo.Reader(getContentResolver(), cursor);  
  40.                   int idColumn = cursor.getColumnIndexOrThrow(Downloads.Impl._ID);  
  41.                   if (Constants.LOGVV) {  
  42.                       Log.i(Constants.TAG, "number of rows from downloads-db: " +  
  43.                               cursor.getCount());  
  44.                   }  
  45.                   for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {  
  46.                       long id = cursor.getLong(idColumn);  
  47.                       idsNoLongerInDatabase.remove(id);  
  48.                       DownloadInfo info = mDownloads.get(id);  
  49.                       if (info != null) {  
  50.                           updateDownload(reader, info, now);  
  51.                       } else {  
  52.                           info = insertDownload(reader, now);  
  53.                       }  
  54.   
  55.                       if (info.shouldScanFile() && !scanFile(info, true, false)) {  
  56.                           mustScan = true;  
  57.                           keepService = true;  
  58.                       }  
  59.                       if (info.hasCompletionNotification()) {  
  60.                           keepService = true;  
  61.                       }  
  62.                       long next = info.nextAction(now);  
  63.                       if (next == 0) {  
  64.                           keepService = true;  
  65.                       } else if (next > 0 && next < wakeUp) {  
  66.                           wakeUp = next;  
  67.                       }  
  68.                   }  
  69.               } finally {  
  70.                   cursor.close();  
  71.               }  
  72.   
  73.               for (Long id : idsNoLongerInDatabase) {  
  74.                   deleteDownload(id);  
  75.               }  
  76.   
  77.               // is there a need to start the DownloadService? yes, if there are rows to be  
  78.               // deleted.  
  79.               if (!mustScan) {  
  80.                   for (DownloadInfo info : mDownloads.values()) {  
  81.                       if (info.mDeleted && TextUtils.isEmpty(info.mMediaProviderUri)) {  
  82.                           mustScan = true;  
  83.                           keepService = true;  
  84.                           break;  
  85.                       }  
  86.                   }  
  87.               }  
  88.               mNotifier.updateNotification(mDownloads.values());  
  89.               if (mustScan) {  
  90.                   bindMediaScanner();  
  91.               } else {  
  92.                   mMediaScannerConnection.disconnectMediaScanner();  
  93.               }  
  94.   
  95.               // look for all rows with deleted flag set and delete the rows from the database  
  96.               // permanently  
  97.               for (DownloadInfo info : mDownloads.values()) {  
  98.                   if (info.mDeleted) {  
  99.                       // this row is to be deleted from the database. but does it have  
  100.                       // mediaProviderUri?  
  101.                       if (TextUtils.isEmpty(info.mMediaProviderUri)) {  
  102.                           if (info.shouldScanFile()) {  
  103.                               // initiate rescan of the file to - which will populate  
  104.                               // mediaProviderUri column in this row  
  105.                               if (!scanFile(info, false, true)) {  
  106.                                   throw new IllegalStateException("scanFile failed!");  
  107.                               }  
  108.                               continue;  
  109.                           }  
  110.                       } else {  
  111.                           // yes it has mediaProviderUri column already filled in.  
  112.                           // delete it from MediaProvider database.  
  113.                           getContentResolver().delete(Uri.parse(info.mMediaProviderUri), null,  
  114.                                   null);  
  115.                       }  
  116.                       // delete the file  
  117.                       deleteFileIfExists(info.mFileName);  
  118.                       // delete from the downloads db  
  119.                       getContentResolver().delete(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,  
  120.                               Downloads.Impl._ID + " = ? ",  
  121.                               new String[]{String.valueOf(info.mId)});  
  122.                   }  
  123.               }  
  124.           }  
  125.       }  

其实看着大部分代码 ,我们可能看不出来什么也不明白什么,我们只要看懂他的运行逻辑,每一步该做什么,不必在意每一个细节的问题,当我们遇到同样的事情的时候,可以只需要替换他某一步骤成我们的方法就可以进行自己的修改了。好接着看run方法,我们主要看代码的48-53行,在这里获得了一个downloadInfo对象(根据id),当downloadInfo不为null的时候执行updateDownload,

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. private void updateDownload(DownloadInfo.Reader reader, DownloadInfo info, long now) {  
  2.      int oldVisibility = info.mVisibility;  
  3.      int oldStatus = info.mStatus;  
  4.   
  5.      reader.updateFromDatabase(info);  
  6.      if (Constants.LOGVV) {  
  7.          Log.v(Constants.TAG, "processing updated download " + info.mId +  
  8.                  ", status: " + info.mStatus);  
  9.      }  
  10.   
  11.      boolean lostVisibility =  
  12.              oldVisibility == Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED  
  13.              && info.mVisibility != Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED  
  14.              && Downloads.Impl.isStatusCompleted(info.mStatus);  
  15.      boolean justCompleted =  
  16.              !Downloads.Impl.isStatusCompleted(oldStatus)  
  17.              && Downloads.Impl.isStatusCompleted(info.mStatus);  
  18.      if (lostVisibility || justCompleted) {  
  19.          mSystemFacade.cancelNotification(info.mId);  
  20.      }  
  21.   
  22.      info.startIfReady(now, mStorageManager);  
  23.  }  

updateDownload方法里面其实就是根据数据库里面的数据,更新一些Notification的显示状态,最后继续执行info.startIfReady.

如果info为null我们就开始执行insertDownload

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. private DownloadInfo insertDownload(DownloadInfo.Reader reader, long now) {  
  2.         DownloadInfo info = reader.newDownloadInfo(this, mSystemFacade);  
  3.         mDownloads.put(info.mId, info);  
  4.   
  5.         if (Constants.LOGVV) {  
  6.             Log.v(Constants.TAG, "processing inserted download " + info.mId);  
  7.         }  
  8.   
  9.         info.startIfReady(now, mStorageManager);  
  10.         return info;  
  11.     }  

其实就是创建一个新的DownloadInfo将其放入mDownloads的map集合里,最后和上面的updateDownload一样,执行info.startIfReady

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. void startIfReady(long now, StorageManager storageManager) {  
  2.         if (!isReadyToStart(now)) {  
  3.             return;  
  4.         }  
  5.   
  6.         if (Constants.LOGV) {  
  7.             Log.v(Constants.TAG, "Service spawning thread to handle download " + mId);  
  8.         }  
  9.         if (mStatus != Impl.STATUS_RUNNING) {  
  10.             mStatus = Impl.STATUS_RUNNING;  
  11.             ContentValues values = new ContentValues();  
  12.             values.put(Impl.COLUMN_STATUS, mStatus);  
  13.             mContext.getContentResolver().update(getAllDownloadsUri(), values, null, null);  
  14.         }  
  15.         DownloadHandler.getInstance().enqueueDownload(this);  
  16.     }  

在startIfReady中,首先检查下载任务是否正在下载,接着更新数据库数据,最后调用DownloadHandler的enqueueDownload方法执行下载有关的操作

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. synchronized void enqueueDownload(DownloadInfo info) {  
  2.        if (!mDownloadsQueue.containsKey(info.mId)) {  
  3.            if (Constants.LOGV) {  
  4.                Log.i(TAG, "enqueued download. id: " + info.mId + ", uri: " + info.mUri);  
  5.            }  
  6.            mDownloadsQueue.put(info.mId, info);  
  7.            startDownloadThread();  
  8.        }  
  9.    }  

查看DownloadHandler中的enqueueDownload最后其实就是开启了下载的线程startDownloadThrea

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. private synchronized void startDownloadThread() {  
  2.     Iterator<Long> keys = mDownloadsQueue.keySet().iterator();  
  3.     ArrayList<Long> ids = new ArrayList<Long>();  
  4.     while (mDownloadsInProgress.size() < mMaxConcurrentDownloadsAllowed && keys.hasNext()) {  
  5.         Long id = keys.next();  
  6.         DownloadInfo info = mDownloadsQueue.get(id);  
  7.         info.startDownloadThread();  
  8.         ids.add(id);  
  9.         mDownloadsInProgress.put(id, mDownloadsQueue.get(id));  
  10.         if (Constants.LOGV) {  
  11.             Log.i(TAG, "started download for : " + id);  
  12.         }  
  13.     }  
  14.     for (Long id : ids) {  
  15.         mDownloadsQueue.remove(id);  
  16.     }  
  17. }  

其实就是调用了info.startDownloadThread,并将我们的下载任务的id存储起来。

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. void startDownloadThread() {  
  2.      DownloadThread downloader = new DownloadThread(mContext, mSystemFacade, this,  
  3.              StorageManager.getInstance(mContext));  
  4.      mSystemFacade.startThread(downloader);  
  5.  }  

新建DownloadThread,并启动起来。来看下载线程的run方法。

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. public void run() {  
  2.        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);  
  3.   
  4.        State state = new State(mInfo);  
  5.        AndroidHttpClient client = null;  
  6.        PowerManager.WakeLock wakeLock = null;  
  7.        int finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;  
  8.        String errorMsg = null;  
  9.   
  10.        final NetworkPolicyManager netPolicy = NetworkPolicyManager.getSystemService(mContext);  
  11.        final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);  
  12.   
  13.        try {  
  14.            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);  
  15.            wakeLock.acquire();  
  16.   
  17.            // while performing download, register for rules updates  
  18.            netPolicy.registerListener(mPolicyListener);  
  19.   
  20.            if (Constants.LOGV) {  
  21.                Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);  
  22.            }  
  23.   
  24.            client = AndroidHttpClient.newInstance(userAgent(), mContext);  
  25.   
  26.            // network traffic on this thread should be counted against the  
  27.            // requesting uid, and is tagged with well-known value.  
  28.            TrafficStats.setThreadStatsTag(TrafficStats.TAG_SYSTEM_DOWNLOAD);  
  29.            TrafficStats.setThreadStatsUid(mInfo.mUid);  
  30.   
  31.            boolean finished = false;  
  32.            while(!finished) {  
  33.                Log.i(Constants.TAG, "Initiating request for download " + mInfo.mId);  
  34.                // Set or unset proxy, which may have changed since last GET request.  
  35.                // setDefaultProxy() supports null as proxy parameter.  
  36.                ConnRouteParams.setDefaultProxy(client.getParams(),  
  37.                        Proxy.getPreferredHttpHost(mContext, state.mRequestUri));  
  38.                HttpGet request = new HttpGet(state.mRequestUri);  
  39.                try {  
  40.                    executeDownload(state, client, request);  
  41.                    finished = true;  
  42.                } catch (RetryDownload exc) {  
  43.                    // fall through  
  44.                } finally {  
  45.                    request.abort();  
  46.                    request = null;  
  47.                }  
  48.            }  
  49.   
  50.            if (Constants.LOGV) {  
  51.                Log.v(Constants.TAG, "download completed for " + mInfo.mUri);  
  52.            }  
  53.            finalizeDestinationFile(state);  
  54.            finalStatus = Downloads.Impl.STATUS_SUCCESS;  
  55.        } catch (StopRequestException error) {  
  56.            // remove the cause before printing, in case it contains PII  
  57.            errorMsg = error.getMessage();  
  58.            String msg = "Aborting request for download " + mInfo.mId + ": " + errorMsg;  
  59.            Log.w(Constants.TAG, msg);  
  60.            if (Constants.LOGV) {  
  61.                Log.w(Constants.TAG, msg, error);  
  62.            }  
  63.            finalStatus = error.mFinalStatus;  
  64.            // fall through to finally block  
  65.        } catch (Throwable ex) { //sometimes the socket code throws unchecked exceptions  
  66.            errorMsg = ex.getMessage();  
  67.            String msg = "Exception for id " + mInfo.mId + ": " + errorMsg;  
  68.            Log.w(Constants.TAG, msg, ex);  
  69.            finalStatus = Downloads.Impl.STATUS_UNKNOWN_ERROR;  
  70.            // falls through to the code that reports an error  
  71.        } finally {  
  72.            TrafficStats.clearThreadStatsTag();  
  73.            TrafficStats.clearThreadStatsUid();  
  74.   
  75.            if (client != null) {  
  76.                client.close();  
  77.                client = null;  
  78.            }  
  79.            cleanupDestination(state, finalStatus);  
  80.            notifyDownloadCompleted(finalStatus, state.mCountRetry, state.mRetryAfter,  
  81.                                    state.mGotData, state.mFilename,  
  82.                                    state.mNewUri, state.mMimeType, errorMsg);  
  83.            DownloadHandler.getInstance().dequeueDownload(mInfo.mId);  
  84.   
  85.            netPolicy.unregisterListener(mPolicyListener);  
  86.   
  87.            if (wakeLock != null) {  
  88.                wakeLock.release();  
  89.                wakeLock = null;  
  90.            }  
  91.        }  
  92.        mStorageManager.incrementNumDownloadsSoFar();  
  93.    }  

这里才是真正的访问网络的操作,具体操作我们就不一一细细解读了。到这里其实运用DownloadManager进行下载的逻辑基本通读了一遍。

 

 

 

其实还有一个细节的操作在我们最开始的downloadUtil的download方法中之后一句代码downLoadManager.enqueue(request);会返回一个long行的id,这个id就是我们provider中存放的id。我们可以将这个id记录在我们的文件或者sharedPreference中,当我们由于某种原因(网络或者认为原因)使下载中断的时候,我们可以再下次再次进入服务器的时候,继续请求服务器,根据这个id去查询数据库中的文件的下载完成状态是否完成,如果位完成,继续下载或者删除数据库和下载未完成的部分文件,重新下载,如果下载完成,直接在下载的文件夹找到相应的文件提示下载安装。

还有就是,当我们手机中的其他应用也用到DownloadManager进行他们的下载任务的时候,也会记录到数据库中,但是有这么一种可能,当我们2个应用同时下载更新,并且下载完成之后发出广播通知安装的时候,我们可以根据自己的sharedPreference中所记录的id找到自己app下载的文件,检查它的下载状态,最后决定是否执行安装或者其他 操作,这样管理文件的时候以至于不会混乱。

 

这是个人在做项目的时候的一些学习和使用DownloadManager的观点,记录下来方便自己下次使用,也供大家参

posted @ 2016-11-29 17:06  天涯海角路  阅读(444)  评论(0)    收藏  举报