如何从 Android API 24+ 将文件写入 SD 卡

How to write files on SD Card from Android API 24+

我有一个大问题。我想通过我的应用程序将从互联网上下载的一些文件保存到我的 SD 卡中,路径如下:

/storage/9016-4EF8/Android/data/com.my.application/files

但我不想在我的代码中硬编码这个字符串。那么我该如何以编程方式进行呢? 我已经请求允许在外部存储上写入。

目前在我的代码中有下面这段代码:

File sdcard = new File(context.getExternalFilesDir(null).getAbsolutePath() + "/Video scaricati/");

但是有了它,我的应用程序将文件保存在里面:

/storage/emulated/0/Android/data/com.my.application/files/Video scaricati

它不在我的 SD 卡中。

我该怎么做?

试试这样改成 Environment.getExternalStorageDirectory()

new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video scaricati/");

返回的第二项
File dirs[] =getExternalFilesDirs();

使用前检查数组是否包含一个以上的元素。不是每个人都把 micro SD 卡放进去。