Android中使用DownloadManager下载并安装apk

是一个很好用的网络框架,但是 不适合用来下载大的数据文件 。因为会保持在解析的过程中所有的响应 。对于下载大量的数据操作,建议我们使用。
类介绍
官方文档上对是这样介绍的:
Theis athatlong- HTTP .maythat a URI beto afile. Thewillthein the ,care of HTTPandafterorand.of this classbeice()by ICE. Apps thatthis APIawhen the useron ain aor from theUI. Note that themustuse this class.
简而言之:
相关类
包含两个内部类:
.(主要用于发起一个下载请求):
( ,value):添加http的
es(int flags):设置允许的网络类型
(Uri uri):自定义下载目录
ility(int ):设置的显示情况
( title):设置中显示的标题
.Query(主要用于查询下载信息):
(long… ids):添加下载的id,便于查询对应的下载情况 应用下载更新 实例实现后台更新
Step 1:在中通过启动,并传递参数 。
.java:
Intent serviceIntent = new Intent(MainActivity.this,DownloadService.class);//将下载地址url放入intent中serviceIntent.setData(Uri.parse(url));startService(serviceIntent);
Step 2:在中获得url,通过下载应用
.java:
public class DownloadService extends IntentService {private String TAG = "DownloadService";public static final String BROADCAST_ACTION ="com.example.android.threadsample.BROADCAST";public static final String EXTENDED_DATA_STATUS ="com.example.android.threadsample.STATUS";private LocalBroadcastManager mLocalBroadcastManager;public DownloadService() {super("DownloadService");}@Overrideprotected void onHandleIntent(Intent intent) {//获取下载地址String url = intent.getDataString();Log.i(TAG,url);//获取DownloadManager对象DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));//指定APK缓存路径和应用名称,可在SD卡/Android/data/包名/file/Download文件夹中查看request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "mydown.app");//设置网络下载环境为wifirequest.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);//设置显示通知栏,下载完成后通知栏自动消失request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);//设置通知栏标题request.setTitle("下载");request.setDescription("应用正在下载");request.setAllowedOverRoaming(false);//获得唯一下载idlong requestId = downloadManager.enqueue(request);//将id放进IntentIntent localIntent = new Intent(BROADCAST_ACTION);localIntent.putExtra(EXTENDED_DATA_STATUS,requestId);//查询下载信息DownloadManager.Query query=new DownloadManager.Query();query.setFilterById(requestId);try{boolean isGoging=true;while(isGoging){Cursor cursor = downloadManager.query(query);if (cursor != null && cursor.moveToFirst()) {int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));switch(status){//如果下载状态为成功 case DownloadManager.STATUS_SUCCESSFUL:isGoging=false;//调用LocalBroadcastManager.sendBroadcast将intent传递回去mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);mLocalBroadcastManager.sendBroadcast(localIntent);break;}}if(cursor!=null){cursor.close();}}}catch(Exception e){e.printStackTrace();}}}
Step 3:中注册,监听广播,更新UI 。
.java:
注册广播的方法(动态注册):
private void regist() {IntentFilter intentFilter = new IntentFilter(DownloadService.BROADCAST_ACTION);intentFilter.addCategory(Intent.CATEGORY_DEFAULT);LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);}
接受到广播,处理传递过来的数据,下载完成,自动安装应用: