Thursday , November 21 2024

How to clear cache data in your Android application Programmatically ?

clear_data

To do it programmatically you need to remove user data from application dir.

You have to create a class “MyApplication” which extends with “Application” class. In this class by using this code you can remove user data from application dir.

1). Declare MyApplication class in manifest file as shown below:

<application
android:name = <your_package_name>.MyApplication
android:allowBackup=”true”
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >

......

</application>

2). MyApplication class:

package com.w2class.cleaner;

import java.io.File;

import android.app.Application;
import android.util.Log;

public class MyApplication extends Application {
    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApplication getInstance(){
        return instance;
    }

    public void clearApplicationData() {
        File cache = getCacheDir();
        File appDir = new File(cache.getParent());
        if(appDir.exists()){
            String[] children = appDir.list();
            for(String s : children){
                if(!s.equals("lib")){
                    deleteDir(new File(appDir, s));
                    Log.i("TAG", "File /data/data/APP_PACKAGE/" + s +" DELETED");
                }
            }
        }
    }

    public static boolean deleteDir(File dir) {
        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();
    }
}

 

About admin

Check Also

Binding JavaScript and Android Code – Example

When developing a web application that’s designed specifically for the WebView in your Android application, …

Leave a Reply