你好,游客 登录 注册 搜索
背景:
阅读新闻

Android中获取应用程序(包)的大小-----PackageManager的使用(二)

[日期:2012-02-02] 来源:Linux社区  作者:qinjuning [字体:大 中 小]

第四步、  最后我们可以获取 pStats的属性,获得它们的属性值,通过调用系统函数Formatter.formateFileSize(long size)转换

为对应的以kb/mb为计量单位的字符串。

很重要的一点:为了能够通过反射获取应用程序大小,我们必须加入以下权限,否则,会出现警告并且得不到实际值。

 

[java]
  1. <uses-permission Android:name="android.permission.GET_PACKAGE_SIZE"></uses-permission>  


 

     流程图如下:

           

Demo说明:

              在第一部分应用得基础上,我们添加了一个新功能,点击任何一个应用后后,弹出显示该应用的包信息大小的对话框。

        截图如下:

                 工程图:                                                                                  程序效果图:

                          

1、dialg_app_size.xml 文件

[html]
  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如下:

[java]

  1. package com.qin.appsize;  
  2.   
  3.   
  4. import java.lang.reflect.Method;  
  5. import java.util.ArrayList;  
  6. import java.util.Collections;  
  7. import java.util.List;  
  8.   
  9. import com.qin.appsize.AppInfo;  
  10.   
  11. import android.app.Activity;  
  12. import android.app.AlertDialog;  
  13. import android.content.ComponentName;  
  14. import android.content.Context;  
  15. import android.content.DialogInterface;  
  16. import android.content.Intent;  
  17. import android.content.pm.IPackageStatsObserver;  
  18. import android.content.pm.PackageManager;  
  19. import android.content.pm.PackageStats;  
  20. import android.content.pm.ResolveInfo;  
  21. import android.graphics.drawable.Drawable;  
  22. import android.os.Bundle;  
  23. import android.os.RemoteException;  
  24. import android.text.format.Formatter;  
  25. import android.util.Log;  
  26. import android.view.LayoutInflater;  
  27. import android.view.View;  
  28. import android.widget.AdapterView;  
  29. import android.widget.ListView;  
  30. import android.widget.TextView;  
  31. import android.widget.AdapterView.OnItemClickListener;  
  32.   
  33. public class MainActivity extends Activity implements OnItemClickListener{  
  34.     private static String TAG = "APP_SIZE";  
  35.   
  36.     private ListView listview = null;  
  37.     private List<AppInfo> mlistAppInfo = null;  
  38.     LayoutInflater infater = null ;   
  39.     //全局变量,保存当前查询包得信息   
  40.     private long cachesize ; //缓存大小   
  41.     private long datasize  ;  //数据大小    
  42.     private long codesize  ;  //应用程序大小   
  43.     private long totalsize ; //总大小   
  44.     @Override  
  45.     public void onCreate(Bundle savedInstanceState) {  
  46.         super.onCreate(savedInstanceState);  
  47.         setContentView(R.layout.browse_app_list);  
  48.         listview = (ListView) findViewById(R.id.listviewApp);  
  49.         mlistAppInfo = new ArrayList<AppInfo>();  
  50.         queryAppInfo(); // 查询所有应用程序信息   
  51.         BrowseApplicationInfoAdapter browseAppAdapter = new BrowseApplicationInfoAdapter(  
  52.                 this, mlistAppInfo);  
  53.         listview.setAdapter(browseAppAdapter);  
  54.         listview.setOnItemClickListener(this);  
  55.     }  
  56.      // 点击弹出对话框,显示该包得大小   
  57.     public void onItemClick(AdapterView<?> arg0, View view, int position,long arg3) {  
  58.         //更新显示当前包得大小信息   
  59.         queryPacakgeSize(mlistAppInfo.get(position).getPkgName());   
  60.           
  61.         infater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  62.         View dialog = infater.inflate(R.layout.dialog_app_size, null) ;  
  63.         TextView tvcachesize =(TextView) dialog.findViewById(R.id.tvcachesize) ; //缓存大小   
  64.         TextView tvdatasize = (TextView) dialog.findViewById(R.id.tvdatasize)  ; //数据大小   
  65.         TextView tvcodesize = (TextView) dialog.findViewById(R.id.tvcodesize) ; // 应用程序大小   
  66.         TextView tvtotalsize = (TextView) dialog.findViewById(R.id.tvtotalsize) ; //总大小   
  67.         //类型转换并赋值   
  68.         tvcachesize.setText(formateFileSize(cachesize));  
  69.         tvdatasize.setText(formateFileSize(datasize)) ;  
  70.         tvcodesize.setText(formateFileSize(codesize)) ;  
  71.         tvtotalsize.setText(formateFileSize(totalsize)) ;  
  72.         //显示自定义对话框   
  73.         AlertDialog.Builder builder =new AlertDialog.Builder(MainActivity.this) ;  
  74.         builder.setView(dialog) ;  
  75.         builder.setTitle(mlistAppInfo.get(position).getAppLabel()+"的大小信息为:") ;  
  76.         builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {  
  77.   
  78.             @Override  
  79.             public void onClick(DialogInterface dialog, int which) {  
  80.                 // TODO Auto-generated method stub   
  81.                 dialog.cancel() ;  // 取消显示对话框   
  82.             }  
  83.               
  84.         });  
  85.         builder.create().show() ;  
  86.     }  
  87.     public void  queryPacakgeSize(String pkgName) throws Exception{  
  88.         if ( pkgName != null){  
  89.             //使用放射机制得到PackageManager类的隐藏函数getPackageSizeInfo   
  90.             PackageManager pm = getPackageManager();  //得到pm对象   
  91.             try {  
  92.                 //通过反射机制获得该隐藏函数   
  93.                 Method getPackageSizeInfo = pm.getClass().getDeclaredMethod("getPackageSizeInfo", String.class,IPackageStatsObserver.class);  
  94.                 //调用该函数,并且给其分配参数 ,待调用流程完成后会回调PkgSizeObserver类的函数   
  95.                 getPackageSizeInfo.invoke(pm, pkgName,new PkgSizeObserver());  
  96.             }   
  97.             catch(Exception ex){  
  98.                 Log.e(TAG, "NoSuchMethodException") ;  
  99.                 ex.printStackTrace() ;  
  100.                 throw ex ;  // 抛出异常   
  101.             }   
  102.         }  
  103.     }  
  104.      
  105.     //aidl文件形成的Bindler机制服务类   
  106.     public class PkgSizeObserver extends IPackageStatsObserver.Stub{  
  107.         /*** 回调函数, 
  108.          * @param pStatus ,返回数据封装在PackageStats对象中 
  109.          * @param succeeded  代表回调成功 
  110.          */   
  111.         @Override  
  112.         public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)  
  113.                 throws RemoteException {  
  114.             // TODO Auto-generated method stub   
  115.            cachesize = pStats.cacheSize  ; //缓存大小   
  116.             datasize = pStats.dataSize  ;  //数据大小    
  117.             codesize = pStats.codeSize  ;  //应用程序大小   
  118.             totalsize = cachesize + datasize + codesize ;  
  119.             Log.i(TAG, "cachesize--->"+cachesize+" datasize---->"+datasize+ " codeSize---->"+codesize)  ;  
  120.         }  
  121.     }  
  122.     //系统函数,字符串转换 long -String (kb)   
  123.     private String formateFileSize(long size){  
  124.         return Formatter.formatFileSize(MainActivity.this, size);   
  125.     }  
  126.    // 获得所有启动Activity的信息,类似于Launch界面   
  127.     public void queryAppInfo() {  
  128.         PackageManager pm = this.getPackageManager(); // 获得PackageManager对象   
  129.         Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);  
  130.         mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);  
  131.         // 通过查询,获得所有ResolveInfo对象.   
  132.         List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent, 0);  
  133.         // 调用系统排序 , 根据name排序   
  134.         // 该排序很重要,否则只能显示系统应用,而不能列出第三方应用程序   
  135.         Collections.sort(resolveInfos,new ResolveInfo.DisplayNameComparator(pm));  
  136.         if (mlistAppInfo != null) {  
  137.             mlistAppInfo.clear();  
  138.             for (ResolveInfo reInfo : resolveInfos) {  
  139.                 String activityName = reInfo.activityInfo.name; // 获得该应用程序的启动Activity的name   
  140.                 String pkgName = reInfo.activityInfo.packageName; // 获得应用程序的包名   
  141.                 String appLabel = (String) reInfo.loadLabel(pm); // 获得应用程序的Label   
  142.                 Drawable icon = reInfo.loadIcon(pm); // 获得应用程序图标   
  143.                 // 为应用程序的启动Activity 准备Intent   
  144.                 Intent launchIntent = new Intent();  
  145.                 launchIntent.setComponent(new ComponentName(pkgName,activityName));  
  146.                 // 创建一个AppInfo对象,并赋值   
  147.                 AppInfo appInfo = new AppInfo();  
  148.                 appInfo.setAppLabel(appLabel);  
  149.                 appInfo.setPkgName(pkgName);  
  150.                 appInfo.setAppIcon(icon);  
  151.                 appInfo.setIntent(launchIntent);  
  152.                 mlistAppInfo.add(appInfo); // 添加至列表中   
  153.             }  
  154.         }  
  155.     }  
  156. }  

获取应用程序信息大小就是这么来的,整个过程相对而言还是挺简单的,比较难理解的是AIDL文件的使用和回调函数的处理。

仔细研究后,才有所理解。

linux
相关资讯       Android开发教程 
本文评论   查看全部评论 (1)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款
第 1 楼
* 匿名 发表于 2013/8/21 15:10:34
已经没用了! 4.1