alwaystest / Blog

24 stars 2 forks source link

Android External Storage 权限问题 #61

Open alwaystest opened 7 years ago

alwaystest commented 7 years ago

Android External Storage 权限问题

标签(空格分隔): Android


4.4以上读写External Storage下的Android/data/packageName/是不需要声明权限的。哪怕是使用new File("/storage/emulated/0/Android/data/packageName", "fileName")也没有问题。需要注意的是这个文件夹是在调用getExternalFilesDir()的时候创建的,如果直接使用File去访问的话是没有这个文件夹的。自己手动建目录也是可以的。卸载这个软件的时候,整个Android/data/packageName/都会被删掉。看官方文档有歧义。

When the user uninstalls your app, the system removes your app's files from here only if you save them in the directory from getExternalFilesDir().

4.4以下懒得看了,看别的blog说是读不需要权限,写需要声明权限。偷懒的做法是保险一些把权限都声明好。

If none of the pre-defined sub-directory names suit your files, you can instead call getExternalFilesDir() and pass null. This returns the root directory for your app's private directory on the external storage.

这里我以为返回的是Android/data/packageName/但是实际上返回的是Android/data/packageName/files。不知道是歧义还是我英文没学到家。


Caution: Currently, all apps have the ability to read the external storage without a special permission. However, this will change in a future release. If your app needs to read the external storage (but not write to it), then you will need to declare the READ_EXTERNAL_STORAGE permission. To ensure that your app continues to work as expected, you should declare this permission now, before the change takes effect.

然后我天真的信了官方文档,然而在6.0以上,不声明权限,没有给Storage权限,是读不出来的。所以External Storage中除了Android/data/packageName下的文件,其他地方不论读写,都应该声明权限,如果是6.0以上,还要考虑动态获取权限的问题。


关于cache文件夹

internal storage的cache文件夹,系统在存储空间不足的时候会默默的尝试清理这里的文件。官方建议最好自己把不用的缓存清理掉,保持这个文件夹比较小的一个状态,因为依赖系统来清理的话,被清理掉的文件就不可预测了。

external storage的cache文件夹就不一样了,官方建议自己维护一个最大值,自己去清理。The platform does not always monitor the space available in shared storage, and thus may not automatically delete these files.所以系统有时也会来清理一下,但是不可依赖。

Currently the only time files here will be deleted by the platform is when running on JELLY_BEAN_MR1 or later and isExternalStorageEmulated(File) returns true.


Storage参考