【发布时间】:2017-12-26 12:25:59
【问题描述】:
class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
String url2 = "https://www.w3schools.com/w3css/img_fjords.jpg";
String url = url2.replaceAll(" ", "%20");
String fileName = URLUtil.guessFileName(url, null, MimeTypeMap.getFileExtensionFromUrl(url));
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(MimeTypeMap.getFileExtensionFromUrl(url));
String cookies = CookieManager.getInstance().getCookie(url);
//request.addRequestHeader("Cookie", cookies);
//request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading File");
//request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("test.png");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager downloadManager = (DownloadManager) module.getActivity().getSystemService(DOWNLOAD_SERVICE);
if (downloadManager != null) {
final long downloadID = downloadManager.enqueue(request);
System.out.println(downloadID);
}
Toast.makeText(module.getActivity(), "Downloading File", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
Log.d("Post Execute","Post Execute");
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(Void... values) {}
}
new LongOperation().execute("");
我正在使用上面的代码在我的 react 本机应用程序中使用本机 android 代码下载图像。当此方法执行时,下载状态会进入称为 STATUS_PAUSED -> PAUSED_WAITING_TO_RETRY 的状态,一段时间后它会失败并显示错误代码 ERROR_HTTP_DATA_ERROR。 我在我的 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"/>
我做错了什么?
【问题讨论】:
-
同时读取This thread。
-
谢谢,我会检查一下(Y)
-
是否需要在异步任务中运行这段代码?
-
即使没有它我也试过了。仍然没有运气。我添加它是因为,我尝试使用 HttpURLConnection 下载,当我在异步任务之外运行它时,它引发了异常
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork -
在主线程上使用 httpURL 连接会给你 NetworkOnMainThreadException 但向下载管理器发送请求以下载文件不会
标签: android react-native android-download-manager imagedownload