Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 installed application pkg name but can't calculate same cache size which native setting application show(i m talking about that place where clear cache option in setting).

pkNames = getPackageManager().getInstalledPackages(0);

                    ArrayAdapter<PackageInfo> adapter = new ArrayAdapter<PackageInfo>(this,
                            android.R.layout.simple_list_item_1, pkNames);
                     final PackageManager pm = getPackageManager();
                    for(int i =0;i<pkNames.size();i++)
                    {
                        ApplicationInfo applicationInfo = pm.getApplicationInfo(pkNames.get(i).packageName.toString(), 0);
                        File file = new File(applicationInfo.publicSourceDir);
                        long size = file.length();
                        System.out.println("application name == "+pkNames.get(i).packageName.toString()+"  ,and size of cache is == "+size(this, size));
                    } 

I use this code but it will give me .apk size of that application. :( Please help thanks in advance.

like image 925
Bhanu Sharma Avatar asked Dec 12 '22 01:12

Bhanu Sharma


1 Answers

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 interface IPackageStatsObserver {
void onGetStatsCompleted(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

public interface IDataStatus {
    public void onStatusListner(String msg);
}

Activity

    public class MyScreen extends Activity implements OnClickListener {
    public static final int FETCH_PACKAGE_SIZE_COMPLETED = 100;
    public static final int ALL_PACAGE_SIZE_COMPLETED = 200;
    IDataStatus onIDataStatus;
    TextView lbl_cache_size;
    ProgressDialog pd;

    @Override
    public void onCreate(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();
    }

    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() {
        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:
                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);
            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;
        }
    }

}

AppDetails

public class AppDetails {
    Activity mActivity;
    public ArrayList<PackageInfoStruct> res = new ArrayList<PackageInfoStruct>();
    public ListView list;
    public String app_labels[];

    public AppDetails(Activity mActivity) {
        this.mActivity = mActivity;

    }

    public ArrayList<PackageInfoStruct> getPackages() {
        ArrayList<PackageInfoStruct> apps = getInstalledApps(false); /*
                                                                     * false =
                                                                     * no system
                                                                     * packages
                                                                     */
        final int max = apps.size();
        for (int i = 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 = new String[packs.size()];
        } catch (Exception e) {
            Toast.makeText(mActivity.getApplicationContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
        for (int i = 0; i < packs.size(); i++) {
            PackageInfo p = packs.get(i);
            if ((!getSysPackages) && (p.versionName == null)) {
                continue;
            }
            PackageInfoStruct newInfo = new PackageInfoStruct();
            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;
    }

    class PackageInfoStruct {
        String appname = "";
        String pname = "";
        String versionName = "";
        int versionCode = 0;
        Drawable icon;
        String datadir = "";
    }
}

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

  <Button
        android:id="@+id/btn_get_cacheSize"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Get Cache Size" />

    <TextView
        android:id="@+id/lbl_cache_size"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Cache Size : " />

</LinearLayout>
like image 181
user1140237 Avatar answered Jan 21 '23 00:01

user1140237