Android development record 20-Get cache size and clear cache function, android20-

Source: Internet
Author: User

Android development record 20-Get cache size and clear cache function, android20-
Android development record 20-Get cache size and clear cache Function

Reprinted Please note: IT_xiao Little Wu blog address: http://blog.csdn.net/wwj_748
Preface

This blog will share with you how to obtain the application cache size and clear the cache function. We know that our applications often produce some data, such as slice cache and database files, configuration files. When developing products, we may need to clear the cached data in the application so that users can choose to delete the data generated in the application. This is also a user-friendly design point. For example, the setting interface of a product developed by the author provides the cache clearing function, as shown in:


Before Pasting a large piece of code, we should first popularize the knowledge of Android:

First look at a figure of the 360 mobile ASSISTANT:


From the figure above, we can see that this mobile phone has

System File (note: this is the system file system and cannot be modified)

Built-in SD card (Note: The current mobile phones are basically available, that is, our so-called ROM, which cannot be removed, and RAM is the running memory of our mobile phones)

External SD card (Note: This is our SD card and can be removed)

Let's consider a question: where is the cache data stored in our application?

Our applications generally generate the following types of data:

File-common file storage

Database-database file (. db file)

SharedPreference-configuration data (. xml file)

Cache-image cache files


All data paths in the application:

/Data/com. xxx. xxx/cache-in-app cache (Note: Corresponding Method getCacheDir ())

/Data/com. xxx. xxx/databases-in-app Database

/Data/com. xxx. xxx/shared_prefs-application configuration file

/Data/com. xxx. xxx/files-files in the application (Note: Corresponding Method getFilesDir ())


In one case, we do not have an external SD card, so where is the installed application? Naturally, it is the built-in SD card in the mobile phone. The specific path is as follows:


In Android, how does one obtain the path:


If our mobile phone has an external SD card, we can also install the app on the SD card, but it cannot be used after the SD card is removed.



Whether it is a built-in or external SD card, the method for obtaining the path is the same:

Get the root directory of the SD card: Environment. getExternalStorageDirectory (). getAbsolutePath ();

External Cache path:/mnt/sdcard/android/data/com. xxx. xxx/cache generally stores cached data (Note: obtained through getExternalCacheDir)

External File path:/mnt/sdcard/android/data/com. xxx. xxx/files stores long-time data (Note: obtained through getExternalFilesDir (String type), type is of a specific type, can be any of the following

Environment. DIRECTORY_MUSIC, Environment. Environment, Environment. directory_configurations, Environment. DIRECTORY_PICTURES, or Environment. DIRECTORY_MOVIES .)


Finally, a tool class is provided:

DataCleanManager. java

Package com. infzm. daily. know. utils;/** file name: DataCleanManager. java ** Description: main functions include clearing the internal/external cache, clearing the database, sharedPreference, files, and user-defined directories. **/import java. io. file; import java. math. bigDecimal; import android. content. context; import android. OS. environment; import android. text. textUtils;/***** the application data clearing manager */public class DataCleanManager {/***** clears the internal cache of the application (/data/com. xxx. xxx/cache) ***** @ param context */pub Lic static void cleanInternalCache (Context context) {deleteFilesByDirectory (context. getCacheDir ();}/***** clear all databases of the application (/data/com. xxx. xxx/databases) ***** @ param context */public static void cleanDatabases (Context context) {deleteFilesByDirectory (new File ("/data/" + context. getPackageName () + "/databases");}/***** clear the SharedPreference (/data/com. xxx. xxx/shared_prefs) *** @ param Context */public static void cleanSharedPreference (Context context) {deleteFilesByDirectory (new File ("/data/" + context. getPackageName () + "/shared_prefs "));} /***** clear the application database by name ***** @ param context * @ param dbName */public static void cleanDatabaseByName (Context context, String dbName) {context. deleteDatabase (dbName);}/***** clear/data/com. xxx. content in xxx/files *** @ param context */publi C static void cleanFiles (Context context) {deleteFilesByDirectory (context. getFilesDir ();}/***** clear content in the external cache (/mnt/sdcard/android/data/com. xxx. xxx/cache) ** @ param context */public static void cleanExternalCache (Context context) {if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {deleteFilesByDirectory (context. getExternalCacheDir ();}/*** clear the files in the custom path. Be careful when using the command. Do not delete the files by mistake. Only files in the directory can be deleted ***** @ param filePath **/public static void cleanCustomCache (String filePath) {deleteFilesByDirectory (new File (filePath ));} /***** clear all data of the application ***** @ param context * @ param filepath */public static void cleanApplicationData (Context context, String... filepath) {cleanInternalCache (context); cleanExternalCache (context); cleanDatabases (context); cleanSharedPreference (context); cleanFiles (Context); if (filepath = null) {return ;}for (String filePath: filepath) {cleanCustomCache (filePath );}} /***** the deletion method only deletes files in a folder. If the imported directory is a file, *** @ param directory */private static void deleteFilesByDirectory (File directory) {if (directory! = Null & directory. exists () & directory. isDirectory () {for (File item: directory. listFiles () {item. delete () ;}}// obtain the file // Context. getExternalFilesDir () --> SDCard/Android/data/the package name/files/directory of your application. Generally, save some long-time data // Context. getExternalCacheDir () --> SDCard/Android/data/your application package name/cache/directory, which generally stores temporary cache data public static long getFolderSize (File file) throws Exception {long size = 0; try {File [] fileList = file. listF Iles (); for (int I = 0; I <fileList. length; I ++) {// if there is a file below if (fileList [I]. isDirectory () {size = size + getFolderSize (fileList [I]);} else {size = size + fileList [I]. length () ;}} catch (Exception e) {e. printStackTrace ();} return size ;} /*** delete files and directories in the specified directory ** @ param deleteThisPath * @ param filepath * @ return */public static void deleteFolderFile (String filePath, boolean deleteThisPath) {if (! TextUtils. isEmpty (filePath) {try {File file = new File (filePath); if (file. isDirectory () {// if there are still files under File files [] = file. listFiles (); for (int I = 0; I <files. length; I ++) {deleteFolderFile (files [I]. getAbsolutePath (), true) ;}} if (deleteThisPath) {if (! File. isDirectory () {// if it is a file, delete the file. delete ();} else {// directory if (file. listFiles (). length = 0) {// No file or directory exists in the directory. delete the file. delete () ;}}} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}/ ***** formatting unit ** @ param size * @ return */public static String getFormatSize (double size) {double kiloByte = size/1024; if (kiloByte <1) {return size + "Byte";} double megaByte = kiloByte/1024; if (megaByte <1) {BigDecimal result1 = new BigDecimal (Double. toString (kiloByte); return result1.setScale (2, BigDecimal. ROUND_HALF_UP ). toPlainString () + "KB";} double gigaByte = megaByte/1024; if (gigaByte <1) {BigDecimal result2 = new BigDecimal (Double. toString (megaByte); return result2.setScale (2, BigDecimal. ROUND_HALF_UP ). toPlainString () + "MB";} double teraBytes = gigaByte/1024; if (teraBytes <1) {BigDecimal result3 = new BigDecimal (Double. toString (gigaByte); return result3.setScale (2, BigDecimal. ROUND_HALF_UP ). toPlainString () + "GB";} BigDecimal result4 = new BigDecimal (teraBytes); return result4.setScale (2, BigDecimal. ROUND_HALF_UP ). toPlainString () + "TB";} public static String getCacheSize (File file) throws Exception {return getFormatSize (getFolderSize (file ));}}

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.