1

I'm doing an Android application which needs to list out all installed applications with cache size & app user data size. Now I want to clear the data (both cache & User data) of all installed applications. Below is my tried code. Its not clearing data. When I go to Settings -> Applications -> Manage Applications -> Your Application -> Size is still showing as data & Cache. How could I remove those unused data for all installed applications. Thanks.

My code:

...

public static void trimCache(Context context) {

    try {
        File dir = context.getCacheDir();
        if (dir != null && dir.isDirectory()) {
            deleteDir(dir);
        }
    } catch (Exception e) {
        // TODO: handle exception
    }
}
 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;
            }
        }

    }

    // The directory is now empty so delete it
    return dir.delete();
}

private void showProgress(String message) {
    pd = new ProgressDialog(this);
    pd.setIcon(R.drawable.ic_launcher);
    pd.setTitle("Please Wait...");
    pd.setMessage(message);
    pd.setCancelable(false);
    pd.show();

}

long packageSize = 0, size = 0;
AppDetails cAppDetails;
public ArrayList<PackageInfoStruct> res;

private void getpackageSize() {
    PACK_SIZE.clear();
    DATA_SIZE.clear();
    CACHE_SIZE.clear();
    mPack = null;
    mData = null;
    mCache = null;

    cAppDetails = new AppDetails(this);
    res = cAppDetails.getPackages();
    if (res == null)
        return;
    for (int m = 0; m < res.size(); m++) {
        PackageManager pm = getPackageManager();
        Method getPackageSizeInfo;
        try {
            getPackageSizeInfo = pm.getClass().getMethod(
                    "getPackageSizeInfo", String.class,
                    IPackageStatsObserver.class);
            getPackageSizeInfo.invoke(pm, res.get(m).pname,
                    new cachePackState());
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    handle.sendEmptyMessage(ALL_PACAGE_SIZE_COMPLETED);
    Log.v("Total Cache Size", " " + packageSize);

}

private Handler handle = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case FETCH_PACKAGE_SIZE_COMPLETED:
            if (packageSize > 0)
                size = (packageSize / 1024000);
             lbl_cache_size.setText("Cache Size : " + size + " MB");
            break;
        case ALL_PACAGE_SIZE_COMPLETED:
            MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(
                    CacheList.this, mPack, mData, mCache);
            lv.setAdapter(adapter);

            if (null != pd)
                if (pd.isShowing())
                    pd.dismiss();

            break;
        default:
            break;
        }

    }

};

private class cachePackState extends IPackageStatsObserver.Stub {

    @Override
    public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
            throws RemoteException {
        Log.d("Package Size", pStats.packageName + "");
        Log.i("Cache Size", pStats.cacheSize + "");
        Log.w("Data Size", pStats.dataSize + "");
        packageSize = packageSize + pStats.cacheSize;
        Log.v("Total Cache Size", " " + packageSize);


        PACK_SIZE.add(pStats.packageName);
        DATA_SIZE.add(String.valueOf(pStats.dataSize / 1024000));
        CACHE_SIZE.add(String.valueOf(pStats.cacheSize / 1024000));

        mPack = PACK_SIZE.toArray(new String[PACK_SIZE.size()]);
        mData = DATA_SIZE.toArray(new String[DATA_SIZE.size()]);
        mCache = CACHE_SIZE.toArray(new String[CACHE_SIZE.size()]);
        handle.sendEmptyMessage(FETCH_PACKAGE_SIZE_COMPLETED);
    }

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_get_cacheSize:
        size = 0;
        packageSize = 0;
        showProgress("Calculating Cache Size..!!!");
        /**
         * You can also use async task
         * */
        new Thread(new Runnable() {

            @Override
            public void run() {
                getpackageSize();
            }
        }).start();

        break;
    case R.id.btn_clear_cache:
        clearApplicationData();// Clear User Data
        trimCache(CacheList.this);// Clear Cache Data
        Toast.makeText(getApplicationContext(), "Successfully Cleared",
                Toast.LENGTH_SHORT).show();
    }
}
TomCho
  • 3,204
  • 6
  • 32
  • 83
Subra
  • 33
  • 1
  • 6
  • Possible duplicate of http://stackoverflow.com/questions/4553238/how-to-clear-data-cache-of-the-application-through-code – Harsh Dattani Apr 28 '15 at 11:10
  • @Harsh Thanks for your reply. It show How to clear cache files. But i need also how to delete app User data. Could you guide me in this? – Subra Apr 28 '15 at 11:22
  • 1
    Fortunately, you cannot clear the "user data" (interpreted here as meaning places like `getFilesDir()` or `getDatabaseDir()`) of third-party apps, unless your app is running with superuser privileges on a rooted device. – CommonsWare Apr 28 '15 at 11:24

0 Answers0