我正在尝试将下载的文件写入存储空间但我收到并出错。这是我的代码 -
request.setDestinationInExternalPublicDir("/songs", "name-of-the-file.mp3");
记录 -
03-25 12:40:47.230 10480-10480/com.xxxx.ytm.yyyy E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xxxx.ytm.yyyy, PID: 10480
java.lang.IllegalStateException: Unable to create directory: /storage/emulated/0/songs
at android.app.DownloadManager$Request.setDestinationInExternalPublicDir(DownloadManager.java:538)
at com.antimatter.ytm.youtubemp3.MainActivity$1.onClick(MainActivity.java:84)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
如需记录,请参阅其余代码 -
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// To work and download on main thread
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downl));
request.setDestinationInExternalPublicDir("/songs", "name-of-the-file.mp3");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
我已添加以下权限 -
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
答案 0 :(得分:1)
如果您没有写入SD卡的权限,SD卡不存在或者您没有访问正确的卡,则最有可能发生这种情况。 首先确保你有一张SD卡。 其次,存储路径因制造商而异,所以不要硬编码。尝试以下方法来创建目录
String pathTofile = Environment.getExternalStorageDirectory()。getAbsolutePath(); String fullpath = pathTofile +“您定义的目录路径”
上面的应该有用。
如果没有,请尝试以下链接
`/storage/emulated/legacy/` vs `/storage/emulated/0/` vs `data/data/myApp'