(转载) 清理缓存 IPackageStatsObserver

时间:2023-03-08 22:08:54
2016-04-10 13:40 2288人阅读 评论(0) 收藏 举报
(转载) 清理缓存 IPackageStatsObserver 分类:
android(59) (转载) 清理缓存 IPackageStatsObserver

版权声明:本文为博主原创文章,未经博主允许不得转载。

目录(?)[+]

现在的位置: 首页 > 综合 > 正文

http://www.xuebuyuan.com/901153.html

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

2013年09月22日 ⁄ 综合 ⁄ 共 20231字 ⁄ 字号    ⁄ 评论关闭

通过第一部分<<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. package android.content.pm;
  2. import android.content.pm.PackageStats;
  3. /**
  4. * API for package data change related callbacks from the Package Manager.
  5. * Some usage scenarios include deletion of cache directory, generate
  6. * statistics related to code, data, cache usage(TODO)
  7. * {@hide}
  8. */
  9. oneway interface IPackageStatsObserver {
  10. void onGetStatsCompleted(in PackageStats pStats, boolean succeeded);
  11. }

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>

     流程图如下:

(转载) 清理缓存 IPackageStatsObserver

Demo说明

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

截图如下:

  工程图:                                                                                  程序效果图:

(转载) 清理缓存 IPackageStatsObserver           (转载) 清理缓存 IPackageStatsObserver

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(
  46. this, mlistAppInfo);
  47. listview.setAdapter(browseAppAdapter);
  48. listview.setOnItemClickListener(this);
  49. }
  50. // 点击弹出对话框,显示该包得大小
  51. public void onItemClick(AdapterView<?> arg0, View view, int position,long arg3) {
  52. //更新显示当前包得大小信息
  53. queryPacakgeSize(mlistAppInfo.get(position).getPkgName());
  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. public void  queryPacakgeSize(String pkgName) throws Exception{
  79. if ( pkgName != null){
  80. //使用放射机制得到PackageManager类的隐藏函数getPackageSizeInfo
  81. PackageManager pm = getPackageManager();  //得到pm对象
  82. try {
  83. //通过反射机制获得该隐藏函数
  84. Method getPackageSizeInfo = pm.getClass().getDeclaredMethod("getPackageSizeInfo", String.class,IPackageStatsObserver.class);
  85. //调用该函数,并且给其分配参数 ,待调用流程完成后会回调PkgSizeObserver类的函数
  86. getPackageSizeInfo.invoke(pm, pkgName,new PkgSizeObserver());
  87. }
  88. catch(Exception ex){
  89. Log.e(TAG, "NoSuchMethodException") ;
  90. ex.printStackTrace() ;
  91. throw ex ;  // 抛出异常
  92. }
  93. }
  94. }
  95. //aidl文件形成的Bindler机制服务类
  96. public class PkgSizeObserver extends IPackageStatsObserver.Stub{
  97. /*** 回调函数,
  98. * @param pStatus ,返回数据封装在PackageStats对象中
  99. * @param succeeded  代表回调成功
  100. */
  101. @Override
  102. public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
  103. throws RemoteException {
  104. // TODO Auto-generated method stub
  105. cachesize = pStats.cacheSize  ; //缓存大小
  106. datasize = pStats.dataSize  ;  //数据大小
  107. codesize = pStats.codeSize  ;  //应用程序大小
  108. totalsize = cachesize + datasize + codesize ;
  109. Log.i(TAG, "cachesize--->"+cachesize+" datasize---->"+datasize+ " codeSize---->"+codesize)  ;
  110. }
  111. }
  112. //系统函数,字符串转换 long -String (kb)
  113. private String formateFileSize(long size){
  114. return Formatter.formatFileSize(MainActivity.this, size);
  115. }
  116. // 获得所有启动Activity的信息,类似于Launch界面
  117. public void queryAppInfo() {
  118. PackageManager pm = this.getPackageManager(); // 获得PackageManager对象
  119. Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
  120. mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
  121. // 通过查询,获得所有ResolveInfo对象.
  122. List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent, 0);
  123. // 调用系统排序 , 根据name排序
  124. // 该排序很重要,否则只能显示系统应用,而不能列出第三方应用程序
  125. Collections.sort(resolveInfos,new ResolveInfo.DisplayNameComparator(pm));
  126. if (mlistAppInfo != null) {
  127. mlistAppInfo.clear();
  128. for (ResolveInfo reInfo : resolveInfos) {
  129. String activityName = reInfo.activityInfo.name; // 获得该应用程序的启动Activity的name
  130. String pkgName = reInfo.activityInfo.packageName; // 获得应用程序的包名
  131. String appLabel = (String) reInfo.loadLabel(pm); // 获得应用程序的Label
  132. Drawable icon = reInfo.loadIcon(pm); // 获得应用程序图标
  133. // 为应用程序的启动Activity 准备Intent
  134. Intent launchIntent = new Intent();
  135. launchIntent.setComponent(new ComponentName(pkgName,activityName));
  136. // 创建一个AppInfo对象,并赋值
  137. AppInfo appInfo = new AppInfo();
  138. appInfo.setAppLabel(appLabel);
  139. appInfo.setPkgName(pkgName);
  140. appInfo.setAppIcon(icon);
  141. appInfo.setIntent(launchIntent);
  142. mlistAppInfo.add(appInfo); // 添加至列表中
  143. }
  144. }
  145. }
  146. }

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

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

package com.itheima.mobilesafe74.activity;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Random;

import com.itheima.mobilesafe74.R;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

public class CacheClearActivity extends Activity {
protected static final int UPDATE_CACHE_APP = 100;
protected static final int CHECK_CACHE_APP = 101;
protected static final int CHECK_FINISH = 102;
protected static final int CLEAR_CACHE = 103;
protected static final String tag = "CacheClearActivity";

private Button bt_clear;
private ProgressBar pb_bar;
private TextView tv_name;
private LinearLayout ll_add_text;
private PackageManager mPm;
private int mIndex = 0;

private Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_CACHE_APP:
//8.在线性布局中添加有缓存应用条目
View view = View.inflate(getApplicationContext(), R.layout.linearlayout_cache_item, null);

ImageView iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
TextView tv_item_name = (TextView) view.findViewById(R.id.tv_name);
TextView tv_memory_info = (TextView)view.findViewById(R.id.tv_memory_info);
ImageView iv_delete = (ImageView) view.findViewById(R.id.iv_delete);

final CacheInfo cacheInfo = (CacheInfo) msg.obj;
iv_icon.setBackgroundDrawable(cacheInfo.icon);
tv_item_name.setText(cacheInfo.name);
tv_memory_info.setText(Formatter.formatFileSize(getApplicationContext(), cacheInfo.cacheSize));

ll_add_text.addView(view, 0);

iv_delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//清除单个选中应用的缓存内容(PackageMananger)

/* 以下代码如果要执行成功则需要系统应用才可以去使用的权限
* android.permission.DELETE_CACHE_FILES
* try {
Class<?> clazz = Class.forName("android.content.pm.PackageManager");
//2.获取调用方法对象
Method method = clazz.getMethod("deleteApplicationCacheFiles", String.class,IPackageDataObserver.class);
//3.获取对象调用方法
method.invoke(mPm, cacheInfo.packagename,new IPackageDataObserver.Stub() {
@Override
public void onRemoveCompleted(String packageName, boolean succeeded)
throws RemoteException {
//删除此应用缓存后,调用的方法,子线程中
Log.i(tag, "onRemoveCompleted.....");
}
});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//源码开发课程(源码(handler机制,AsyncTask(异步请求,手机启动流程)源码))
//通过查看系统日志,获取开启清理缓存activity中action和data
Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.parse("package:"+cacheInfo.packagename));
startActivity(intent);
}
});
break;
case CHECK_CACHE_APP:
tv_name.setText((String)msg.obj);
break;
case CHECK_FINISH:
tv_name.setText("扫描完成");
break;
case CLEAR_CACHE:
//从线性布局中移除所有的条目
ll_add_text.removeAllViews();
break;
}
};
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cache_clear);
initUI();
initData();
}

/**
* 遍历手机所有的应用,获取有缓存的应用,用作显示
*/
private void initData() {
new Thread(){
public void run() {
//1.获取包管理者对象

mPm = getPackageManager();

//2.获取安装在手机上的所有的应用
List<PackageInfo> installedPackages = mPm.getInstalledPackages(0);
//3.给进度条设置最大值(手机中所有应用的总数)
pb_bar.setMax(installedPackages.size());
//4.遍历每一个应用,获取有缓存的应用信息(应用名称,图标,缓存大小,包名)
for (PackageInfo packageInfo : installedPackages) {
//包名作为获取缓存信息的条件
String packageName = packageInfo.packageName;
getPackageCache(packageName);

try {
Thread.sleep(100+new Random().nextInt(50));
} catch (InterruptedException e) {
e.printStackTrace();
}
mIndex++;
pb_bar.setProgress(mIndex);

//每循环一次就将检测应用的名称发送给主线程显示
Message msg = Message.obtain();
msg.what = CHECK_CACHE_APP;
String name = null;
try {
name = mPm.getApplicationInfo(packageName, 0).loadLabel(mPm).toString();
} catch (NameNotFoundException e) {
e.printStackTrace();
}
msg.obj = name;
mHandler.sendMessage(msg);
}
Message msg = Message.obtain();
msg.what = CHECK_FINISH;
mHandler.sendMessage(msg);
};
}.start();
}

class CacheInfo{
public String name;
public Drawable icon;
public String packagename;
public long cacheSize;
}

/**通过包名获取此包名指向应用的缓存信息
* @param packageName
应用包名
*/
protected void getPackageCache(String packageName) {
IPackageStatsObserver.Stub mStatsObserver = new IPackageStatsObserver.Stub() {

public void onGetStatsCompleted(PackageStats stats,
boolean succeeded) {
//子线程中方法,用到消息机制

//4.获取指定包名的缓存大小
long cacheSize = stats.cacheSize;
//5.判断缓存大小是否大于0
if(cacheSize>0){
//6.告知主线程更新UI
Message msg = Message.obtain();
msg.what = UPDATE_CACHE_APP;
CacheInfo cacheInfo = null;
try {
//7.维护有缓存应用的javabean
cacheInfo = new CacheInfo();
cacheInfo.cacheSize = cacheSize;
cacheInfo.packagename = stats.packageName;
cacheInfo.name = mPm.getApplicationInfo(stats.packageName, 0).loadLabel(mPm).toString();
cacheInfo.icon = mPm.getApplicationInfo(stats.packageName, 0).loadIcon(mPm);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
msg.obj = cacheInfo;
mHandler.sendMessage(msg);
}
}
};
//1.获取指定类的字节码文件
try {
Class<?> clazz = Class.forName("android.content.pm.PackageManager");
//2.获取调用方法对象
Method method = clazz.getMethod("getPackageSizeInfo", String.class,IPackageStatsObserver.class);
//3.获取对象调用方法
method.invoke(mPm, packageName,mStatsObserver);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private void initUI() {
bt_clear = (Button) findViewById(R.id.bt_clear);
pb_bar = (ProgressBar) findViewById(R.id.pb_bar);
tv_name = (TextView) findViewById(R.id.tv_name);
ll_add_text = (LinearLayout) findViewById(R.id.ll_add_text);

bt_clear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//1.获取指定类的字节码文件
try {
Class<?> clazz = Class.forName("android.content.pm.PackageManager");
//2.获取调用方法对象
Method method = clazz.getMethod("freeStorageAndNotify", long.class,IPackageDataObserver.class);
//3.获取对象调用方法
method.invoke(mPm, Long.MAX_VALUE,new IPackageDataObserver.Stub() {
@Override
public void onRemoveCompleted(String packageName, boolean succeeded)
throws RemoteException {
//清除缓存完成后调用的方法(考虑权限)
Message msg = Message.obtain();
msg.what = CLEAR_CACHE;
mHandler.sendMessage(msg);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}

1
0
  相关文章推荐
查看评论
  暂无评论
您还没有登录,请[登录][注册]
* 以上用户言论只代表其个人观点,不代表****网站的观点或立场