使用Android系统提供的DownloadManager来下载文件
在android2.3以后android系统提供了一个系统组件来供其他app调用来下载东西,使用起来非常方便。
例如我们可以拿来下载app的新版本apk,同时在同时注册一个广播接收器来接收下载完成时DownloadManager发出的的广播,然后自动安装程序。
SDK在APILevel9中加入了DownloadManager服务,可以将长时间的下载任务交给系统,完全由系统管理。
直接看实例代码:
packagecom.hebaijun.downloadtest; importjava.io.UnsupportedEncodingException; importjava.net.URLEncoder; importandroid.app.Activity; importandroid.app.DownloadManager; importandroid.app.DownloadManager.Request; importandroid.content.BroadcastReceiver; importandroid.content.Context; importandroid.content.Intent; importandroid.content.IntentFilter; importandroid.content.SharedPreferences; importandroid.database.Cursor; importandroid.net.Uri; importandroid.os.Bundle; importandroid.preference.PreferenceManager; importandroid.util.Log; importandroid.webkit.MimeTypeMap; publicclassDownloadTestActivityextendsActivity{ privateDownloadManagerdownloadManager; privateSharedPreferencesprefs; privatestaticfinalStringDL_ID="downloadId"; /**Calledwhentheactivityisfirstcreated.*/ @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); downloadManager=(DownloadManager)getSystemService(DOWNLOAD_SERVICE); prefs=PreferenceManager.getDefaultSharedPreferences(this); } @Override protectedvoidonPause(){ //TODOAuto-generatedmethodstub super.onPause(); unregisterReceiver(receiver); } @Override protectedvoidonResume(){ //TODOAuto-generatedmethodstub super.onResume(); if(!prefs.contains(DL_ID)){ Stringurl="http://10.0.2.2/android/film/G3.mp4"; //开始下载 Uriresource=Uri.parse(encodeGB(url)); DownloadManager.Requestrequest=newDownloadManager.Request(resource); request.setAllowedNetworkTypes(Request.NETWORK_MOBILE|Request.NETWORK_WIFI); request.setAllowedOverRoaming(false); //设置文件类型 MimeTypeMapmimeTypeMap=MimeTypeMap.getSingleton(); StringmimeString=mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url)); request.setMimeType(mimeString); //在通知栏中显示 request.setShowRunningNotification(true); request.setVisibleInDownloadsUi(true); //sdcard的目录下的download文件夹 request.setDestinationInExternalPublicDir("/download/","G3.mp4"); request.setTitle("移动G3广告"); longid=downloadManager.enqueue(request); //保存id prefs.edit().putLong(DL_ID,id).commit(); }else{ //下载已经开始,检查状态 queryDownloadStatus(); } registerReceiver(receiver,newIntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); } /** *如果服务器不支持中文路径的情况下需要转换url的编码。 *@paramstring *@return */ publicStringencodeGB(Stringstring) { //转换中文编码 Stringsplit[]=string.split("/"); for(inti=1;i<split.length;i++){ try{ split[i]=URLEncoder.encode(split[i],"GB2312"); }catch(UnsupportedEncodingExceptione){ e.printStackTrace(); } split[0]=split[0]+"/"+split[i]; } split[0]=split[0].replaceAll("\\+","%20");//处理空格 returnsplit[0]; } privateBroadcastReceiverreceiver=newBroadcastReceiver(){ @Override publicvoidonReceive(Contextcontext,Intentintent){ //这里可以取得下载的id,这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听 Log.v("intent",""+intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,0)); queryDownloadStatus(); } }; privatevoidqueryDownloadStatus(){ DownloadManager.Queryquery=newDownloadManager.Query(); query.setFilterById(prefs.getLong(DL_ID,0)); Cursorc=downloadManager.query(query); if(c.moveToFirst()){ intstatus=c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); switch(status){ caseDownloadManager.STATUS_PAUSED: Log.v("down","STATUS_PAUSED"); caseDownloadManager.STATUS_PENDING: Log.v("down","STATUS_PENDING"); caseDownloadManager.STATUS_RUNNING: //正在下载,不做任何事情 Log.v("down","STATUS_RUNNING"); break; caseDownloadManager.STATUS_SUCCESSFUL: //完成 Log.v("down","下载完成"); break; caseDownloadManager.STATUS_FAILED: //清除已下载的内容,重新下载 Log.v("down","STATUS_FAILED"); downloadManager.remove(prefs.getLong(DL_ID,0)); prefs.edit().clear().commit(); break; } } } }
最后需要的权限是:
<uses-permissionandroid:name="android.permission.INTERNET"/> <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
如果需要隐藏下载工具的提示和显示,修改代码:
request.setShowRunningNotification(false); request.setVisibleInDownloadsUi(false);
加入下面的权限:
<uses-permissionandroid:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。