[Android development experience] What Should cached files of an APP exist? After reading this article, you should be clear about it. androidapp

Source: Internet
Author: User

[Android development experience] What Should cached files of an APP exist? After reading this article, you should be clear about it. androidapp

Reprinted please indicate the source: http://blog.csdn.net/zhaokaiqiang1992

As long as it is an APP that requires online data retrieval, cache files will be generated locally, regardless of version update or image cache. So where are these cache files suitable? Does the system provide us with a suggested cache location? What are the differences between different cache locations? This article focuses on this issue.

First, we need to know that there are two types of cache locations in Android phones: Internal Storage, Internal Storage, and External Storage. The old mobile phone has an internal storage device and an SD card storage device, which corresponds to the two storage locations, because the previous SD card can be expanded and can be disassembled, therefore, it can be used as a classification standard for internal and external storage. However, the latest devices, such as Xiaomi, hammer, and Huawei, have all removed removable SD cards and welded them together with the body, which are divided into 16G and 32G versions, therefore, the classification of internal and external storage is no longer based on whether the storage is detachable, but the following aspects serve as a new Standard:


Internal Storage:

Always available
By default, files can only be accessed by your app.
When you uninstall your app, the system will clear all the related files in internal.
Internal is the best storage area you want to ensure that it is not accessed by users and other apps.


External Storage:

It is not always available, because you can choose to use this part as the USB storage mode, so that you will not be able to access it.
Is accessible to everyone, so the files saved here lose the access control permission.
When you uninstall your app, the system only deletes the relevant files under the external root directory (getExternalFilesDir.
External is the best storage region when you do not require strict access permissions and you want these files to be shared by other apps or allow users to access them through a computer.


The read permission is not required for the internal storage, but the read permission or write permission is required for the external storage. In the current version, the read permission is not declared or can be read, but may be modified in later versions, therefore, be sure to add the write permission. If the application requires the write permission, you only need to declare the write permission and do not need to declare the read permission.

The following describes how to obtain the locations and differences of files stored inside and outside the bucket.


1. Storage Method

1. getFileDir () can be used to obtain the files stored in your APP. The path is/data/pacgage_name/files.

We can directly test the Code:

File file1 = new File(getFilesDir(), "getFilesDir.txt");        Log.d("TAG", "file1=" + file1.getAbsolutePath());        try {            OutputStream outputStream1 = new FileOutputStream(file1);            outputStream1.write("file".getBytes());            outputStream1.close();        } catch (Exception e) {            e.printStackTrace();        }

The running result is as follows:

02-03 07:18:04.068  22237-22237/? D/TAG﹕ file1=/data/data/com.socks.baidudemo/files/getFilesDir.txt

2. getCacheDir () can be used to obtain the files stored in your APP. The path is/data/package_name/cache.

Test code:

File file2 = new File(getCacheDir(), "cache.txt");        Log.d("TAG", "file2=" + file2.getAbsolutePath());        try {            OutputStream outputStream1 = new FileOutputStream(file2);            outputStream1.write("cache".getBytes());            outputStream1.close();        } catch (Exception e) {            e.printStackTrace();        }

The running result is as follows:

02-03 07:19:31.508  23652-23652/? D/TAG﹕ file2=/data/data/com.socks.baidudemo/cache/cache.txt

3. openFileOutput () through this method, we can obtain an output stream. The storage path of the output stream is/data/package_name/files, which is consistent with the path of getFileDir ().

The test code is as follows:

try {            OutputStream outputStream = openFileOutput("openFileOutput.txt", MODE_PRIVATE);            outputStream.write("openFileOutput".getBytes());            outputStream.close();        } catch (Exception e) {            e.printStackTrace();        }

Running result:



The internal storage directory of your app is marked by the package name of your app and stored in the specific directory [data/com. example. xx] of the Android file system. Technically, if you set the file to readable, other apps can read your internal file. However, other apps need to know your package name and file name. If you are not set to readable or writable, other apps cannot read or write data. Therefore, as long as you use MODE_PRIVATE, these files cannot be accessed by other apps.

Remember that when your APP is uninstalled, it will be deleted. Therefore, we can place our image cache in the cache directory, in addition, the difference between cache and files is that if the internal storage control of the mobile phone is insufficient, the cache directory will be selected for deletion. Therefore, do not place important files in the cache file, it can be placed in files because the file will be deleted only when the APP is uninstalled. Note that if the application is updated, the internal storage will not be deleted. This is different from manual uninstallation.


Ii. External Storage

1. External Storage status

Unlike the internal storage, the external storage capacity is generally large. When a mobile device is connected to a PC, if we enable the USB mode to connect to the PC and operate files, at this time, the external storage is in the unmount status, and the APP cannot operate on the files in it. Therefore, before operating on the external storage, check the status of the external storage.

 /* Checks if external storage is available for read and write */public boolean isExternalStorageWritable() {    String state = Environment.getExternalStorageState();    if (Environment.MEDIA_MOUNTED.equals(state)) {        return true;    }    return false;}/* Checks if external storage is available to at least read */public boolean isExternalStorageReadable() {    String state = Environment.getExternalStorageState();    if (Environment.MEDIA_MOUNTED.equals(state) ||        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {        return true;    }    return false;}

2. External private storage

From the introduction of internal storage, the files stored in the internal storage should belong to private files. It is difficult for other apps to access the files. What about external storage? Because the external storage capacity is large, it is generally the best choice for our APP to store large files. Is it because the files in the external storage can be freely accessed by all apps? Obviously, this is not the case. In External Storage, there is also the concept of private files.

Just like the method we used to obtain internal storage, we can use Context. getExternalCacheDir () and Context. getExternalFilesDir () to obtain private files in external storage. The following code is used as an example:

File file3 = new File(getExternalCacheDir().getAbsolutePath(), "getExternalCacheDir.txt");        try {            OutputStream outputStream1 = new FileOutputStream(file3);            outputStream1.write("getExternalCacheDir".getBytes());            outputStream1.close();        } catch (Exception e) {            e.printStackTrace();        }        Log.d("TAG", "file3=" + file3);        File file4 = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "getExternalFilesDir.txt");        try {            OutputStream outputStream1 = new FileOutputStream(file4);            outputStream1.write("getExternalFilesDir".getBytes());            outputStream1.close();        } catch (Exception e) {            e.printStackTrace();        }

The running result is as follows:

02-03 08:11:38.860    9096-9096/? D/TAG﹕ file3=/storage/emulated/0/Android/data/com.socks.baidudemo/cache/getExternalCacheDir.txt02-03 08:11:38.860    9096-9096/? D/TAG﹕ file4=/storage/emulated/0/Android/data/com.socks.baidudemo/files/Pictures/getExternalFilesDir.txt

The location in the system is as follows:



We can see that the address of the private file we created is under/sdcard/Android/date/package_name. The Android folder is a hidden folder and cannot be operated by users.

If you want to cache images and other space-consuming files, it is recommended to put them under the file where getExternalCacheDir () is located. This file is similar to getCacheDir () and can both store cached files, when an APP is uninstalled, it will be deleted by the system, and the cached content is relatively private to other apps.

However, there are some differences:


Context. getExternalFilesDir () and Context. getFilesDir () are also different, but they are also deleted when the application is uninstalled.




3. External Public Storage

If the files generated by your APP do not need to be hidden, that is, they are visible to users, you can place the files under external public storage files.

We can use the following code to obtain the public storage directory.

Environment.getExternalStorageDirectory()Environment.getExternalStoragePublicDirectory()

This method is not the Context method, but the two Environment methods. The first method obtains the root directory of external storage, the second method gets the public directory of external storage. In fact, there is no difference in access permissions. The difference is that when getExternalStoragePublicDirectory () is running, you need a specific parameter to specify these public file types, to facilitate classification with other public files. The parameter types include DIRECTORY_MUSIC or DIRECTORY_PICTURES:

public File getAlbumStorageDir(Context context, String albumName) {    // Get the directory for the app's private pictures directory.    File file = new File(context.getExternalFilesDir(            Environment.DIRECTORY_PICTURES), albumName);    if (!file.mkdirs()) {        Log.e(LOG_TAG, "Directory not created");    }    return file;}

Whether you use getExternalStoragePublicDirectory () to store files that can be shared, or use getExternalFilesDir () to store files that are private to your app, it is very important, that is, you need to use the constants of the APIS similar to DIRECTORY_PICTURES. The directory type parameters can ensure that those files are correctly treated by the system. For example, files saved as DIRECTORY_RINGTONES will be considered as ringtone rather than music by the system's media repository.

The following are the folders corresponding to these parameters.



The cache folder has been messy. After this sorting, I feel a lot clearer ~~~~ ^_^ ~~~


---------------------------------------- Gorgeous split line ------------------------------------------

Thanks to the guys in the comments, it is true that 360 software also knows where our cache is, so one-click acceleration is likely to kill our cache files. What should we do? We can create a cache folder in the external storage to store our image cache or something. In this way, 360 won't be deleted, because if it is deleted incorrectly, he is in big trouble, hahaha!



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.