本文主要实现使用DownloadManager实现下载更新
首先得到prefs以及downloadManager
downloadManager = (DownloadManager) currActivity.getSystemService(Context.DOWNLOAD_SERVICE); prefs = PreferenceManager.getDefaultSharedPreferences(currActivity);
然后再检查下载ID是否存在,如果不存在就新建下载任务,如果存在就查询下载状态。
private void downloadFile(String url, String version) { if (!prefs.contains(DL_ID)) { Uri uri = Uri.parse(url); DownloadManager.Request request = new DownloadManager.Request(uri); request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI); request.setAllowedOverRoaming(false); //设置文件类型 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url)); request.setMimeType(mimeString); //在通知栏中显示 request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); request.setVisibleInDownloadsUi(true); request.setDestinationInExternalPublicDir("/download/", " ****.apk"); request.setTitle("******"); long id = downloadManager.enqueue(request); prefs.edit().putLong(DL_ID, id).commit(); showDialog(); } else { //下载已经开始,检查状态 queryDownloadStatus(); } }
showDialog方法主要用于显示下载进度,
public void showDialog() { if (currActivity == null) { return; } currActivity.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); mDownloadObserver = new DownloadObserver(handler, currActivity, prefs.getLong(DL_ID, 0)); currActivity.getContentResolver().registerContentObserver(Uri.parse("content://downloads/"), true, mDownloadObserver); if (mDialog != null && mDialog.isShowing()) { mDialog.dismiss(); mDialog = null; } if (mDialog == null) { mDialog = new Dialog(currActivity, R.style.MyDialog); mDialog.setCancelable(false); mDialog.setCanceledOnTouchOutside(false); } View view = LayoutInflater.from(currActivity).inflate(R.layout.download_progress_dialog_layout, null); progressBar = (ProgressBar) view.findViewById(R.id.download_progress); sizeView = (TextView) view.findViewById(R.id.download_size); mDialog.setContentView(view); mDialog.show(); }
当需要实时显示下载进度时,可以通过监听下载数据库的变化来实时更新下载进度:
在前面注册的contentobserver就是起到这个作用
public class DownloadObserver extends ContentObserver { private long downid; private Handler handler; private Context context; public DownloadObserver(Handler handler, Context context, long downid) { super(handler); this.handler = handler; this.downid = downid; this.context = context; } @Override public void onChange(boolean selfChange) { //每当/data/data/com.android.providers.download/database/database.db变化后,触发onCHANGE,开始具体查询 Log.w("onChangeID", String.valueOf(downid)); super.onChange(selfChange); //实例化查询类,这里需要一个刚刚的downid DownloadManager.Query query = new DownloadManager.Query().setFilterById(downid); DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); //这个就是数据库查询啦 Cursor cursor = downloadManager.query(query); if (cursor.moveToNext()) { int mDownload_so_far = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); int mDownload_all = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); int mProgress = (int) ((mDownload_so_far * 100f) / mDownload_all); Message message = new Message(); Bundle bundle = new Bundle(); bundle.putInt("downSize", mDownload_so_far); bundle.putInt("allSize", mDownload_all); bundle.putInt("progress", mProgress); message.setData(bundle); handler.sendMessage(message); } } }
在数据库下载发生变化时,通过handler来刷新progress,在下载完成之后,查询下载状态,queryDownloadStatus(),如果成功就安装APK, 如果失败就清除已下载内容,重新下载。
private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //这里可以取得下载的id,这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听 queryDownloadStatus(); try { currActivity.unregisterReceiver(receiver); currActivity.getContentResolver().unregisterContentObserver(mDownloadObserver); } catch (Exception e) { e.printStackTrace(); } } }; private void queryDownloadStatus() { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(prefs.getLong(DL_ID, 0)); long downloadId = prefs.getLong(DL_ID, 0); Cursor c = downloadManager.query(query); if (c.moveToFirst()) { int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); switch (status) { case DownloadManager.STATUS_PAUSED: Log.e("AAA", "STATUS_PAUSED"); case DownloadManager.STATUS_PENDING: Log.e("AAA", "STATUS_PENDING"); case DownloadManager.STATUS_RUNNING: //正在下载,不做任何事情 Log.e("AAA", "STATUS_RUNNING"); showDialog(); break; case DownloadManager.STATUS_SUCCESSFUL: if (mDialog != null && mDialog.isShowing()) { mDialog.dismiss(); } //完成 Log.e("AAA", "下载完成"); installApk(downloadId); break; case DownloadManager.STATUS_FAILED: //清除已下载的内容,重新下载 Log.e("AAA", "STATUS_FAILED"); if (mDialog != null && mDialog.isShowing()) { mDialog.dismiss(); } downloadManager.remove(prefs.getLong(DL_ID, 0)); prefs.edit().clear().commit(); break; } } } private void installApk(long downloadId) { try { DownloadManager downloadManager = (DownloadManager) currActivity.getSystemService(Context.DOWNLOAD_SERVICE); Uri filepath = downloadManager.getUriForDownloadedFile(downloadId); Intent activityIntent = new Intent(Intent.ACTION_VIEW); activityIntent.setDataAndType(filepath, "application/vnd.android.package-archive"); activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); currActivity.startActivity(activityIntent); } catch (ActivityNotFoundException ex) { ex.printStackTrace(); } }