天天看點

安卓輕松實作清理緩存

效果圖

安卓輕松實作清理緩存
安卓輕松實作清理緩存

layout布局

activity_clean_cache.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="cn.edu.nju.software.tongbaoshipper.controller.activity.CleanCacheActivity">
    <RelativeLayout
        android:id="@+id/clean_title"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:background="@color/background_blue">

        <LinearLayout
            android:id="@+id/clean_btn_back"
            android:layout_width="@dimen/title_btn_width"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:gravity="center">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/back" />
        </LinearLayout>

        <TextView
            android:id="@+id/cache_title"
            style="@style/title_font"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@string/clean_cache" />
    </RelativeLayout>

    <TextView
        android:id="@+id/cache_size"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="10M"
        android:textColor="@color/colorPrimary"
        android:textSize="20pt"
        android:layout_below="@+id/clean_title"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"/>


    <Button
        android:id="@+id/button_clean"
        android:background="@color/colorPrimary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/clean_button"
        android:textColor="@color/font_white"
        android:layout_below="@+id/cache_size"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"/>

</RelativeLayout>
           

activity實作代碼

我這裡activity是用kotlin代碼實作的,用java的可以自行轉換

CleanCacheActivity.kt

package cn.edu.nju.software.tongbaoshipper.controller.activity

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import cn.edu.nju.software.tongbaoshipper.R
import cn.edu.nju.software.tongbaoshipper.controller.utils.DataCleanManager
import cn.edu.nju.software.tongbaoshipper.controller.utils.GetFileSize

class CleanCacheActivity : AppCompatActivity() {
    var cacheSize: String = "";
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_clean_cache)
        val btnBack: LinearLayout = findViewById(R.id.clean_btn_back) as LinearLayout
        btnBack.setOnClickListener { finish() }
        val cachTextView: TextView = findViewById(R.id.cache_size) as TextView
        cacheSize = GetFileSize.FormetFileSize(GetFileSize.getFileSize([email protected].cacheDir))
        cachTextView.setText(cacheSize)
        val btnClean: Button = findViewById(R.id.button_clean) as Button
        btnClean.setOnClickListener {
            DataCleanManager.cleanInternalCache([email protected])
            cacheSize = GetFileSize.FormetFileSize(GetFileSize.getFileSize([email protected].cacheDir))
            cachTextView.setText(cacheSize)
        }
    }
}
           

GetFileSize.java

package cn.edu.nju.software.tongbaoshipper.controller.utils;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;

/**
 * 作者 : motoon
 * 日期 : 2017/5/28
 * 版本 : v1.0
 */

public class GetFileSize {
    public static long getFileSizes(File f) throws Exception{//取得檔案大小
        long s=;
        if (f.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(f);
            s= fis.available();
        } else {
            f.createNewFile();
            System.out.println("檔案不存在");
        }
        return s;
    }
    // 遞歸
    public static long getFileSize(File f)throws Exception//取得檔案夾大小
    {
        long size = ;
        File flist[] = f.listFiles();
        for (int i = ; i < flist.length; i++)
        {
            if (flist[i].isDirectory())
            {
                size = size + getFileSize(flist[i]);
            } else
            {
                size = size + flist[i].length();
            }
        }
        return size;
    }
    public static String FormetFileSize(long fileS) {//轉換檔案大小
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < ) {
            if (fileS < ){
                fileSizeString =  + "B";
            }else {
                fileSizeString = df.format((double) fileS) + "B";
            }
        } else if (fileS < ) {
            fileSizeString = df.format((double) fileS / ) + "K";
        } else if (fileS < ) {
            fileSizeString = df.format((double) fileS / ) + "M";
        } else {
            fileSizeString = df.format((double) fileS / ) + "G";
        }
        return fileSizeString;
    }

    public static long getlist(File f){//遞歸求取目錄檔案個數
        long size = ;
        File flist[] = f.listFiles();
        size=flist.length;
        for (int i = ; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getlist(flist[i]);
                size--;
            }
        }
        return size;
    }

    public static void main(String args[])
    {
        GetFileSize g = new GetFileSize();
        long startTime = System.currentTimeMillis();
        try
        {
            long l = ;
            String path = "C:\\WINDOWS";
            File ff = new File(path);
            if (ff.isDirectory()) { //如果路徑是檔案夾的時候
                System.out.println("檔案個數           " + g.getlist(ff));
                System.out.println("目錄");
                l = g.getFileSize(ff);
                System.out.println(path + "目錄的大小為:" + g.FormetFileSize(l));
            } else {
                System.out.println("     檔案個數           1");
                System.out.println("檔案");
                l = g.getFileSizes(ff);
                System.out.println(path + "檔案的大小為:" + g.FormetFileSize(l));
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("總共花費時間為:" + (endTime - startTime) + "毫秒...");
    }
}
           

DataCleanManager.java

/**
 * 作者 : motoon
 * 日期 : 2017/5/28
 * 版本 : v1.0
 */
package cn.edu.nju.software.tongbaoshipper.controller.utils;

/*  * 文 件 名:  DataCleanManager.java
 * * 描    述:  主要功能有清除内/外緩存,清除資料庫,清除sharedPreference,清除files和清除自定義目錄
 * */

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.math.BigDecimal;

/** * 本應用資料清除管理器 */
public class DataCleanManager {
    /**
     * * 清除本應用内部緩存(/data/data/com.xxx.xxx/cache) * *
     *
     * @param context
     */
    public static void cleanInternalCache(Context context) {
        deleteFolderFile(String.valueOf(context.getCacheDir()),false);
    }

    /**
     * * 清除本應用所有資料庫(/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);
        if (filepath == null) {
            return;
        }
        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();
            }
        }
    }

    // 擷取檔案
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的應用的包名/files/ 目錄,一般放一些長時間儲存的資料
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的應用包名/cache/目錄,一般存放臨時緩存資料
    public static long getFolderSize(File file) throws Exception {
        long size = ;
        try {
            File[] fileList = file.listFiles();
            for (int i = ; 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 deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {// 如果下面還有檔案
                    File files[] = file.listFiles();
                    for (int i = ; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {// 如果是檔案,删除
                        file.delete();
                    } else {// 目錄
                        if (file.listFiles().length == ) {// 目錄下沒有檔案或者目錄,删除
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 格式化機關
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / ;
        if (kiloByte < ) {
            return size + "Byte";
        }

        double megaByte = kiloByte / ;
        if (megaByte < ) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / ;
        if (gigaByte < ) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / ;
        if (teraBytes < ) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }


    public static String getCacheSize(File file) throws Exception {
        return getFormatSize(getFolderSize(file));
    }

}
           

代碼寫完運作就OK啦!是不是很簡單哦~