Android 自带的DownloadManager 在Service 中下载 apk 安装

  在Android 中如果请求网络,数据量小的时候,可以使用Volley 库,但是如果是下载数据非常大时,变的不可行了。这时我们可以使用Andoid 自带的 DownloadManager ,只要是api 9以上都可以用。网上也有很多例子,但是大部分都是放在Activity 中,这样带来很多的不便。当我们下载大文件时必须在这个界面。所以,我就根据网上的例子,自己改造了一下,把下载放在Service 中,用来下载apk 安装。


   1、首先,拿到启动Service 时传过来的 下载Url ,  DownloadManager 下载后会发出一个广播,所以我们同时注册下载完成的广播;

       

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. Intent intent = new Intent(MainActivity.this, DownloadRecommdAppService.class);  
  2.                 intent.putExtra(DownloadRecommdAppService.DOWNLOAD_URL, url);  
  3.                 startService(intent);  

   2、因为 Service 也是运行在主线程中的,所以,我们把下载这些耗时的工作另开线程进行。

   3、在广播中,通过判断下载的状态,如果下载成功,就启动安装apk, 同时停止 Service.


  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public class DownloadRecommdAppService extends Service{  
  2.   
  3.     public static final String DOWNLOAD_URL = "download_url";  
  4.     public static final String DOWNLOAD_FOLDER_NAME = "download";  
  5.     public  static final String DOWNLOAD_FILE_NAME = "yxhuang.apk";  
  6.       
  7.       
  8.     @Override  
  9.     public IBinder onBind(Intent intent) {  
  10.         return null;  
  11.     }  
  12.       
  13.     @Override  
  14.     public int onStartCommand(Intent intent, int flags, int startId) {  
  15.         if (intent != null) {  
  16.             String downloadUrl = intent.getExtras().getString(DOWNLOAD_URL);  
  17.             if (downloadUrl != null) {  
  18.                 // 注册下载完成广播  
  19.                 DownloadCompleteReceiver completeReceiver = new DownloadCompleteReceiver();  
  20.                 registerReceiver(completeReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));  
  21.                 // 下载  
  22.                 new Thread(new DownloadRunable(downloadUrl)).start();  
  23.             }  
  24.         }  
  25.         return super.onStartCommand(intent, flags, startId);  
  26.     }  
  27.   
  28.     // 下载  
  29.     class DownloadRunable implements Runnable{  
  30.         private String mDownloadUrl;  
  31.           
  32.         public DownloadRunable(String url) {  
  33.             mDownloadUrl = url;  
  34.         }  
  35.           
  36.         @Override  
  37.         public void run() {  
  38.             startDownload();  
  39.         }  
  40.           
  41.         // 开始下载  
  42.         private void startDownload(){  
  43.               
  44.             File folder = Environment.getExternalStoragePublicDirectory(DOWNLOAD_FOLDER_NAME);  
  45.             if (!folder.exists() || !folder.isDirectory()) {  
  46.                 folder.mkdirs();  
  47.             }  
  48.               
  49.             DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);  
  50.             DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mDownloadUrl));  
  51.             request.setMimeType("application/vnd.android.package-archive");  
  52.             // 存储的目录  
  53.             request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME, DOWNLOAD_FILE_NAME);  
  54.             // 设定只有在 WIFI 情况下才能下载  
  55.             request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);  
  56.             request.setTitle("下载应用");  
  57.             request.setVisibleInDownloadsUi(true);  
  58.             manager.enqueue(request);  
  59.         }  
  60.     }  
  61.       
  62.       
  63.     // 下载完成  
  64.      class DownloadCompleteReceiver extends BroadcastReceiver {  
  65.   
  66.             @Override  
  67.             public void onReceive(Context context, Intent intent) {  
  68.                  long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);  
  69.                 if (intent.getAction() == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {  
  70.                     checkStatus(context, completeDownloadId);  
  71.                 }  
  72.             }  
  73.               
  74.             private void checkStatus(Context context,Long completeDownloadId){  
  75.                 DownloadManager mManager  = (DownloadManager) context.getSystemService(Service.DOWNLOAD_SERVICE);  
  76.                 DownloadManager.Query query = new DownloadManager.Query();  
  77.                 query.setFilterById(completeDownloadId);  
  78.                 Cursor cursor = mManager.query(query);  
  79.                 if (cursor.moveToFirst()) {  
  80.                     int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));  
  81.                       
  82.                     switch (status) {  
  83.                     case DownloadManager.STATUS_RUNNING:  
  84.                         break;  
  85.                           
  86.                     case DownloadManager.STATUS_SUCCESSFUL:  
  87.                         Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();  
  88.                          String apkFilePath = new StringBuilder(Environment.getExternalStorageDirectory().getAbsolutePath())  
  89.                          .append(File.separator).append(DownloadRecommdAppService.DOWNLOAD_FOLDER_NAME).append(File.separator)  
  90.                          .append(DownloadRecommdAppService.DOWNLOAD_FILE_NAME).toString();  
  91.                           
  92.                          installApk(context, apkFilePath);  
  93.                            
  94.                          // 停止下载Service  
  95.                          DownloadRecommdAppService.this.stopSelf();  
  96.                         break;  
  97.                           
  98.                     default:  
  99.                         break;  
  100.                     }  
  101.                 }  
  102.                 cursor.close();  
  103.             }  
  104.               
  105.             // 安装APk  
  106.             private  void installApk(Context context, String file) {  
  107.                 File apkFile = new File(file);  
  108.                 Intent intent = new Intent(Intent.ACTION_VIEW);  
  109.                 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  110.                 intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");  
  111.                 context.startActivity(intent);  
  112.             }  
  113.         }  
  114. }  


 关于 DownloadManager 详细的介绍,移步至 http://www.trinea.cn/android/android-downloadmanager/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值