在網上找了很多資料,但是都存在一定的bug,問題解決后,特寫出問題解決方案,
1.使用安卓自帶的downloadmanage下載,(推薦,下載后的檔案可在手機最近的目錄查看)
final DownloadManager dManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(UrlUtils.BASE_URL+"/media/"+list_show.get(position).get("file_path")+"/"+list_show.get(position).get("file_show"));
DownloadManager.Request request = new DownloadManager.Request(uri);
// 設定下載路徑和檔案名 request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, list_show.get(position).get("file_show").toString());
request.setDescription(list_show.get(position).get("file_show")+"下載中"); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//apk的type型別,下載apk時可以打開
//request.setMimeType("application/vnd.android.package-archive");
// 設定為可被媒體掃描器找到
request.allowScanningByMediaScanner();
// 設定為可見和可管理
request.setVisibleInDownloadsUi(true);
// 獲取此次下載的ID
final long refernece = dManager.enqueue(request);
效果圖:

2.使用okhttp下載檔案,(暫未解決問題:在手機上找不到檔案位置,歡迎大佬給出解決方案)
因為之前的后端局限性,我發的是post請求的下載檔案方式,
代碼改了后,效果圖沒截,
progressDialog = new ProgressDialog(FileActivity.this);
canReturn=false;
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("正在下載");
progressDialog.setMessage("請稍后...");
progressDialog.setProgress(0);
progressDialog.setMax(100);
progressDialog.setCancelable(false);
progressDialog.show();
MyApplication myApplication= (MyApplication) getApplication().getApplicationContext();
String accessKey = AccessKeyUtils.getAccessKey(myApplication.getMenuApplication(), 54);
String json="{\"businessJson\":{\"file_type\": \""+list_show.get(position).get("file_type")+"\",\"file_path\": \""+list_show.get(position).get("file_path")+"\",\"file_name\": \""+list_show.get(position).get("file_name")+"\"},\"controlJson\":{\"menuId\":54,\"opt\":\"c\",\"accessKey\":\""+accessKey+"\",\"token\":\""+myApplication.getToken()+"\",\"opt_desc\":\"下載檔案\"}}";
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(UrlUtils.BASE_URL+"/app/hsdj/xxjymgr/views/downloadFile")
.post(body)
.build();
OkHttpClient client = new OkHttpClient();
okhttp3.Call task=client.newCall(request);
task.enqueue(new Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
Looper.prepare();
progressDialog.dismiss();
Toast.makeText(myApplication, "檔案獲取失敗!", Toast.LENGTH_SHORT).show();
Looper.loop();
}
@Override
public void onResponse(okhttp3.Call call, Response response) throws IOException {
Looper.prepare();
final long startTime = System.currentTimeMillis();
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
// 儲存下載檔案的目錄
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// java.io.File directory = cw.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
java.io.File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
is = response.body().byteStream();
long total = response.body().contentLength();
java.io.File file = new java.io.File(directory,list_show.get(position).get("file_show").toString());
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
progress = (int) (sum * 1.0f / total * 100);
progressDialog.setProgress(progress);
}
fos.flush();
// 下載完成
// listener.onDownloadSuccess();
Log.i("DOWNLOAD","download success");
Log.i("DOWNLOAD","totalTime="+ (System.currentTimeMillis() - startTime));
} catch (Exception e) {
e.printStackTrace();
// listener.onDownloadFailed();
Log.i("DOWNLOAD","download failed");
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
progressDialog.dismiss();
Toast.makeText(myApplication, "檔案下載成功!", Toast.LENGTH_SHORT).show();
Looper.loop();
}
});
參考:(如果是apk的更新建議參考以下)
使用Android系統提供的DownloadManager來下載檔案, - 黑暗中的一盞明燈 - 博客園 (cnblogs.com)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/289890.html
標籤:其他
