TShopping

 找回密碼
 註冊
搜索
查看: 1870|回復: 0
打印 上一主題 下一主題

[教學] Android4以上獲取應用程序(包)的大小-PackageManager使用(二)

[複製鏈接]
跳轉到指定樓層
1#
發表於 2014-11-29 00:41:28 | 只看該作者 |只看大圖 回帖獎勵 |倒序瀏覽 |閱讀模式
 
Push to Facebook

          通過第一部分<< Android中獲取應用程序(包)的信息-----PackageManager的使用(一) >>的介紹,對PackageManager以及AndroidManife.xml定義的節點信息類XXXInfo類都有了一定的認識。

          本部分的內容是如何獲取安裝包得大小,包括緩存大小( cachesize)、數據大小(datasize)、應用程序大小(codesize)。

本部分的知識點涉及到AIDL、Java反射機制。理解起來也不是很難。

   

          關於安裝包得大小信息封裝在PackageStats類中,該類很簡單,只有幾個字段:

                PackageStats類:

                 常用字段:

                             public long cachesize 緩存大小

                             public long codesize 應用程序大小

                             public long datasize 數據大小

                             public String packageName 包名

         PS:應用程序的總大小= cachesize + codesize + datasize


        也就是說只要獲得了安裝包所對應的PackageStats對象,就可以獲得信息了。但是在AndroidSDK中並沒有顯示提供方法來

獲得該對象,是不是很苦惱呢?但是,我們可以通過放射機制來調用系統中隱藏的函數( @hide )來獲得每個安裝包得信息。

具體方法如下:


       第一步、通過放射機制調用getPackageSizeInfo ()方法原型為:  

  1. /*@param packageName 应用程序包名
  2.      *@param observer    当查询包得信息大小操作完成后,将回调给IPackageStatsObserver类中的onGetStatsCompleted()方法,
  3.      *      ,并且我们需要的PackageStats对象也封装在其参数里.
  4.      * @hide //隐藏函数的标记
  5.      */
  6.        public abstract void getPackageSizeInfo(String packageName,IPackageStatsObserver observer);{
  7.                //
  8.        }
複製代碼

內部調用流程如下,這個知識點較為複雜,知道即可,

         getPackageSizeInfo方法內部調用getPackageSizeInfoLI(packageName, pStats)方法來完成包狀態獲取。

getPackageSizeInfoLI方法內部調用Installer.getSizeInfo(String pkgName, String apkPath,String fwdLockApkPath, PackageStats

pStats),繼而將包狀態信息返回給參數pStats。

         getSizeInfo這個方法內部是以本機Socket方式連接到Server,然後向server發送一個文本字符串命令,格式:getsize apkPath fwdLockApkPath 給server。

        Server將結果返回,並解析到pStats中。掌握這個調用知識鏈即可。


     第二步、由於需要獲得系統級的服務或類,我們必須加入Android系統形成的AIDL文件,共兩個:

             IPackageStatsObserver.aidl 和PackageStats.aidl文件。並將其放置在android.pm.content包路徑下。

   IPackageStatsObserver.aidl 文件

  1. /*@param packageName 应用程序包名
  2.      *@param observer    当查询包得信息大小操作完成后,将回调给IPackageStatsObserver类中的onGetStatsCompleted()方法,
  3.      *      ,并且我们需要的PackageStats对象也封装在其参数里.
  4.      * @hide //隐藏函数的标记
  5.      */
  6.        public abstract void getPackageSizeInfo(String packageName,IPackageStatsObserver observer);{
  7.                //
  8.        }
複製代碼

PackageStats.aidl文件

  1. package android.content.pm;
  2. parcelable PackageStats;
複製代碼

第三步、創建一個類繼承至IPackageStatsObserver.Stub (樁,)它本質上實現了Binder機制。當我們把該類的一個實例通過getPackageSizeInfo()調用時,並該函數繼而啟動了啟動中間流程去獲取相關包得信息大小,當掃描完成後,最後將查詢信息回調至該類的onGetStatsCompleted(in PackageStats pStats, boolean succeeded)方法,信息大小封裝在此實例上。

例如:

  1. //aidl文件形成的Bindler机制服务类
  2.     public class PkgSizeObserver extends IPackageStatsObserver.Stub{
  3.         /*** 回调函数,
  4.          * @param pStatus ,返回数据封装在PackageStats对象中
  5.          * @param succeeded  代表回调成功
  6.          */
  7.         @Override
  8.         public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
  9.                         throws RemoteException {
  10.            // TODO Auto-generated method stub
  11.            cachesize = pStats.cacheSize  ; //缓存大小
  12.            datasize = pStats.codeSize  ;  //数据大小
  13.            codesize =        pStats.codeSize  ;  //应用程序大小
  14.       }
  15.    }
複製代碼

第四步、最後我們可以獲取pStats的屬性,獲得它們的屬性值,通過調用系統函數Formatter.formateFileSize(long size)轉換為對應的以kb/mb為計量單位的字符串。


     很重要的一點:為了能夠通過反射獲取應用程序大小,我們必須加入以下權限,否則,會出現警告並且得不到實際值。

  1. <uses-permission android:name="android.permission.GET_PACKAGE_SIZE"></uses-permission>
複製代碼

  流程圖如下:

            


Demo說明

              在第一部分應用得基礎上,我們添加了一個新功能,點擊任何一個應用後後,彈出顯示該應用的包信息大小的對話框。

        截圖如下:

                 工程圖: 程序效果圖:

               

           


1、dialg_app_size.xml 文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.         android:orientation="vertical" android:layout_width="wrap_content"
  4.         android:layout_height="wrap_content">
  5.         <LinearLayout android:layout_width="wrap_content"
  6.                 android:layout_height="wrap_content" android:orientation="horizontal">
  7.                 <TextView android:layout_width="100dip"
  8.                         android:layout_height="wrap_content" android:text="缓存大小:"></TextView>
  9.                 <TextView android:layout_width="100dip" android:id="@+id/tvcachesize"
  10.                         android:layout_height="wrap_content"></TextView>
  11.         </LinearLayout>
  12.         <LinearLayout android:layout_width="wrap_content"
  13.                 android:layout_height="wrap_content" android:orientation="horizontal">
  14.                 <TextView android:layout_width="100dip"
  15.                         android:layout_height="wrap_content" android:text="数据大小:"></TextView>
  16.                 <TextView android:layout_width="100dip" android:id="@+id/tvdatasize"
  17.                         android:layout_height="wrap_content"></TextView>
  18.         </LinearLayout>
  19.         <LinearLayout android:layout_width="wrap_content"
  20.                 android:layout_height="wrap_content" android:orientation="horizontal">
  21.                 <TextView android:layout_width="100dip"
  22.                         android:layout_height="wrap_content" android:text="应用程序大小:"></TextView>
  23.                 <TextView android:layout_width="100dip" android:id="@+id/tvcodesize"
  24.                         android:layout_height="wrap_content"></TextView>
  25.         </LinearLayout>
  26.         <LinearLayout android:layout_width="wrap_content"
  27.                 android:layout_height="wrap_content" android:orientation="horizontal">
  28.                 <TextView android:layout_width="100dip"
  29.                         android:layout_height="wrap_content" android:text="总大小:"></TextView>
  30.                 <TextView android:layout_width="100dip" android:id="@+id/tvtotalsize"
  31.                         android:layout_height="wrap_content"></TextView>
  32.         </LinearLayout>
  33. </LinearLayout>
複製代碼

  2、另外的資源文件或自定義適配器復用了第一部分,請知悉。

  3、添加AIDL文件,如上。

  4、主文件MainActivity.java如下:

  1. package com.qin.appsize;

  2. import java.lang.reflect.Method;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.List;
  6. import com.qin.appsize.AppInfo;
  7. import android.app.Activity;
  8. import android.app.AlertDialog;
  9. import android.content.ComponentName;
  10. import android.content.Context;
  11. import android.content.DialogInterface;
  12. import android.content.Intent;
  13. import android.content.pm.IPackageStatsObserver;
  14. import android.content.pm.PackageManager;
  15. import android.content.pm.PackageStats;
  16. import android.content.pm.ResolveInfo;
  17. import android.graphics.drawable.Drawable;
  18. import android.os.Bundle;
  19. import android.os.RemoteException;
  20. import android.text.format.Formatter;
  21. import android.util.Log;
  22. import android.view.LayoutInflater;
  23. import android.view.View;
  24. import android.widget.AdapterView;
  25. import android.widget.ListView;
  26. import android.widget.TextView;
  27. import android.widget.AdapterView.OnItemClickListener;

  28. public class MainActivity extends Activity implements OnItemClickListener{
  29.     private static String TAG = "APP_SIZE";

  30.         private ListView listview = null;
  31.         private List<AppInfo> mlistAppInfo = null;
  32.         LayoutInflater infater = null ;
  33.         //全局变量,保存当前查询包得信息
  34.         private long cachesize ; //缓存大小
  35.         private long datasize  ;  //数据大小
  36.         private long codesize  ;  //应用程序大小
  37.         private long totalsize ; //总大小
  38.     @Override
  39.     public void onCreate(Bundle savedInstanceState) {
  40.         super.onCreate(savedInstanceState);
  41.         setContentView(R.layout.browse_app_list);
  42.         listview = (ListView) findViewById(R.id.listviewApp);
  43.                 mlistAppInfo = new ArrayList<AppInfo>();
  44.                 queryAppInfo(); // 查询所有应用程序信息
  45.                 BrowseApplicationInfoAdapter browseAppAdapter = new BrowseApplicationInfoAdapter(this, mlistAppInfo);
  46.                 listview.setAdapter(browseAppAdapter);
  47.                 listview.setOnItemClickListener(this);
  48.     }
  49.      // 点击弹出对话框,显示该包得大小
  50.         public void onItemClick(AdapterView<?> arg0, View view, int position,long arg3) {
  51.         //更新显示当前包得大小信息
  52.                 queryPacakgeSize(mlistAppInfo.get(position).getPkgName());
  53.         
  54.                 infater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  55.                 View dialog = infater.inflate(R.layout.dialog_app_size, null) ;
  56.                 TextView tvcachesize =(TextView) dialog.findViewById(R.id.tvcachesize) ; //缓存大小
  57.                 TextView tvdatasize = (TextView) dialog.findViewById(R.id.tvdatasize)  ; //数据大小
  58.                 TextView tvcodesize = (TextView) dialog.findViewById(R.id.tvcodesize) ; // 应用程序大小
  59.                 TextView tvtotalsize = (TextView) dialog.findViewById(R.id.tvtotalsize) ; //总大小
  60.                 //类型转换并赋值
  61.                 tvcachesize.setText(formateFileSize(cachesize));
  62.                 tvdatasize.setText(formateFileSize(datasize)) ;
  63.                 tvcodesize.setText(formateFileSize(codesize)) ;
  64.                 tvtotalsize.setText(formateFileSize(totalsize)) ;
  65.                 //显示自定义对话框
  66.                 AlertDialog.Builder builder =new AlertDialog.Builder(MainActivity.this) ;
  67.                 builder.setView(dialog) ;
  68.                 builder.setTitle(mlistAppInfo.get(position).getAppLabel()+"的大小信息为:") ;
  69.                 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

  70.                         @Override
  71.                         public void onClick(DialogInterface dialog, int which) {
  72.                                 // TODO Auto-generated method stub
  73.                                 dialog.cancel() ;  // 取消显示对话框
  74.                         }
  75.                 });
  76.                 builder.create().show() ;
  77.         }

  78.     //Android 4.2以上有修正,舊有方法不適用
  79.     public void  queryPacakgeSize(String pkgName) throws Exception{
  80.         if ( pkgName != null) {
  81.             PackageManager pm = getPackageManager();
  82.             Method getPackageSizeInfo = pm.getClass().getMethod("getPackageSizeInfo", String.class, IPackageStatsObserver.class);
  83.             getPackageSizeInfo.invoke(pm, pkgName, new IPackageStatsObserver.Stub() {
  84.                 @Override
  85.                 public void onGetStatsCompleted(PackageStats pStats, boolean succeeded) throws RemoteException {
  86.                     cachesize = pStats.cacheSize  ; //缓存大小
  87.                     datasize = pStats.dataSize  ;  //数据大小
  88.                     codesize = pStats.codeSize  ;  //应用程序大小
  89.                     totalsize = cachesize + datasize + codesize ;
  90.                     Log.i("TAG", "cachesize--->"+cachesize+" datasize---->"+datasize+ " codeSize---->"+codesize)  ;
  91.                 }
  92.             });
  93.         }
  94.     }
  95.     //Android 4以上有修正,舊有方法不適用
  96.     /*
  97.     //aidl文件形成的Bindler机制服务类
  98.     public class PkgSizeObserver extends IPackageStatsObserver.Stub{
  99.         /*** 回调函数,
  100.          * @param pStatus ,返回数据封装在PackageStats对象中
  101.          * @param succeeded  代表回调成功
  102.          */
  103.                 @Override
  104.               public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
  105.                   throws RemoteException {
  106.                         // TODO Auto-generated method stub
  107.                     cachesize = pStats.cacheSize  ; //缓存大小
  108.                     datasize = pStats.dataSize  ;  //数据大小
  109.                     codesize = pStats.codeSize  ;  //应用程序大小
  110.                     totalsize = cachesize + datasize + codesize ;
  111.                         Log.i(TAG, "cachesize--->"+cachesize+" datasize---->"+datasize+ " codeSize---->"+codesize)  ;
  112.                 }
  113.     }
  114.     */
  115.     //Android 4以上有修正,舊有方法不適用

  116.     //系统函数,字符串转换 long -String (kb)
  117.     private String formateFileSize(long size){
  118.             return Formatter.formatFileSize(MainActivity.this, size);
  119.     }
  120.    // 获得所有启动Activity的信息,类似于Launch界面
  121.         public void queryAppInfo() {
  122.                 PackageManager pm = this.getPackageManager(); // 获得PackageManager对象
  123.                 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
  124.                 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
  125.                 // 通过查询,获得所有ResolveInfo对象.
  126.                 List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent, 0);
  127.                 // 调用系统排序 , 根据name排序
  128.                 // 该排序很重要,否则只能显示系统应用,而不能列出第三方应用程序
  129.                 Collections.sort(resolveInfos,new ResolveInfo.DisplayNameComparator(pm));
  130.                 if (mlistAppInfo != null) {
  131.                         mlistAppInfo.clear();
  132.                         for (ResolveInfo reInfo : resolveInfos) {
  133.                                 String activityName = reInfo.activityInfo.name; // 获得该应用程序的启动Activity的name
  134.                                 String pkgName = reInfo.activityInfo.packageName; // 获得应用程序的包名
  135.                                 String appLabel = (String) reInfo.loadLabel(pm); // 获得应用程序的Label
  136.                                 Drawable icon = reInfo.loadIcon(pm); // 获得应用程序图标
  137.                                 // 为应用程序的启动Activity 准备Intent
  138.                                 Intent launchIntent = new Intent();
  139.                                 launchIntent.setComponent(new ComponentName(pkgName,activityName));
  140.                                 // 创建一个AppInfo对象,并赋值
  141.                                 AppInfo appInfo = new AppInfo();
  142.                                 appInfo.setAppLabel(appLabel);
  143.                                 appInfo.setPkgName(pkgName);
  144.                                 appInfo.setAppIcon(icon);
  145.                                 appInfo.setIntent(launchIntent);
  146.                                 mlistAppInfo.add(appInfo); // 添加至列表中
  147.                         }
  148.                 }
  149.         }
  150. }
複製代碼

獲取應用程序信息大小就是這麼來的,整個過程相對而言還是挺簡單的,比較難理解的是AIDL文件的使用和回調函數的處理。

仔細研究後,才有所理解。


上方加入
  1. import android.content.pm.IPackageStatsObserver;  
複製代碼

       關於PackageManager的使用的源代碼已上傳,下載地址:http://download.csdn.net/detail/qinjuning/3775856

    PS:源碼中的AIDL所在包名錯誤,導致報錯,應為:android.content.pm。請大家修改後運行。

         把getDeclaredMethod()改成getMethod()
可用. 4.3的系統.



轉帖:http://blog.csdn.net/qinjuning/article/details/6892054



 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-4-27 04:37 , Processed in 0.106777 second(s), 25 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表