gpt4 book ai didi

java - setDestinationInExternalFilesDir() 有效 setDestinationInExternalPublicDir() 无效

转载 作者:行者123 更新时间:2023-12-02 12:09:40 25 4
gpt4 key购买 nike

我正在尝试从 url 下载文件并将其保存到常规下载文件夹。 setDestinationInExternalPublicDir() 不起作用,也不会引发任何异常。但是 setDestinationInExternalFilesDir() 工作正常。知道原因是什么吗?

我的代码是这样的:

webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimeType,
long contentLength) {

if (url.startsWith("data:")) {
save(url);
return;
}


DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription(getResources().getString(R.string.downloadingMsg));
String filename = URLUtil.guessFileName(url, contentDisposition, mimeType);
request.setTitle(filename);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//DOESN'T WORK
request.setDestinationInExternalPublicDir("Downloads", filename);
//WORKS
//request.setDestinationInExternalFilesDir(getApplicationContext(), "Downloads", filename);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), R.string.downloadingMsg, Toast.LENGTH_LONG).show();
}
});

和 list 文件:

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

最佳答案

所以,我终于可以让 setDestinationInExternalPublicDir() 函数工作了。感谢 CommonsWare。通过关注 Commonsware 的评论和回答 here我了解到,在 Android 版本 6+ 上,即使 list 文件中声明了权限,仍然应该在运行时请求它们。你猜怎么着,我正在使用 android 7...也就是说,我收到了权限被拒绝错误。

因此,我在 onCreate() 函数中添加了这些行,该函数也会提示用户获得运行时的权限(最终解决了我的问题):

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
int PERMISSION_REQUEST_CODE = 1;
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {

if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_CODE);
}
}
}

关于java - setDestinationInExternalFilesDir() 有效 setDestinationInExternalPublicDir() 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46629476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com