1. 程式人生 > >Android——實現網路下載資源

Android——實現網路下載資源

網路許可權:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
/>

MainActivity

downloadAPK(bean.getData().getApkUrl(),"APK");

private void downloadAPK(String versionUrl, String versionName) {
    //建立下載任務
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionUrl));
    request.setAllowedOverRoaming(false);//漫遊網路是否可以下載
//設定檔案型別,可以在下載結束後自動開啟該檔案
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(versionUrl)); request.setMimeType(mimeString); //在通知欄中顯示,預設就是顯示的 request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE); request.setVisibleInDownloadsUi
(true); //sdcard的目錄下的download資料夾,必須設定 request.setDestinationInExternalPublicDir("/download/", versionName); //request.setDestinationInExternalFilesDir(),也可以自己制定下載路徑 //將下載請求加入下載佇列 downloadManager = (DownloadManager) MainActivity.this.getSystemService(MainActivity.this.DOWNLOAD_SERVICE); //加入下載佇列後會給該任務返回一個long型的id//通過該id可以取消任務,重啟任務等等,看上面原始碼中框起來的方法 mTaskId = downloadManager.enqueue(request); //註冊廣播接收者,監聽下載狀態 MainActivity.this.registerReceiver(receiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { checkDownloadStatus();//檢查下載狀態 } }; private void checkDownloadStatus() { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(mTaskId);//篩選下載任務,傳入任務ID,可變引數 Cursor c = downloadManager.query(query); if (c.moveToFirst()) { int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)); switch (status) { case DownloadManager.STATUS_PAUSED: Log.i("zzz",">>>下載暫停"); case DownloadManager.STATUS_PENDING: Log.i("zzz",">>>下載延遲"); case DownloadManager.STATUS_RUNNING: Log.i("zzz",">>>正在下載"); break; case DownloadManager.STATUS_SUCCESSFUL: Log.i("zzz",">>>下載完成"); File file = Environment.getExternalStorageDirectory(); installAPK(new File(file+"/Download")); break; case DownloadManager.STATUS_FAILED: Log.i("zzz",">>>下載失敗"); break; } } } protected void installAPK(File file) { if (!file.exists()) return; Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri = Uri.parse("file://" + file.toString()); intent.setDataAndType(uri, "application/vnd.android.package-archive"); //在服務中開啟activity必須設定flag,後面解釋 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); MainActivity.this.startActivity(intent); }