6.0以前感觉只要在manifest中申明了权限就可以用数据库、硬盘缓存、sp这些来做数据缓存。但是6.0后需要动态申请权限, 并且用户可以随时关掉这些权限。 那么在用户关掉或者没有允许sd卡读取权限的情况下,还能做数据缓存么(没有开启权限的话,file总是会创建失败)? 如果能的话,那该怎么做呢?
高洛峰2017-04-17 18:00:29
Brother, you got it wrong.
You can check out the official documentation.
Android storage space is divided into two parts: Internal storage
和External storage
Always available, no additional permissions required, files here can only be accessed by our app by default.
You can get the internal cache directory through getFilesDir()
方法获取到App的internal目录,通过getCacheDir()
under Context.
This space may not always be available due to mounting external storage. However, more and more manufacturers no longer allow users to use SD cards to expand capacity, and instead fix the storage space of the device. These storage spaces will still be divided into Internal storage and External storage, but in this case External storage is basically is always available, you can also use
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
To determine whether External storage is mounted.
You can get the external cache directory through getExternalFilesDir()
方法获取到App的external目录,通过getExternalCacheDir()
under Context.
These two directories are located in 外置储存空间目录/Android/data/你的App的包名/
下,你往这里面读写是不需要额外权限的(API 18以上),如果你的App的minSdkVersion
<= 18,建议你在AndroidManifest.xml
and add this permission:
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"/>
However, if you read and write files outside this directory, you need runtime permissions (for example, if you want to write a log file or something in the root directory of External storage)
Many apps or third-party SDKs will read and write cache to the root directory of External storage, which will drive you to obsessive-compulsive disorder every minute. Looking at all kinds of strange directories in the root directory of your phone’s external SD card, it will really crash, okay? However, I believe that as the share of Android devices with version 6.0 and above continues to increase, this problem will gradually be solved.
I hope that all Android application development colleagues will use the getExternalFilesDir()
和getExternalCacheDir()
method as much as possible to give users a clean and tidy External storage.