- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的应用程序中,我需要在设备存储中存储大量图像。此类文件往往用于设备存储,我希望允许用户能够选择外部 SD 卡作为目标文件夹。
我到处都读到 Android 不允许用户写入外部 SD 卡,SD 卡是指外部和可安装的 SD 卡和 不是外部存储 ,但文件管理器应用程序设法在所有 Android 版本上写入外部 SD .
在不同的 API 级别(Pre-KitKat、KitKat、Lollipop+)授予对外部 SD 卡的读/写访问权限的更好方法是什么?
更新 1
我尝试了 Doomknight 答案中的方法 1,但无济于事:
如您所见,在尝试写入 SD 之前,我正在运行时检查权限:
HashSet<String> extDirs = getStorageDirectories();
for(String dir: extDirs) {
Log.e("SD",dir);
File f = new File(new File(dir),"TEST.TXT");
try {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)==PackageManager.PERMISSION_GRANTED) {
f.createNewFile();
}
} catch (IOException e) {
e.printStackTrace();
}
}
10-22 14:52:57.329 30280-30280/? E/SD: /mnt/media_rw/F38E-14F8
10-22 14:52:57.329 30280-30280/? W/System.err: java.io.IOException: open failed: EACCES (Permission denied)
10-22 14:52:57.329 30280-30280/? W/System.err: at java.io.File.createNewFile(File.java:939)
10-22 14:52:57.329 30280-30280/? W/System.err: at com.myapp.activities.TestActivity.onResume(TestActivity.java:167)
10-22 14:52:57.329 30280-30280/? W/System.err: at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1326)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.Activity.performResume(Activity.java:6338)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3336)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3384)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2574)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread.access$900(ActivityThread.java:150)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.os.Looper.loop(Looper.java:168)
10-22 14:52:57.330 30280-30280/? W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5885)
10-22 14:52:57.330 30280-30280/? W/System.err: at java.lang.reflect.Method.invoke(Native Method)
10-22 14:52:57.330 30280-30280/? W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:819)
10-22 14:52:57.330 30280-30280/? W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:709)
10-22 14:52:57.330 30280-30280/? W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
10-22 14:52:57.330 30280-30280/? W/System.err: at libcore.io.Posix.open(Native Method)
10-22 14:52:57.330 30280-30280/? W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
10-22 14:52:57.330 30280-30280/? W/System.err: at java.io.File.createNewFile(File.java:932)
10-22 14:52:57.330 30280-30280/? W/System.err: ... 14 more
最佳答案
摘要
您可以将 grant read/write access 连接到 different api levels ( API23+ at run time ) 上的外部 SD 卡。
如果您使用特定于应用程序的目录,则 Since KitKat, 权限为 not necessary,否则为 required。
通用方式:
history 表示没有通用的方法可以写入外部 SD 卡 but continues...
This fact 由 these examples of external storage configurations for devices 证明。
基于 API 的方式:
在 KitKat 之前尝试使用 Doomsknight method 1, method 2 otherwise.
请求权限 in manifest (Api < 23) 和 at run time (Api >= 23)。
推荐方式:
当您不需要共享文件时,ContextCompat.getExternalFilesDirs 解决了 the access error。
共享它的安全方式是使用 content provider 或 new Storage Access Framework 。
隐私感知方式:
As of Android Q Beta 4 ,默认情况下,面向 Android 9(API 级别 28)或更低版本的应用没有看到任何变化。
默认情况下(或选择加入)以 Android Q 为目标的应用程序会在外部存储中分配 filtered view。
Universal way to write to external SD card on Android
What is the better way to grant read/write access to external SD cardon different API levels
/storage/extSdCard/Android/data/com.myapp.example/files
。 Update 1. I tried Method 1 from Doomknight's answer, with no avail:
As you can see I'm checking for permissions at runtime beforeattempting to write on SD...
ContextCompat.getExternalFilesDirs()
。
android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT
等不同 api 级别确定代表可移动媒体的内容
... But I get an access error, tried on two different devices: HTC10and Shield K1.
/mnt/media_rw
,例如 API 19+ 的
this fix :
<permission name="android.permission.WRITE_EXTERNAL_STORAGE" >
<group gid="sdcard_r" />
<group gid="sdcard_rw" />
<group gid="media_rw" /> // this line is added via root in the link to fix it.
</permission>
我从未尝试过,所以我无法共享代码,但我会避免
for
尝试在所有返回的目录上写入并查找
the best available storage directory to write into based on remaining space 。
getStorageDirectories()
方法,这是一个很好的起点。
ContextCompat.getExternalFilesDirs
可以解决
access to other folders 。
public static HashSet<String> getExternalMounts() {
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}
将下一个代码添加到您的
AndroidManifest.xml
并读取
Getting access to external storage
Access to external storage is protected by various Androidpermissions.
Starting in Android 1.0, write access is protected withthe
WRITE_EXTERNAL_STORAGE
permission.Starting in Android 4.1, readaccess is protected with the
READ_EXTERNAL_STORAGE
permission.In order to ... write files on the external storage, your app mustacquire ... systempermissions:
<manifest ...>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>If you need to both..., you need to requestonly the
WRITE_EXTERNAL_STORAGE
permission.
- Until Android 4.4, there was no official support for removable media in Android, Starting in KitKat, the concept of “primary” and “secondary” external storage emerges in the FMW API.
- Prior apps are just relying on MediaStore indexing, ship with the hardware or examine mount points and apply some heuristics to determine what represents removable media.
ContextCompat.getExternalFilesDirs()
:
- Since Android 4.2, there has been a request from Google for device manufacturers to lock down removable media for security (multi-user support) and new tests were added in 4.4.
- Since KitKat
getExternalFilesDirs()
and other methods were added to return a usable path on all available storage volumes (The firstitem returned is the primary volume).
Note: Beginning with Android 4.4, these permissions are not requiredif you're reading or writing only files that are private to your app.For more info..., see saving files thatare app-private.
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
</manifest>
In KitKat there's now a public API for interacting withthese secondary shared storage devices.
The new
Context.getExternalFilesDirs()
andContext.getExternalCacheDirs()
methods can return multiple paths,including both primary and secondary devices.You can then iterateover them and check
Environment.getStorageState()
andFile.getFreeSpace()
to determine the best place to store your files.These methods are also available on
ContextCompat
in the support-v4 library.
Starting in Android 4.4, the owner, group and modes of files onexternal storage devices are now synthesized based on directorystructure. This enables apps to manage their package-specificdirectories on external storage without requiring they hold the broad
WRITE_EXTERNAL_STORAGE
permission. For example, the app with packagenamecom.example.foo
can now freely accessAndroid/data/com.example.foo/
on external storage devices with nopermissions. These synthesized permissions are accomplished bywrapping raw storage devices in a FUSE daemon.
The Android project has definitely screwed up here.No apps get full access to external SD cards:
- file managers: you cannot use them to manage your external SD card. Inmost areas, they can only read but not write.
- media apps: you cannotretag/re-organize your media collection any longer, as those appscannot write to it.
- office apps: pretty much the same
The only place 3rd party apps are allowed to write on yourexternal card are "their own directories" (i.e.
/sdcard/Android/data/<package_name_of_the_app>
).The only ways toreally fix that require either the manufacturer (some of them fixedit, e.g. Huawei with their Kitkat update for the P6) – or root... (Izzy's explanation continues here)
getStorageState
在 API 19 中添加,在 API 21 中弃用,
getExternalStorageState(File)
Here's a great tutorial for interacting with the Storage AccessFramework in KitKat.
Interacting with the new APIs in Lollipop is very similar (Jeff Sharkey's explanation).
Beginning in Android 6.0 (API level 23), users grant permissions toapps while the app is running, not when they install the app ... or update the app ... user can revoke the permissions.
// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
Android 6.0 introduces a new runtime permissions model where appsrequest capabilities when needed at runtime. Because the new modelincludes the
READ/WRITE_EXTERNAL_STORAGE
permissions, the platformneeds to dynamically grant storage access without killing orrestarting already-running apps. It does this by maintaining threedistinct views of all mounted storage devices:
- /mnt/runtime/default is shown to apps with no special storagepermissions...
- /mnt/runtime/read is shown to apps withREAD_EXTERNAL_STORAGE
- /mnt/runtime/write is shown to apps withWRITE_EXTERNAL_STORAGE
Scoped Directory AccessIn Android 7.0, apps can use new APIs to request access to specificexternal storage directories, including directories on removable mediasuch as SD cards...
For more information, see the Scoped Directory Access training.
Note that the scoped directory access added in 7.0 is deprecated inAndroid Q.
Specifically, the
createAccessIntent()
method on StorageVolume isdeprecated.They added a
createOpenDocumentTreeIntent()
that can be used as analternative.
Starting in AndroidO, theStorage Access Framework allows custom documentsprovidersto create seekable file descriptors for files residing in a remotedata source...
Permissions,prior to Android O, if an app requested a permission at runtime and the permission was granted, the system also incorrectly grantedthe app the rest of the permissions that belonged to the samepermission group, and that were registered in the manifest.
For apps targeting Android O, this behavior has been corrected. The app is granted only the permissions it has explicitly requested.However, once the user grants a permission to the app, all subsequentrequests for permissions in that permission group are automaticallygranted.
For example,
READ_EXTERNAL_STORAGE
andWRITE_EXTERNAL_STORAGE
...
READ_EXTERNAL_STORAGE
和
WRITE_EXTERNAL_STORAGE
权限。
READ_MEDIA_IMAGES
、
READ_MEDIA_AUDIO
和
READ_MEDIA_VIDEO
-
are now obsolete 。
更多信息:
"Death is more universal than life. Everyone dies, but not everyonelives." ― Andrew Sachs
关于java - 在 Android 上写入外部 SD 卡的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068984/
我最近在/ drawable中添加了一些.gifs,以便可以将它们与按钮一起使用。这个工作正常(没有错误)。现在,当我重建/运行我的应用程序时,出现以下错误: Error: Gradle: Execu
Android 中有返回内部存储数据路径的方法吗? 我有 2 部 Android 智能手机(Samsung s2 和 s7 edge),我在其中安装了一个应用程序。我想使用位于这条路径中的 sqlit
这个问题在这里已经有了答案: What's the difference between "?android:" and "@android:" in an android layout xml f
我只想知道 android 开发手机、android 普通手机和 android root 手机之间的实际区别。 我们不能从实体店或除 android marketplace 以外的其他地方购买开发手
自Gradle更新以来,我正在努力使这个项目达到标准。这是一个团队项目,它使用的是android-apt插件。我已经进行了必要的语法更改(编译->实现和apt->注释处理器),但是编译器仍在告诉我存在
我是android和kotlin的新手,所以请原谅要解决的一个非常简单的问题! 我已经使用导航体系结构组件创建了一个基本应用程序,使用了底部的导航栏和三个导航选项。每个导航选项都指向一个专用片段,该片
我目前正在使用 Facebook official SDK for Android . 我现在正在使用高级示例应用程序,但我不知道如何让它获取应用程序墙/流/状态而不是登录的用户。 这可能吗?在那种情
我在下载文件时遇到问题, 我可以在模拟器中下载文件,但无法在手机上使用。我已经定义了上网和写入 SD 卡的权限。 我在服务器上有一个 doc 文件,如果用户单击下载。它下载文件。这在模拟器中工作正常但
这个问题在这里已经有了答案: What is the difference between gravity and layout_gravity in Android? (22 个答案) 关闭 9
任何人都可以告诉我什么是 android 缓存和应用程序缓存,因为当我们谈论缓存清理应用程序时,它的作用是,缓存清理概念是清理应用程序缓存还是像内存管理一样主存储、RAM、缓存是不同的并且据我所知,缓
假设应用程序 Foo 和 Eggs 在同一台 Android 设备上。任一应用程序都可以获取设备上所有应用程序的列表。一个应用程序是否有可能知道另一个应用程序是否已经运行以及运行了多长时间? 最佳答案
我有点困惑,我只看到了从 android 到 pc 或者从 android 到 pc 的例子。我需要制作一个从两部手机 (android) 连接的 android 应用程序进行视频聊天。我在想,我知道
用于使用 Android 以编程方式锁定屏幕。我从 Stackoverflow 之前关于此的问题中得到了一些好主意,并且我做得很好,但是当我运行该代码时,没有异常和错误。而且,屏幕没有锁定。请在这段代
文档说: android:layout_alignParentStart If true, makes the start edge of this view match the start edge
我不知道这两个属性和高度之间的区别。 以一个TextView为例,如果我将它的layout_width设置为wrap_content,并将它的width设置为50 dip,会发生什么情况? 最佳答案
这两个属性有什么关系?如果我有 android:noHistory="true",那么有 android:finishOnTaskLaunch="true" 有什么意义吗? 最佳答案 假设您的应用中有
我是新手,正在尝试理解以下 XML 代码: 查看 developer.android.com 上的文档,它说“starStyle”是 R.attr 中的常量, public static final
在下面的代码中,为什么当我设置时单选按钮的外观会发生变化 android:layout_width="fill_parent" 和 android:width="fill_parent" 我说的是
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 9
假设我有一个函数 fun myFunction(name:String, email:String){},当我调用这个函数时 myFunction('Ali', 'ali@test.com ') 如何
我是一名优秀的程序员,十分优秀!