關於Android中獲取包資訊之二
通過第一部分<<Android中獲取應用程式(包)的資訊-----PackageManager的使用(一)>>的介紹,對PackageManager以及
AndroidManife.xml定義的節點資訊類XXXInfo類都有了一定的認識。
本部分的內容是如何獲取安裝包得大小,包括快取大小(cachesize)、資料大小(datasize)、應用程式大小(codesize)。
本部分的知識點涉及到AIDL、Java反射機制。理解起來也不是很難。
關於安裝包得大小資訊封裝在類中,該類很簡單,只有幾個欄位:
PackageStats類:
常用欄位:
public long cachesize 快取大小
public long codesize 應用程式大小
public long datasize 資料大小
public String packageName 包名
PS:應用程式的總大小 = cachesize + codesize + datasize
也就是說只要獲得了安裝包所對應的PackagerStats物件,就可以獲得資訊了。但是在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如下:
[java] view plaincopyprint?
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所在包名錯誤,導致報錯,應為:android.content.pm。請大家修改後執行