Skip to content Skip to sidebar Skip to footer

How To Programmatically Calculate All Cache Size Of Installed Application?

i just want to show list of all installed application name with cache size. Cache size must be same as native setting application show in android device. i able to list all install

Solution 1:

To get the cache size of the Installed Application directly u can not get. As using PackageManger we cant directly get the details regarding installed package size as abstract getPackageSizeInfo method is directly not accessible so by using Java Reflection you can invoke it.It may not work if in future the method name change or any thing changed.

You need to create AIDL IPackageStatsObserver.aidl & PackageStats.aidl which should be in the android.content.pm package as you cant directly access them.

IPackageStatsObserver.aidl

package android.content.pm;
import android.content.pm.PackageStats;
oneway interfaceIPackageStatsObserver {
voidonGetStatsCompleted(in android.content.pm.PackageStats pStats, boolean succeeded);
}

PackageStats.aidl

package android.content.pm;
parcelable PackageStats;

IPackageStatsObserver.aidl & PackageStats.aidl both keep it in android.content.pm package. IDataStatus

publicinterfaceIDataStatus {
    publicvoidonStatusListner(String msg);
}

Activity

publicclassMyScreenextendsActivityimplementsOnClickListener {
    publicstaticfinalintFETCH_PACKAGE_SIZE_COMPLETED=100;
    publicstaticfinalintALL_PACAGE_SIZE_COMPLETED=200;
    IDataStatus onIDataStatus;
    TextView lbl_cache_size;
    ProgressDialog pd;

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.btn_get_cacheSize).setOnClickListener(this);
        lbl_cache_size = (TextView) findViewById(R.id.lbl_cache_size);
        // clearCache();
    }

    privatevoidshowProgress(String message) {
        pd = newProgressDialog(this);
        pd.setIcon(R.drawable.ic_launcher);
        pd.setTitle("Please Wait...");
        pd.setMessage(message);
        pd.setCancelable(false);
        pd.show();

    }

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

    privatevoidgetpackageSize() {
        cAppDetails = newAppDetails(this);
        res = cAppDetails.getPackages();
        if (res == null)
            return;
        for (intm=0; m < res.size(); m++) {
            PackageManagerpm= getPackageManager();
            Method getPackageSizeInfo;
            try {
                getPackageSizeInfo = pm.getClass().getMethod(
                        "getPackageSizeInfo", String.class,
                        IPackageStatsObserver.class);
                getPackageSizeInfo.invoke(pm, res.get(m).pname,
                        newcachePackState());
            } 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);

    }

    privateHandlerhandle=newHandler() {
        @OverridepublicvoidhandleMessage(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:
                if (null != pd)
                    if (pd.isShowing())
                        pd.dismiss();

                break;
            default:
                break;
            }

        }

    };

    privateclasscachePackStateextendsIPackageStatsObserver.Stub {

        @OverridepublicvoidonGetStatsCompleted(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);
            handle.sendEmptyMessage(FETCH_PACKAGE_SIZE_COMPLETED);
        }

    }

    @OverridepublicvoidonClick(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
             * */newThread(newRunnable() {

                @Overridepublicvoidrun() {
                    getpackageSize();
                }
            }).start();

            break;
        }
    }

}

AppDetails

publicclassAppDetails {
    Activity mActivity;
    public ArrayList<PackageInfoStruct> res = newArrayList<PackageInfoStruct>();
    public ListView list;
    public String app_labels[];

    publicAppDetails(Activity mActivity) {
        this.mActivity = mActivity;

    }

    public ArrayList<PackageInfoStruct> getPackages() {
        ArrayList<PackageInfoStruct> apps = getInstalledApps(false); /*
                                                                     * false =
                                                                     * no system
                                                                     * packages
                                                                     */finalintmax= apps.size();
        for (inti=0; i < max; i++) {
            apps.get(i);
        }
        return apps;
    }

    private ArrayList<PackageInfoStruct> getInstalledApps(boolean getSysPackages) {

        List<PackageInfo> packs = mActivity.getPackageManager()
                .getInstalledPackages(0);
        try {
            app_labels = newString[packs.size()];
        } catch (Exception e) {
            Toast.makeText(mActivity.getApplicationContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
        for (inti=0; i < packs.size(); i++) {
            PackageInfop= packs.get(i);
            if ((!getSysPackages) && (p.versionName == null)) {
                continue;
            }
            PackageInfoStructnewInfo=newPackageInfoStruct();
            newInfo.appname = p.applicationInfo.loadLabel(
                    mActivity.getPackageManager()).toString();
            newInfo.pname = p.packageName;
            newInfo.datadir = p.applicationInfo.dataDir;
            newInfo.versionName = p.versionName;
            newInfo.versionCode = p.versionCode;
            newInfo.icon = p.applicationInfo.loadIcon(mActivity
                    .getPackageManager());
            res.add(newInfo);

            app_labels[i] = newInfo.appname;
        }
        return res;
    }

    classPackageInfoStruct {
        Stringappname="";
        Stringpname="";
        StringversionName="";
        intversionCode=0;
        Drawable icon;
        Stringdatadir="";
    }
}

xml

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><Buttonandroid:id="@+id/btn_get_cacheSize"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Get Cache Size" /><TextViewandroid:id="@+id/lbl_cache_size"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Cache Size : " /></LinearLayout>

Solution 2:

Locate the application cache folder into memory in following path

"/data/data/com.your.package.appname/cache"

Calculate the application cache size on the disk.

Post a Comment for "How To Programmatically Calculate All Cache Size Of Installed Application?"