Monday, July 25, 2016

android - How to clear cache files

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f4f8ff"
    >
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        >
        <TextView
            android:id="@+id/tv_info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:elevation="3dp"
            android:background="#7dffffff"
            android:padding="8dp"
            />
    </ScrollView>
</android.support.design.widget.CoordinatorLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

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


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private CoordinatorLayout mCLayout;
    private TextView mTVInfo;

    private File mCacheDirectory;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widget reference from XML layout
        mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
        mTVInfo = (TextView) findViewById(R.id.tv_info);

        // Initialize a new StringBuilder instance
        StringBuilder builder = new StringBuilder();

        // Get the cache directory
        mCacheDirectory = mContext.getCacheDir();

        // Get the cache directory name
        String cacheDirName = mCacheDirectory.getName();
        builder.append("\nDirectory name : " + cacheDirName);

        // Get the cache directory length/size
        long length = mCacheDirectory.length();
        builder.append("\nLength : " + readableFileSize(length));

        // Get the cache directory absolute path
        String cacheDirPath = mCacheDirectory.getAbsolutePath();
        builder.append("\nDirectory path : " + cacheDirPath);

        // Get the cache directory total space
        long totalSpace = mCacheDirectory.getTotalSpace();
        builder.append("\n\nTotal space : " + readableFileSize(totalSpace));

        // Get the cache directory usable space
        long usableSpace = mCacheDirectory.getUsableSpace();
        builder.append("\nUsable space : " + readableFileSize(usableSpace));

        /*
            getFreeSpace()
                Returns the number of unallocated bytes in the partition named by
                this abstract path name.
        */
        // Get the cache directory free space
        long freeSpace = mCacheDirectory.getFreeSpace();
        builder.append("\nFree space : " + readableFileSize(freeSpace));

        // Get the cache directory file list
        File[] files = mCacheDirectory.listFiles();

        // Get the number of cache files
        builder.append("\n\nNumber of cache files : " + files.length);

        // Initialize a variable to calculate cache files length
        long filesLength = 0;

        builder.append("\n\nFile list : ");

        // Iterate over the cache directory file list
        for(File file:files){
            builder.append("\n"+ file.getName() + " : " + readableFileSize(file.length()));
            filesLength += file.length();

            // Now delete the cache file
            // Finally, this loop will empty the cache directory
            file.delete();
        }

        // Get the cache files total size
        builder.append("\n\nCache files length : " + readableFileSize(filesLength));

        // Get the cache directory file list again
        File[] filesList = mCacheDirectory.listFiles();

        if(filesList.length == 0){
            builder.append("\n\nWOW! No cache files exists....");
        }else {
            // Get the number of cache files after deleting
            builder.append("\n\nNumber of cache files : " + filesList.length);
        }

        // Finally, display the cache directory info
        mTVInfo.setText(builder);
    }

    // Custom method to get human readable file size from bytes
    public static String readableFileSize(long size) {
        if(size <= 0) return "0";
        final String[] units = new String[] {
                "B",
                "kB",
                "MB",
                "GB",
                "TB"
        };
        int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}