如何以编程方式计算已安装的应用程序的所有缓存的大小? [英] How to programmatically calculate all cache size of installed application?

查看:271
本文介绍了如何以编程方式计算已安装的应用程序的所有缓存的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想表明与高速缓存大小所有已安装的应用程序名称的列表。缓存大小必须与本地的设置应用展现在Android设备上。

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.

我可以列出所有已安装的应用程序PKG名称,但不能计算出高速缓存大小相同而本机的设置应用展(IM谈论的地方,在设置清除缓存选项)。

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));
                    } 

我用这个code,但它会给我的应用程序的apk文件大小。 :( 请帮忙 在此先感谢。

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

推荐答案

要获得所安装应用程序的缓存大小直接不能得到的。 作为使用<一个href="http://developer.android.com/reference/android/content/pm/PackageManager.html">PackageManger我们不能这样使用的 getPackageSizeInfo 方法的细节是直接无法访问:// www.oracle.com/technetwork/articles/java/javareflection-1536171.html">Java反射 可以调用it.It可能无法正常工作,如果将来方法名称变更或任何事情改变了。

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.

您需要创建AIDL <一个href="http://grep$c$c.com/file/repository.grep$c$c.com/java/ext/com.google.android/android/2.0_r1/android/content/pm/IPackageStatsObserver.java#IPackageStatsObserver">IPackageStatsObserver.aidl &放大器; <一href="http://grep$c$c.com/file/repository.grep$c$c.com/java/ext/com.google.android/android/2.0_r1/android/content/pm/PackageStats.java#PackageStats">PackageStats.aidl这应该是在 android.content.pm 包,你不能直接访问它们。

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无论把它放在 android.content.pm 包。 IDataStatus

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

活动

    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>

这篇关于如何以编程方式计算已安装的应用程序的所有缓存的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆