Android fragmentation has been a problem for a long time, so let’s take a look at the fragmentation of file storage. How do you choose and manage file storage correctly?

Why manage files?

Android phones have been criticized for more and more use, less storage space, often have to rely on a variety of cleaning apps to clean up the garbage, in the end, the phone can not be double cleaning, the reason in addition to hardware aging and Android underlying implementation problems, Developers’ neglect of file management creates a lot of “garbage” that can’t be cleaned up.

The openness of Android gives developers great freedom, but freedom is not an excuse for abuse of authority and arbitrary development. Every developer should pay attention to details. Even the third-party push that was once chaotic has started to be unified and standardized. Improving your Android phone experience?

Android flash

As we all know, Android phone storage is divided into two parts: internal storage and external storage, internal storage is generally the phone’s own storage space, external storage refers to the storage space provided by an external SD card; With the development of mobile phones, the definition of these two storage has changed a bit. New phones no longer have the concept of an external SD card, but instead use internal flash memory (eMMC, UFS, etc.), so internal storage and external storage on new Android phones are already on the same hardware. But for compatibility with older devices and a better user experience, we still need to manage the use of both internal and external storage on the phone.

Apis about where files are stored

If you’ve ever done file management, you’ve probably been confused by android’s numerous file apis, so let’s take a look.

I’ve divided the file locations for application actions into three parts:

  1. The application stores private file directories internally
  2. Apply external storage to private file directories
  3. The public directory

We have two apis to get the location of these three parts, which belong to Context and Environment respectively.

Context

Context is the application Context, which is used to obtain the file directory related to the application. You can obtain the application private directory and the application public directory.

1. Context#getCacheDir()                    /data/user/0/cn.appname.xxx/cache
2. Context#getDir("spanner",MODE_PRIVATE)   /data/user/0/cn.appname.xxx/app_spanner
3. Context#getFileDir()                     /data/user/0/cn.appname.xxx/files
3. Context#getExternalCacheDir()            /storage/emulated/0/Android/data/cn.appname.xxx/cache
4. Context#getExternalFilesDir(Environment.DIRECTORY_PICTURES)  /storage/emulated/0/Android/data/cn.appname.xxx/files/Pictures
   Context#getExternalFilesDir(null)        /storage/emulated/0/Android/data/cn.appname.xxx/files
5. Context#getExternalMediaDirs()           /storage/emulated/0/Android/media/cn.appname.xxx
Copy the code

The first two are private directories for internal application storage, and the last four are private file directories for external application storage. Note: /data/user/0/ is equivalent to /data/data/

Environment

The Environment is independent of the application. It is used to obtain the file directory of the public storage location.

1. Environment#getExternalStorageDirectory()                /storage/emulated/0
2. Environment#getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)        /storage/emulated/0/DCIM
   Environment#getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)    /storage/emulated/0/Pictures
3. Environment#getDataDirectory()                           /data
4. Environment#getDownloadCacheDirectory()                  /data/cache
5. Environment#getRootDirectory()                           /system
Copy the code

The selection of the API

What API do you use when?

Apply private file directories

Application private directories are controlled by Context and can be divided into internal storage and external storage. Internal storage can be used without file read and write permission. External storage requires permissions (getetExternalCacheDir() and getExternalFilesDir() have not required read and write permissions since 4.4). All file directories in the external storage and internal storage can be cleared when users clean or uninstall the app.

Internal storage

Internal storage folders cannot be directly accessed by other applications or users and can be used to store sensitive data.

  • getCacheDir()

    • Designed to store cached data.
    • When users clear the app cache, the data in the cache directory will be cleared. When the mobile phone space is insufficient, the system will also clear the data in the cache directory. However, developers still need to manage cached data, especially internal caches, to avoid large caches.
  • getFileDir()

    • Can be used to store private persistent files.
    • It is very suitable for storing all kinds of file data required by app during app operation cycle. It will not be cleaned due to insufficient storage space of mobile phone, nor will it leave data garbage due to app uninstallation, and it is private.
  • getDir(String name,int mode)

    • Category stores private files.
    • A folder named app_name will be created in the internal private directory. Mode used to be able to set the folder private (MODE_PRIVATE) and public (MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE). However, the current public mode is deprecated, which means that the folder created by this API is completely private and cannot be shared.

External storage

Prior to Android Q, other applications could access the application private directory that modifies external storage. This should be noted.

Make sure that external storage is available before you use it, because old devices don’t necessarily have external storage, new phones don’t necessarily give you read and write permissions, and even if users don’t give you access, your app still needs to run, or you won’t need your app.

    public static boolean isSDCardEnable(a) {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }
Copy the code
  • getExternalCacheDir()

    • Designed to store cached data. This is similar to the internal store getCacheDir().
  • getExternalFilesDir(String type)

    • Category stores public files.
    • If type is not null, create a folder named type in the external private directory. Null returns the external private root directory directly. Unless specifically needed, the individual approach is to pass in the Environment’s DIRECTORY constant for folder creation.
    • If you still don’t know how to use the API after reading this article, put all your application clutter in it. At least the files don’t have to be messy and will be cleaned up correctly after uninstallation, but you need to control how much storage you use.
  • getExternalMediaDirs()

    • Store shared media files.
    • This is an API added in Android 5.0 to create and retrieve an application directory in /sdcard/Android/media. Files in this directory can be accessed by other applications and queried and retrieved by MediaStore. Currently, however, few developers are using the API.

The public directory

To get a public directory, use the Environment Api, which returns directories that are all shared public directories. Android phone file storage mess culprit! A large number of irresponsible developers create folders, name and file randomly, and ordinary users have no way to determine which folders and files are useful. After uninstalling the app, huge garbage files that cannot be cleaned up are left, resulting in lack of mobile phone space. So they were deprecated in Android Q, but they worked well before Q, and I think we need to start using them less and using the private directory API in Context more.

  • getExternalStorageDirectory()

    • Gets the root directory of the external storage (SD card). Using getExternalStoragePublicDirectory (String) to replace.
  • getExternalStoragePublicDirectory(String type)

    • Return a folder named type in the root DIRECTORY. I divide it into two uses: one is to pass the Environment DIRECTORY constant and then create a subdirectory to use; One is to pass in appPackageName or easily identifiable name to create a subdirectory for use. The former is more general, and the content can be found by various tools and APPS (including wechat); The latter is for private use and can store files that do not follow the life of the app, even after uninstallation.

    • Environment.DIRECTORY_DCIM is a photo album for your phone. This folder is used by system-related apps to store camera photos, phone screenshots, etc. It is not recommended for developers to use this folder to avoid confusion. It is worth mentioning that Taobao is using this folder to save its product sharing screenshots, this location can really avoid being killed by micro envelope ~ haha

    • Environment.DIRECTORY_PICTURES is used to hold all kinds of “official” images, it is highly recommended to create a folder here for images you want to be found by users and wechat will scan this folder to make your images easier to share. But also.

    • Environment.DIRECTORY_DOWNLOADS can be used to store download resources such as APK for app updates.

    • The other few are less used and will not be introduced.

Adapter Android Q

The application storage function is sandboxed. Documentfiles should be stored outside the sandbox, and media files should be shared using MediaStore. The detailed adaptation has been shared by other developers. MOE/Archives /47…

I like ChengXiang ink film is out of the adapter TTP, more detailed content: mp.weixin.qq.com/s/aiDMyAfAZ…

At the end

Finally, a few important things:

  • Getting a file path can never kill a path. What if there is no SD card? What if a path becomes unusable? So you have to have a storage policy when you manage files. For example, there should not be only one API in the method of obtaining the save address of a file, and there should be a backpocket measure. If I can’t save external storage, I will save internal storage to ensure the normal operation of the APP.

I hope this article will give you a better understanding of how to manage folders on your phone.