android 清除緩衝功能

來源:互聯網
上載者:User

標籤:folder   items   stat   sts   pos   red   cep   idt   操作   

本應用資料清除管理器  

DataCleanManager.java   是從網上摘的 忘了 名字了 對不住了

載入一個webview   產生緩衝  眾所周知的webview是產生緩衝的主要原因之中的一個


webview載入之後   點擊button  查詢快取  然後清除緩衝  再查詢快取  能夠看到  緩衝確實被清除了  

或者咋webview載入之後  點擊button查詢快取  然後去設定裡面應用程式  看程式的緩衝是不是一樣的  答案肯定是一樣 

以下是代碼


DataCleanManager.java

package com.yqy.yqy_cache;/*  * 文 件 名:  DataCleanManager.java  * 描    述:  主要功能有清除內/外緩衝。清除資料庫,清除sharedPreference,清除files和清除自己定義檔案夾  */import java.io.File;import java.math.BigDecimal;import android.content.Context;import android.os.Environment;/** * 本應用資料清除管理器 */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(context.getExternalCacheDir());        }          return getFormatSize(cacheSize);    }// 擷取檔案      //Context.getExternalFilesDir() --> SDCard/Android/data/你的應用的包名/files/ 檔案夾,一般放一些長時間儲存的資料      //Context.getExternalCacheDir() --> SDCard/Android/data/你的應用程式套件名/cache/檔案夾,一般存放暫時快取資料      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 (fileList[i].isDirectory()) {                      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.getExternalCacheDir());        }      }       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();    }           /**      * 格式化單位      *       * @param size      * @return      */     public static String getFormatSize(double 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";      } /** * 清除本應用內部緩衝(/data/data/com.xxx.xxx/cache) * * @param context */public static void cleanInternalCache(Context context) {deleteFilesByDirectory(context.getCacheDir());}/** * 清除本應用全部資料庫(/data/data/com.xxx.xxx/databases) * * @param context */public static void cleanDatabases(Context context) {deleteFilesByDirectory(new File("/data/data/"+ context.getPackageName() + "/databases"));}/** * * 清除本應用SharedPreference(/data/data/com.xxx.xxx/shared_prefs) * * @param * context */public static void cleanSharedPreference(Context context) {deleteFilesByDirectory(new File("/data/data/"+ context.getPackageName() + "/shared_prefs"));}/** * 按名字清除本應用程式資料庫 * * @param context * @param dbName */public static void cleanDatabaseByName(Context context, String dbName) {context.deleteDatabase(dbName);}/** * 清除/data/data/com.xxx.xxx/files下的內容 * * @param context */public static void cleanFiles(Context context) {deleteFilesByDirectory(context.getFilesDir());}/** * * 清除外部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());}}/** * 清除自己定義路徑下的檔案。使用需小心。請不要誤刪。並且僅僅支援檔案夾下的檔案刪除 * * @param filePath */public static void cleanCustomCache(String filePath) {deleteFilesByDirectory(new File(filePath));}/** * 清除本應用全部的資料 * * @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);}}/** * 刪除方法 這裡僅僅會刪除某個檔案夾下的檔案,假設傳入的directory是個檔案,將不做處理 * * @param directory */private static void deleteFilesByDirectory(File directory) {if (directory != null && directory.exists() && directory.isDirectory()) {for (File item : directory.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 {//查看緩衝的大小Log.e("YQY", DataCleanManager.getTotalCacheSize(MainActivity.this));} catch (Exception e) {e.printStackTrace();}//清除操作DataCleanManager.clearAllCache(MainActivity.this);try {//清除後的操作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 present.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="清除緩衝" />    <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 清除緩衝功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.