Android Development record 20-get cache size and Clear cache feature

Source: Internet
Author: User

Android Development record 20-get cache size and clear cache feature
Reprint Please specify: It_xiao Wizard Blog address: http://blog.csdn.net/wwj_748
Preface

This blog to share how to get the size of the application cache and the ability to clear the cache, we know that our application often produces some data, compared to the chip cache, database files, configuration files and so on. When we develop products, there may be such a need to clear in-app cache data, allowing users to choose to delete the data generated in the application, this is a more humane design point. For example, the author involved in the development of a product Setup interface provides the ability to clear the cache, as shown in:


Before pasting a large piece of code, first popularize the relevant knowledge points of Android:

Look at a picture of 360 mobile phone assistants first:


From the above picture, we can see that this phone has

System files (Note: This is the system's file system, not allowed to modify)

Built-in SD card (note: Now the phone basically has, is our so-called ROM, is not removable, RAM is our phone's running memory)

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

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

Our applications typically produce the following types of data:

file-Common file Storage

database-database file (. db file)

sharedpreference-configuration data (. xml file)

cache-Picture Cache file


All paths to the in-app data:

/data/data/com.xxx.xxx/cache-in-app cache (Note: corresponding method Getcachedir ())

/data/data/com.xxx.xxx/databases-in-app database

/data/data/com.xxx.xxx/shared_prefs-in-app configuration files

/data/data/com.xxx.xxx/files-In-app file (Note: Corresponding method Getfilesdir ())


One situation where we don't have an external SD card, where are our installed apps installed? Naturally the internal SD card in the phone, the specific path is this:


So what's the way to get this path in Android:


If our phone has an external SD card, we can also install the app on the SD card, but after removing the SD card it will not be available.



Whether it's a built-in or an external SD card, the way to get the path is the same:

Get the SD card root directory: Environment.getexternalstoragedirectory (). GetAbsolutePath ();

External cache path:/mnt/sdcard/android/data/com.xxx.xxx/cache generally stores cached data (note: obtained via Getexternalcachedir ())

External file path:/mnt/sdcard/android/data/com.xxx.xxx/files stores long-existing data (note: obtained by Getexternalfilesdir (String type), Type is specific and can be any one of the following

Environment.directory_music, Environment.directory_podcasts, Environment.directory_ringtones, Environment.directory_alarms, Environment.directory_notifications, 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 function is to clear the internal/external cache, clear the database, clear the Sharedpreferenc E, clear files and clear custom directories * */import Java.io.file;import java.math.bigdecimal;import Android.content.context;import Android.os.environment;import android.text.textutils;/** * This app data Purge manager */public class Datacleanmanager {/** * * Clear this app internal cache (/data/data/com.xxx.xxx/cache) * * * * @param context */public static void Cleaninternalcache (context context) {Deletefil Esbydirectory (Context.getcachedir ());} /** * * Clear all databases for this application (/data/data/com.xxx.xxx/databases) * * * * @param context */public static void cleandatabases (context C Ontext) {deletefilesbydirectory (New File ("/data/data/" + context.getpackagename () + "/databases"));} /** * * Clear this app sharedpreference (/data/data/com.xxx.xxx/shared_prefs) * * * @param context */public static void CLEANSHAREDP Reference (context context) {Deletefilesbydirectory (New File ("/data/data/" + context.getpackagename () + "/shared_prefs "));} /** * * Clear the application database by name * ** * @param context * @param dbName */public static void Cleandatabasebyname (context context, String DbName) {Context.dele Tedatabase (dbName);} /** * * Clear/data/data/com.xxx.xxx/files content * * * * @param context */public static void Cleanfiles (context context) {Delet Efilesbydirectory (Context.getfilesdir ());} /** * * Clear the contents of the external cache (/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param context */public static void Cleanexternalca Che (context context) {if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) { Deletefilesbydirectory (Context.getexternalcachedir ());}} /** * * Clear the file under the custom path, use caution, please do not delete it by mistake. And only supports file deletion in Directory * * * * @param filePath * */public static void Cleancustomcache (String filePath) {deletefilesbydirectory (NE W File (FilePath));} /** * * Clear all data for this app * * * * @param context * @param filepath */public static void Cleanapplicationdata (context context, St Ring ... filepath) {Cleaninternalcache (context); Cleanexternalcache (context); cleandatabases (context); Cleansharedpreference (context); Cleanfiles (context); if (filepath = = null) {return;} for (String Filepath:filepath) {cleancustomcache (FilePath);}} /** * * Delete method will only delete files under a folder, if the incoming directory is a file, will not do processing * * * * @param directory */private static void Deletefilesbydirecto Ry (file directory) {if (directory! = null && directory.exists () && directory.isdirectory ()) {for (file ite M:directory.listfiles ()) {Item.delete ();}}} Get file//context.getexternalfilesdir ()-sdcard/android/data/your app's package name/files/directory, usually put some long time to save the data// Context.getexternalcachedir ()-sdcard/android/data/your app package name/cache/directory, generally storing temporary cache data public static long Getfoldersize (file file) throws Exception {Long size = 0;try {file[] fileList = File.listfiles (); for (int i = 0; i < filelist.length ; i++) {//If the file below also has the 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 is a file files[] = files below. 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 File.delete ();} else {//directory if (File.listfiles (). Length = = 0) {// There is no file or directory under the directory, delete File.delete ();}}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}  /** * Formatted 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)); RET Urn 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)); r Eturn 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));}}

Android Development record 20-get cache size and Clear cache feature

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.