等。除此之外,還提供了一個PackageManger管理類,它的主要職責是管理應用程序包。 通過它,我們就可以獲取應用程序信息。
引入: AnroidManifest.xml文件節點說明:
一、相關類的介紹
PackageItemInfo類
說明: AndroidManifest.xml文件中所有節點的基類,提供了這些節點的基本信息:a label、icon、 meta-data。它並不
直接使用,而是由子類繼承然後調用相應方法。
常用字段:
public int icon 獲得該資源圖片在R文件中的值 (對應於android:icon屬性)
public int labelRes 獲得該label在R文件中的值(對應於android:label屬性)
public String name 獲得該節點的name值 (對應於android:name屬性)
public String packagename 獲得該應用程序的包名 (對應於android:packagename屬性)
常用方法:
Drawable loadIcon(PackageManager pm) 獲得當前應用程序的圖像
CharSequence loadLabel(PackageManager pm) 獲得當前應用程序的label
ActivityInfo類 繼承自 PackageItemInfo
說明: 獲得應用程序中<activity/>或者 <receiver />節點的信息 。我們可以通過它來獲取我們設置的任何屬性,包括
theme 、launchMode、launchmode等
常用方法繼承至PackageItemInfo類中的loadIcon()和loadLabel()
ServiceInfo 類
說明: 同ActivityInfo類似 ,同樣繼承自 PackageItemInfo,只不過它表示的是<service>節點信息。
ApplicationInfo類 繼承自 PackageItemInfo
說明:獲取一個特定引用程序中<application>節點的信息。
字段說明:
flags字段: FLAG_SYSTEM 系統應用程序
FLAG_EXTERNAL_STORAGE 表示該應用安裝在sdcard中
常用方法繼承至PackageItemInfo類中的loadIcon()和loadLabel()
ResolveInfo類
說明:根據<intent>節點來獲取其上一層目錄的信息,通常是<activity>、<receiver>、<service>節點信息。
常用字段:
public ActivityInfo activityInfo 獲取 ActivityInfo對象,即<activity>或<receiver >節點信息
public ServiceInfo serviceInfo 獲取 ServiceInfo對象,即<activity>節點信息
常用方法:
Drawable loadIcon(PackageManager pm) 獲得當前應用程序的圖像
CharSequence loadLabel(PackageManager pm) 獲得當前應用程序的label
PackageInfo類
說明:手動獲取AndroidManifest.xml文件的信息 。
常用字段:
public String packageName 包名
public ActivityInfo[] activities 所有<activity>節點信息
public ApplicationInfo applicationInfo <application>節點信息,只有一個
public ActivityInfo[] receivers 所有<receiver>節點信息,多個
public ServiceInfo[] services 所有<service>節點信息 ,多個
PackageManger 類
說明: 獲得已安裝的應用程序信息 。可以通過getPackageManager()方法獲得。
常用方法:
public abstract PackageManager getPackageManager()
功能:獲得一個PackageManger對象
public abstrac tDrawable getApplicationIcon(StringpackageName)
參數: packageName 包名
功能:返回給定包名的圖標,否則返回null
public abstract ApplicationInfo getApplicationInfo(String packageName, int flags)
參數:packagename 包名
flags 該ApplicationInfo是此flags標記,通常可以直接賦予常數0即可
功能:返回該ApplicationInfo對象
public abstract List<ApplicationInfo> getInstalledApplications(int flags)
參數:flag爲一般爲GET_UNINSTALLED_PACKAGES,那麼此時會返回所有ApplicationInfo。我們可以對ApplicationInfo
的flags過濾,得到我們需要的。
功能:返回給定條件的所有PackageInfo
public abstract List<PackageInfo> getInstalledPackages(int flags)
參數如上
功能:返回給定條件的所有PackageInfo
public abstractResolveInfo resolveActivity(Intent intent, int flags)
參數: intent 查尋條件,Activity所配置的action和category
flags: MATCH_DEFAULT_ONLY :Category必須帶有CATEGORY_DEFAULT的Activity,才匹配
GET_INTENT_FILTERS :匹配Intent條件即可
GET_RESOLVED_FILTER :匹配Intent條件即可
功能 :返回給定條件的ResolveInfo對象(本質上是Activity)
public abstract List<ResolveInfo> queryIntentActivities(Intent intent, int flags)
參數同上
功能 :返回給定條件的所有ResolveInfo對象(本質上是Activity),集合對象
public abstract ResolveInfo resolveService(Intent intent, int flags)
參數同上
功能 :返回給定條件的ResolveInfo對象(本質上是Service)
public abstract List<ResolveInfo> queryIntentServices(Intent intent, int flags)
參數同上
功能 :返回給定條件的所有ResolveInfo對象(本質上是Service),集合對象
二、DEMO講解
通過前面的介紹,相信您一定很瞭解了,本質上來講,這些XXXInfo類不過是我們在AndroidManifest.XML文件中定義的信息,
知道到這點了,理解起來就不是很難了。
下面我透過兩個簡答的DEMO,來學以致用。
Demo 1: 通過queryIntentActivities()方法,查詢Android系統的所有具備ACTION_MAIN和CATEGORY_LAUNCHER
的Intent的應用程序,點擊後,能啓動該應用,說白了就是做一個類似Home程序的簡易Launcher 。
Demo 2 :通過getInstalledApplications()方法獲取應用,然後對其過濾,查找出我們需要的第三方應用,系統應用,安裝在sdcard的應用。
Demo1 :
圖:
1 、佈局文件: 主要有兩個:帶listview的browse_app_list.xml文件 ;listview的項browse_app_item.xml
browse_app_list.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="fill_parent"
- android:layout_height="fill_parent">>
- <ListView android:id="@+id/listviewApp" android:layout_width="fill_parent"
- android:layout_height="fill_parent" ></ListView>
- </LinearLayout>
browse_app_item.xmlbrowse_app_item.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent" android:layout_height="50dip">
- <ImageView android:id="@+id/imgApp" android:layout_width="wrap_content"
- android:layout_height="fill_parent" ></ImageView>
- <RelativeLayout android:layout_width="fill_parent" android:layout_marginLeft="10dip"
- android:layout_height="40dip">
- <TextView android:id="@+id/tvLabel" android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:text="AppLable : "></TextView>
- <TextView android:id="@+id/tvAppLabel" android:layout_width="wrap_content"
- android:layout_toRightOf="@id/tvLabel" android:layout_height="wrap_content"
- android:layout_marginLeft="3dip" android:text="Label" android:textColor="#FFD700"></TextView>
- <TextView android:id="@+id/tvName" android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:layout_below="@id/tvLabel"
- android:text="包名:"></TextView>
- <TextView android:id="@+id/tvPkgName" android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:layout_below="@id/tvAppLabel"
- android:layout_alignLeft="@id/tvAppLabel" android:textColor="#FFD700"></TextView>
- </RelativeLayout>
- </LinearLayout>
2 、AppInfo.java : 保存應用程序信息的Model類
- /Model類 ,用來存儲應用程序信息
- public class AppInfo {
- private String appLabel; //應用程序標籤
- private Drawable appIcon ; //應用程序圖像
- private Intent intent ; //啓動應用程序的Intent ,一般是Action爲Main和Category爲Lancher的Activity
- private String pkgName ; //應用程序所對應的包名
- public AppInfo(){}
- public String getAppLabel() {
- return appLabel;
- }
- public void setAppLabel(String appName) {
- this.appLabel = appName;
- }
- public Drawable getAppIcon() {
- return appIcon;
- }
- public void setAppIcon(Drawable appIcon) {
- this.appIcon = appIcon;
- }
- public Intent getIntent() {
- return intent;
- }
- public void setIntent(Intent intent) {
- this.intent = intent;
- }
- public String getPkgName(){
- return pkgName ;
- }
- public void setPkgName(String pkgName){
- this.pkgName=pkgName ;
- }
- }
3、 BrowseApplicationInfoAdapter.java : 自定義適配器類,爲ListView提供視圖
- //自定義適配器類,提供給listView的自定義view
- public class BrowseApplicationInfoAdapter extends BaseAdapter {
- private List<AppInfo> mlistAppInfo = null;
- LayoutInflater infater = null;
- public BrowseApplicationInfoAdapter(Context context, List<AppInfo> apps) {
- infater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- mlistAppInfo = apps ;
- }
- @Override
- public int getCount() {
- // TODO Auto-generated method stub
- System.out.println("size" + mlistAppInfo.size());
- return mlistAppInfo.size();
- }
- @Override
- public Object getItem(int position) {
- // TODO Auto-generated method stub
- return mlistAppInfo.get(position);
- }
- @Override
- public long getItemId(int position) {
- // TODO Auto-generated method stub
- return 0;
- }
- @Override
- public View getView(int position, View convertview, ViewGroup arg2) {
- System.out.println("getView at " + position);
- View view = null;
- ViewHolder holder = null;
- if (convertview == null || convertview.getTag() == null) {
- view = infater.inflate(R.layout.browse_app_item, null);
- holder = new ViewHolder(view);
- view.setTag(holder);
- }
- else{
- view = convertview ;
- holder = (ViewHolder) convertview.getTag() ;
- }
- AppInfo appInfo = (AppInfo) getItem(position);
- holder.appIcon.setImageDrawable(appInfo.getAppIcon());
- holder.tvAppLabel.setText(appInfo.getAppLabel());
- holder.tvPkgName.setText(appInfo.getPkgName());
- return view;
- }
- class ViewHolder {
- ImageView appIcon;
- TextView tvAppLabel;
- TextView tvPkgName;
- public ViewHolder(View view) {
- this.appIcon = (ImageView) view.findViewById(R.id.imgApp);
- this.tvAppLabel = (TextView) view.findViewById(R.id.tvAppLabel);
- this.tvPkgName = (TextView) view.findViewById(R.id.tvPkgName);
- }
- }
- }
4 、MainActivity.java 主工程邏輯
請仔細體會queryIntentActivities()方法,並且注意到排序,它很重要。
- <span style="font-size:13px;">public class MainActivity extends Activity implements OnItemClickListener {
- private ListView listview = null;
- private List<AppInfo> mlistAppInfo = null;
- @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) {
- // TODO Auto-generated method stub
- Intent intent = mlistAppInfo.get(position).getIntent();
- startActivity(intent);
- }
- // 獲得所有啓動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, PackageManager.MATCH_DEFAULT_ONLY);
- // 調用系統排序 , 根據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); // 添加至列表中
- System.out.println(appLabel + " activityName---" + activityName
- + " pkgName---" + pkgName);
- }
- }
- }
- }</span>
好了,第一個Demo完成 。。
Demo 2:
demo2在佈局、適配器方面和Demo1一樣。只是利用了getInstalledApplications()方法,繼而通過ApplicationInfo.flags來挑選
我們希望的ApplicationInfo對象。
圖:
過濾應用程序如下:
- package com.qiner.appinfo;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import com.qiner.appinfo.R;
- import android.app.Activity;
- import android.app.Application;
- import android.content.pm.ApplicationInfo;
- import android.content.pm.PackageManager;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.ListView;
- public class MainActivity extends Activity {
- public static final int FILTER_ALL_APP = 0; // 所有應用程序
- public static final int FILTER_SYSTEM_APP = 1; // 系統程序
- public static final int FILTER_THIRD_APP = 2; // 第三方應用程序
- public static final int FILTER_SDCARD_APP = 3; // 安裝在SDCard的應用程序
- private ListView listview = null;
- private PackageManager pm;
- private int filter = FILTER_ALL_APP;
- private List<AppInfo> mlistAppInfo ;
- private BrowseApplicationInfoAdapter browseAppAdapter = null ;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.browse_app_list);
- listview = (ListView) findViewById(R.id.listviewApp);
- if(getIntent()!=null){
- filter = getIntent().getIntExtra("filter", 0) ;
- }
- mlistAppInfo = queryFilterAppInfo(filter); // 查詢所有應用程序信息
- // 構建適配器,並且註冊到listView
- browseAppAdapter = new BrowseApplicationInfoAdapter(this, mlistAppInfo);
- listview.setAdapter(browseAppAdapter);
- }
- // 根據查詢條件,查詢特定的ApplicationInfo
- private List<AppInfo> queryFilterAppInfo(int filter) {
- pm = this.getPackageManager();
- // 查詢所有已經安裝的應用程序
- List<ApplicationInfo> listAppcations = pm
- .getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
- Collections.sort(listAppcations,
- new ApplicationInfo.DisplayNameComparator(pm));// 排序
- List<AppInfo> appInfos = new ArrayList<AppInfo>(); // 保存過濾查到的AppInfo
- // 根據條件來過濾
- switch (filter) {
- case FILTER_ALL_APP: // 所有應用程序
- appInfos.clear();
- for (ApplicationInfo app : listAppcations) {
- appInfos.add(getAppInfo(app));
- }
- return appInfos;
- case FILTER_SYSTEM_APP: // 系統程序
- appInfos.clear();
- for (ApplicationInfo app : listAppcations) {
- if ((app.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
- appInfos.add(getAppInfo(app));
- }
- }
- return appInfos;
- case FILTER_THIRD_APP: // 第三方應用程序
- appInfos.clear();
- for (ApplicationInfo app : listAppcations) {
- //非系統程序
- if ((app.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
- appInfos.add(getAppInfo(app));
- }
- //本來是系統程序,被用戶手動更新後,該系統程序也成爲第三方應用程序了
- else if ((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0){
- appInfos.add(getAppInfo(app));
- }
- }
- break;
- case FILTER_SDCARD_APP: // 安裝在SDCard的應用程序
- appInfos.clear();
- for (ApplicationInfo app : listAppcations) {
- if ((app.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
- appInfos.add(getAppInfo(app));
- }
- }
- return appInfos;
- default:
- return null;
- }
- return appInfos;
- }
- // 構造一個AppInfo對象 ,並賦值
- private AppInfo getAppInfo(ApplicationInfo app) {
- AppInfo appInfo = new AppInfo();
- appInfo.setAppLabel((String) app.loadLabel(pm));
- appInfo.setAppIcon(app.loadIcon(pm));
- appInfo.setPkgName(app.packageName);
- return appInfo;
- }
- }
你可以在此基礎上,構建更多豐富的應用。比說說Settings模塊中的卸載安裝應用程序等。
二
本部分的內容是如何獲取安裝包得大小,包括緩存大小(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文件的使用和回調函數的處理。
仔細研究後,纔有所理解。