我正在使用DownloadManager制作android应用。我想将文件下载到我制作的文件夹中。但这来源不起作用。并发生IllegalstateException。我该怎么办?
urlToDownload = Uri.parse(URL);
List<String> pathSegments = urlToDownload.getPathSegments();
request = new DownloadManager.Request(urlToDownload);
request.setTitle(Titlename);
request.setDescription("MCPE STORE");
request.setDestinationInExternalPublicDir(
Environment.getExternalStorageDirectory().getAbsolutePath() +
"/MCPE STORE", pathSegments.get(pathSegments.size()-1));
Environment.getExternalStoragePublicDirectory(
Environment.getExternalStorageDirectory().getAbsolutePath() +
"/MCPE STORE").mkdir();
latestId = downloadManager.enqueue(request);
我该怎么办?
如果您阅读the documentation for setDestinationInExternalPublicDir()
,您将看到第一个参数是“目录类型setDestinationInExternalPublicDir()
”。它必须是在to pass to getExternalStoragePublicDirectory(String)
类上定义的常量之一,例如getExternalStoragePublicDirectory(String)
。您正在传递不支持的其他内容。
请确保您有
Environment
在您的Environment.DIRECTORY_DOWNLOADS
中
此外,如果您使用的是仿真器,请确保使用SD卡存储设备创建了它。默认情况下未创建。
作为我们面临的问题,并且根据文档,我得出的结论是,从API级别29开始,它们不允许我们直接创建任何非标准目录(用户定义),但我找到了解决该问题的一种可行方法。
这是我的清单文件
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
这里是我的build.gradle文件,仅用于确保您正在使用目标sdk 29
manifest.xml
这是MainActivity.kt
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>