通过第一部分<<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()  方法原型为:

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

  

内部调用流程如下,这个知识点较为复杂,知道即可,
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 文件

package android.content.pm;  

import android.content.pm.PackageStats;
/**
* API for package data change related callbacks from the Package Manager.
* Some usage scenarios include deletion of cache directory, generate
* statistics related to code, data, cache usage(TODO)
* {@hide}
*/
oneway interface IPackageStatsObserver { void onGetStatsCompleted(in PackageStats pStats, boolean succeeded);
}

  PackageStats.aidl文件

package android.content.pm;  

parcelable PackageStats;

  

第三步、  创建一个类继承至IPackageStatsObserver.Stub (桩,)它本质上实现了Binder机制。当我们把该类的一个实例通过getPackageSizeInfo()调用时,并该函数继而启动了启动中间流程去获取相关包得信息大小,当扫描完成后,最后将查询信息回调至该类的onGetStatsCompleted(in PackageStats pStats, boolean succeeded)方法,信息大小封装在此实例上。例如:

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

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

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

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

<uses-permission android:name="android.permission.GET_PACKAGE_SIZE"></uses-permission>

     流程图如下:

Demo说明

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

  工程图:                                                                                  程序效果图:

           

1、dialg_app_size.xml 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content" android:orientation="horizontal">
<TextView android:layout_width="100dip"
android:layout_height="wrap_content" android:text="缓存大小:"></TextView>
<TextView android:layout_width="100dip" android:id="@+id/tvcachesize"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content" android:orientation="horizontal">
<TextView android:layout_width="100dip"
android:layout_height="wrap_content" android:text="数据大小:"></TextView>
<TextView android:layout_width="100dip" android:id="@+id/tvdatasize"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content" android:orientation="horizontal">
<TextView android:layout_width="100dip"
android:layout_height="wrap_content" android:text="应用程序大小:"></TextView>
<TextView android:layout_width="100dip" android:id="@+id/tvcodesize"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content" android:orientation="horizontal">
<TextView android:layout_width="100dip"
android:layout_height="wrap_content" android:text="总大小:"></TextView>
<TextView android:layout_width="100dip" android:id="@+id/tvtotalsize"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
</LinearLayout>

  

2、另外的资源文件或自定义适配器复用了第一部分,请知悉。

3、添加AIDL文件,如上。

4、主文件MainActivity.java如下:

package com.qin.appsize;  

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import com.qin.appsize.AppInfo; import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.format.Formatter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener; public class MainActivity extends Activity implements OnItemClickListener{
private static String TAG = "APP_SIZE"; private ListView listview = null;
private List<AppInfo> mlistAppInfo = null;
LayoutInflater infater = null ;
//全局变量,保存当前查询包得信息
private long cachesize ; //缓存大小
private long datasize ; //数据大小
private long codesize ; //应用程序大小
private long totalsize ; //总大小
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browse_app_list);
listview = (ListView) findViewById(R.id.listviewApp);
mlistAppInfo = new ArrayList<AppInfo>();
queryAppInfo(); // 查询所有应用程序信息
BrowseApplicationInfoAdapter browseAppAdapter = new BrowseApplicationInfoAdapter(
this, mlistAppInfo);
listview.setAdapter(browseAppAdapter);
listview.setOnItemClickListener(this);
}
// 点击弹出对话框,显示该包得大小
public void onItemClick(AdapterView<?> arg0, View view, int position,long arg3) {
//更新显示当前包得大小信息
queryPacakgeSize(mlistAppInfo.get(position).getPkgName()); infater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialog = infater.inflate(R.layout.dialog_app_size, null) ;
TextView tvcachesize =(TextView) dialog.findViewById(R.id.tvcachesize) ; //缓存大小
TextView tvdatasize = (TextView) dialog.findViewById(R.id.tvdatasize) ; //数据大小
TextView tvcodesize = (TextView) dialog.findViewById(R.id.tvcodesize) ; // 应用程序大小
TextView tvtotalsize = (TextView) dialog.findViewById(R.id.tvtotalsize) ; //总大小
//类型转换并赋值
tvcachesize.setText(formateFileSize(cachesize));
tvdatasize.setText(formateFileSize(datasize)) ;
tvcodesize.setText(formateFileSize(codesize)) ;
tvtotalsize.setText(formateFileSize(totalsize)) ;
//显示自定义对话框
AlertDialog.Builder builder =new AlertDialog.Builder(MainActivity.this) ;
builder.setView(dialog) ;
builder.setTitle(mlistAppInfo.get(position).getAppLabel()+"的大小信息为:") ;
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel() ; // 取消显示对话框
} });
builder.create().show() ;
}
public void queryPacakgeSize(String pkgName) throws Exception{
if ( pkgName != null){
//使用放射机制得到PackageManager类的隐藏函数getPackageSizeInfo
PackageManager pm = getPackageManager(); //得到pm对象
try {
//通过反射机制获得该隐藏函数
Method getPackageSizeInfo = pm.getClass().getDeclaredMethod("getPackageSizeInfo", String.class,IPackageStatsObserver.class);
//调用该函数,并且给其分配参数 ,待调用流程完成后会回调PkgSizeObserver类的函数
getPackageSizeInfo.invoke(pm, pkgName,new PkgSizeObserver());
}
catch(Exception ex){
Log.e(TAG, "NoSuchMethodException") ;
ex.printStackTrace() ;
throw ex ; // 抛出异常
}
}
} //aidl文件形成的Bindler机制服务类
public class PkgSizeObserver extends IPackageStatsObserver.Stub{
/*** 回调函数,
* @param pStatus ,返回数据封装在PackageStats对象中
* @param succeeded 代表回调成功
*/
@Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
throws RemoteException {
// TODO Auto-generated method stub
cachesize = pStats.cacheSize ; //缓存大小
datasize = pStats.dataSize ; //数据大小
codesize = pStats.codeSize ; //应用程序大小
totalsize = cachesize + datasize + codesize ;
Log.i(TAG, "cachesize--->"+cachesize+" datasize---->"+datasize+ " codeSize---->"+codesize) ;
}
}
//系统函数,字符串转换 long -String (kb)
private String formateFileSize(long size){
return Formatter.formatFileSize(MainActivity.this, size);
}
// 获得所有启动Activity的信息,类似于Launch界面
public void queryAppInfo() {
PackageManager pm = this.getPackageManager(); // 获得PackageManager对象
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// 通过查询,获得所有ResolveInfo对象.
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent, 0);
// 调用系统排序 , 根据name排序
// 该排序很重要,否则只能显示系统应用,而不能列出第三方应用程序
Collections.sort(resolveInfos,new ResolveInfo.DisplayNameComparator(pm));
if (mlistAppInfo != null) {
mlistAppInfo.clear();
for (ResolveInfo reInfo : resolveInfos) {
String activityName = reInfo.activityInfo.name; // 获得该应用程序的启动Activity的name
String pkgName = reInfo.activityInfo.packageName; // 获得应用程序的包名
String appLabel = (String) reInfo.loadLabel(pm); // 获得应用程序的Label
Drawable icon = reInfo.loadIcon(pm); // 获得应用程序图标
// 为应用程序的启动Activity 准备Intent
Intent launchIntent = new Intent();
launchIntent.setComponent(new ComponentName(pkgName,activityName));
// 创建一个AppInfo对象,并赋值
AppInfo appInfo = new AppInfo();
appInfo.setAppLabel(appLabel);
appInfo.setPkgName(pkgName);
appInfo.setAppIcon(icon);
appInfo.setIntent(launchIntent);
mlistAppInfo.add(appInfo); // 添加至列表中
}
}
}
}

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

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

关于PackageManager的使用的源代码已上传,下载地址:http://download.csdn.net/detail/qinjuning/3775856

    PS: 源码中的AIDL所在包名错误,导致报错,应为:android.content.pm。请大家修改后运行。

Android中获取应用程序(包)的大小-----PackageManager的使用(二)的更多相关文章

  1. Android中获取应用程序(包)的信息----PackageManager

    本节内容是如何获取Android系统中应用程序的信息,主要包括packagename.label.icon.占用大小等.具体分为两个 部分,计划如下:   第一部分: 获取应用程序的packagena ...

  2. Android中获取应用程序(包)的信息-----PackageManager的使用(一)

    本节内容是如何获取Android系统中应用程序的信息,主要包括packagename.label.icon.占用大小等.具体分为两个 部分,计划如下:  第一部分: 获取应用程序的packagenam ...

  3. Android中获取应用程序(包)的信息-----PackageManager的使用

    本节内容是如何获取Android系统中应用程序的信息,主要包括packagename.label.icon.占用大小等.具体分为两个 部分,计划如下: 第一部分: 获取应用程序的packagename ...

  4. 【转】Android中获取应用程序(包)的信息-----PackageManager的使用(一)

    转载请注明出处:http://blog.csdn.net/qinjuning       本节内容是如何获取Android系统中应用程序的信息,主要包括packagename.label.icon.占 ...

  5. Android中获取正在运行的应用程序-----ActivityManager.RunningAppProcessInfo类详解

    今天继续讲解关于ActivityManager的使用,通过前面一节的学习,我们学会了如何利用ActivityManager获取系统里 正在运行的进程.本文要讲解的知识点是利用这些进程信息获取系统里正在 ...

  6. Android中获取正在运行的服务-------ActivityManager.RunningServiceInfo的使用

    关于PackageManager和ActivityManager的使用 ,自己也写了一些DEMO 了,基本上写的线路参考了Settings模块下的 应用程序,大家如果真正的有所兴趣,建议大家看看源码, ...

  7. android中获取root权限的方法以及原理(转)

    一. 概述 本文介绍了android中获取root权限的方法以及原理,让大家对android 玩家中常说的“越狱”有一个更深层次的认识. 二. Root 的介绍 1. Root 的目的 可以让我们拥有 ...

  8. Android中获取系统上安装的APP信息

    Version:0.9 StartHTML:-1 EndHTML:-1 StartFragment:00000099 EndFragment:00003259 Android中获取系统上安装的APP信 ...

  9. URL转Drawable之 Android中获取网络图片的三种方法

    转载自: http://doinone.iteye.com/blog/1074283 Android中获取网络图片是一件耗时的操作,如果直接获取有可能会出现应用程序无响应(ANR:Applicatio ...

随机推荐

  1. SQL Server网络地址备份

    SQL Server网络地址备份 Ø  软件系统: SQL Server 各版本 1.问题描述: 在XX客户做SQL Server 到Oracle 数据迁移时,当时由于客户的SQL Server200 ...

  2. mysql数据库千万级别数据的查询优化和分页测试

    原文地址:原创 mysql数据库千万级别数据的查询优化和分页测试作者:于堡舰 本文为本人最近利用几个小时才分析总结出的原创文章,希望大家转载,但是要注明出处 http://blog.sina.com. ...

  3. 基本STRUTS标签-学习笔记-Logic标签

    BEAN标签(name 是从别处得来的:id是自己的,相当于变量:property相当于变量的值) 前提: String str=request.getParameter("param&qu ...

  4. MyBatis(3.2.3) - Configuring MyBatis using XML, Settings

    The default MyBatis global settings, which can be overridden to better suit application-specific nee ...

  5. Ehcache(2.9.x) - Configuration Guide, Configuring Storage Tiers

    About Storage Tiers Ehcache has three storage tiers, summarized here: Memory store – Heap memory tha ...

  6. Linux 命令 - ss: 查看套接字统计信息

    命令格式 ss [options] [ FILTER ] 命令参数 -h, --help 显示帮助信息. -V, --version 显示版本信息. -n, --numeric 不解析服务名称. -r ...

  7. CSS之拖拽库2

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or ...

  8. jquery获取文档高度和窗口高度的例子

    jquery获取文档高度和窗口高度,$(document).height().$(window).height() $(document).height():整个网页的文档高度 $(window).h ...

  9. PHP学习笔记 - 进阶篇(7)

    PHP学习笔记 - 进阶篇(7) 文件操作 读取文件内容 PHP具有丰富的文件操作函数,最简单的读取文件的函数为file_get_contents,可以将整个文件全部读取到一个字符串中. $conte ...

  10. Windows 右键添加「cmd 打开」

    1. 2. 3. 参考: 1.Windows右键添加"使用CMD打开" 2.WIN7.WIN8 右键在目录当前打开命令行Cmd窗口(图文)