使用Android自帶DownloadManager下載檔案
阿新 • • 發佈:2018-12-23
package com.hebaijun.downloadtest; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import android.app.Activity; import android.app.DownloadManager; import android.app.DownloadManager.Request; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.webkit.MimeTypeMap; public class DownloadTestActivity extends Activity { private DownloadManager downloadManager; private SharedPreferences prefs; private static final String DL_ID = "downloadId"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE); prefs = PreferenceManager.getDefaultSharedPreferences(this); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); unregisterReceiver(receiver); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); if(!prefs.contains(DL_ID)) { String url = "http://10.0.2.2/android/film/G3.mp4"; //開始下載 Uri resource = Uri.parse(encodeGB(url)); DownloadManager.Request request = new DownloadManager.Request(resource); request.setAllowedNetworkTypes(Request.NETWORK_MOBILE | Request.NETWORK_WIFI); request.setAllowedOverRoaming(false); //設定檔案型別 MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url)); request.setMimeType(mimeString); //在通知欄中顯示 request.setShowRunningNotification(true); request.setVisibleInDownloadsUi(true); //sdcard的目錄下的download資料夾 request.setDestinationInExternalPublicDir("/download/", "G3.mp4"); request.setTitle("移動G3廣告"); long id = downloadManager.enqueue(request); //儲存id prefs.edit().putLong(DL_ID, id).commit(); } else { //下載已經開始,檢查狀態 queryDownloadStatus(); } registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); } /** * 如果伺服器不支援中文路徑的情況下需要轉換url的編碼。 * @param string * @return */ public String encodeGB(String string) { //轉換中文編碼 String split[] = string.split("/"); for (int i = 1; i < split.length; i++) { try { split[i] = URLEncoder.encode(split[i], "GB2312"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } split[0] = split[0]+"/"+split[i]; } split[0] = split[0].replaceAll("\\+", "%20");//處理空格 return split[0]; } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //這裡可以取得下載的id,這樣就可以知道哪個檔案下載完成了。適用與多個下載任務的監聽 Log.v("intent", ""+intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0)); queryDownloadStatus(); } }; private void queryDownloadStatus() { DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(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.v("down", "STATUS_PAUSED"); case DownloadManager.STATUS_PENDING: Log.v("down", "STATUS_PENDING"); case DownloadManager.STATUS_RUNNING: //正在下載,不做任何事情 Log.v("down", "STATUS_RUNNING"); break; case DownloadManager.STATUS_SUCCESSFUL: //完成 Log.v("down", "下載完成"); break; case DownloadManager.STATUS_FAILED: //清除已下載的內容,重新下載 Log.v("down", "STATUS_FAILED"); downloadManager.remove(prefs.getLong(DL_ID, 0)); prefs.edit().clear().commit(); break; } } } }
最後需要的許可權是: <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 如果需要隱藏下載工具的提示和顯示,修改程式碼: request.setShowRunningNotification(false); request.setVisibleInDownloadsUi(false); 加入下面的許可權: <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>