Android Clear Cache Feature

Source: Internet
Author: User

The Application Data Cleanup Manager

Datacleanmanager.java was picked from the internet, forgot his name.

Loading a webview generating cache well-known webview is one of the main reasons for cache generation


WebView After loading click the button query cache and then clear the cache and then query the cache to see that the cache is actually cleared

Or I webview click the button to query the cache after loading and then go to set the inside application to see if the program's cache is the same answer must be the same

Here is the code


Datacleanmanager.java

Package com.yqy.yqy_cache;/* * File name: Datacleanmanager.java * Description: Main functions are to clear the inside/out cache, clear the database, clear the sharedpreference, clear files and clear Custom Catalog */import Java.io.file;import java.math.bigdecimal;import Android.content.context;import android.os.environment;/** * This app data Purge manager */public class Datacleanmanager {public static String gettotalcachesize (Context        Context) throws Exception {Long cacheSize = Getfoldersize (Context.getcachedir ()); if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {cacheSize + = Getfoldersize (con        Text.getexternalcachedir ());    } return Getformatsize (cacheSize); }//get File//context.getexternalfilesdir ()-sdcard/android/data/your app's package name/files/directory, generally put some long-saved data//context.ge  Texternalcachedir ()-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].isdirecto                  Ry ()) {size = size + getfoldersize (filelist[i]);                  } else {size = size + filelist[i].length ();          }}} catch (Exception e) {e.printstacktrace ();      } return size;        } public static void Clearallcache (context context) {Deletedir (Context.getcachedir ()); if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {Deletedir (Context.getexternalc        Achedir ());    }} private static Boolean Deletedir (File dir) {if (dir = = null) {return false;            } if (dir! = null && dir.isdirectory ()) {string[] children = dir.list ();    for (int i = 0; i < children.length; i++) {Boolean success = Deletedir (New File (dir, children[i]));            if (!success) {return false;    }}} return Dir.delete (); }/** * Formatted unit * * @param size * @return */public static String Getformatsize (Doub          Le size) {double kilobyte = size/1024;              if (kilobyte < 1) {//Return size + "Byte";        return "0K";          } 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"; /** * Clear this app internal cache (/data/data/com.xxx.xxx/cache) * * @param context */public static void Cleaninternalcache (context context ) {Deletefilesbydirectory (Context.getcachedir ());} /** * Clear all databases for this application (/data/data/com.xxx.xxx/databases) * * @param context */public static void cleandatabases (context context {Deletefilesbydirectory (New File ("/data/data/" + context.getpackagename () + "/databases"));} /** * * Clear this app sharedpreference (/data/data/com.xxx.xxx/shared_prefs) * * @param * context */public static void CLEANSHAREDPR Eference (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 Dbna Me) {context.deletedatabase (dbName);} /** * Clear the contents of/data/data/com.xxx.xxx/files * * @param context */public static void Cleanfiles (context context) {Deletefilesb Ydirectory (Context.getfilesdir ());} /** * * Clear the contents of the external cache (/mnt/sdcard/android/data/com.xxx.xxx/cache) * * @param * context */public static void Cleanexternalc Ache (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 (new file (FilePath));} /** * Clear all data for this app * * @param context * @param filepath */public static void Cleanapplicationdata (context context, String: . FilePath) {Cleaninternalcache (context); Cleanexternalcache (context); CleandatabaSES (context); cleansharedpreference (context); Cleanfiles (context); for (String Filepath:filepath) {Cleancustomcache ( FilePath);}} /** * Delete Method This will only delete files under a folder, if the incoming directory is a file, will not do processing * * @param directory */private static void Deletefilesbydirectory (Fil E directory) {if (directory! = null && directory.exists () && directory.isdirectory ()) {for (File Item:di Rectory.listfiles ()) {Item.delete ();}}}}

Mainactivity.java

Package Com.yqy.yqy_cache;import Android.app.activity;import Android.os.bundle;import android.util.Log;import Android.view.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.webkit.WebView Import Android.widget.button;public class Mainactivity extends Activity {private Button btn_clear;private WebView wv;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main) Btn_clear = (Button) Findviewbyid (r.id.btn_clear); WV = (WebView) Findviewbyid (R.ID.WV); btn_ Clear.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method Stubtry {//view cache size LOG.E ("YQY", Datacleanmanager.gettotalcachesize (Mainactivity.this));} catch (Exception e) { E.printstacktrace ();} Clear Operation Datacleanmanager.clearallcache (Mainactivity.this), try {//clear operation LOG.E ("YQY", Datacleanmanager.gettotalcachesize (Mainactivity.this));} catch (Exception e) {e.printstacktrace ();}}}); Wv.loadurl ("http://www.baidu.com");} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}


Activity_main. Xml

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    tools:context= ". Mainactivity ">    <button        android:id=" @+id/btn_clear "        android:layout_width=" Wrap_content        " android:layout_height= "Wrap_content"        android:layout_alignparentbottom= "true"        android:layout_ Centerhorizontal= "true"        android:text= "Clear Cache"/>    <webview        android:id= "@+id/wv"        android: Layout_width= "Match_parent"        android:layout_height= "match_parent"        android:layout_above= "@+id/btn_ Clear "        android:layout_alignparenttop=" true "        android:layout_centerhorizontal=" true "/></ Relativelayout>




Android Clear Cache Feature

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.