Android中獲取緩存大小和應(yīng)用程序大小
通過(guò)第一部分<<Android中獲取應(yīng)用程序(包)的信息-----PackageManager的使用(一)>>的介紹,對(duì)PackageManager以及
AndroidManife.xml定義的節(jié)點(diǎn)信息類(lèi)XXXInfo類(lèi)都有了一定的認(rèn)識(shí)。
本部分的內(nèi)容是如何獲取安裝包得大小,包括緩存大小(cachesize)、數(shù)據(jù)大小(datasize)、應(yīng)用程序大小(codesize)。
本部分的知識(shí)點(diǎn)涉及到AIDL、Java反射機(jī)制。理解起來(lái)也不是很難。
關(guān)于安裝包得大小信息封裝在PackageStats類(lèi)中,該類(lèi)很簡(jiǎn)單,只有幾個(gè)字段:
PackageStats類(lèi):
常用字段:
public long cachesize 緩存大小
public long codesize 應(yīng)用程序大小
public long datasize 數(shù)據(jù)大小
public String packageName 包名
PS:應(yīng)用程序的總大小 = cachesize + codesize + datasize
也就是說(shuō)只要獲得了安裝包所對(duì)應(yīng)的PackageStats對(duì)象,就可以獲得信息了。但是在AndroidSDK中并沒(méi)有顯示提供方法來(lái)
獲得該對(duì)象,是不是很苦惱呢?但是,我們可以通過(guò)放射機(jī)制來(lái)調(diào)用系統(tǒng)中隱藏的函數(shù)(@hide)來(lái)獲得每個(gè)安裝包得信息。
具體方法如下:
第一步、 通過(guò)放射機(jī)制調(diào)用getPackageSizeInfo() 方法原型為:
[java] view plaincopyprint?
/*@param packageName 應(yīng)用程序包名
*@param observer 當(dāng)查詢包得信息大小操作完成后,將回調(diào)給IPackageStatsObserver類(lèi)中的onGetStatsCompleted()方法,
* ,并且我們需要的PackageStats對(duì)象也封裝在其參數(shù)里.
* @hide //隱藏函數(shù)的標(biāo)記
*/
public abstract void getPackageSizeInfo(String packageName,IPackageStatsObserver observer);{
//
}
內(nèi)部調(diào)用流程如下,這個(gè)知識(shí)點(diǎn)較為復(fù)雜,知道即可,
getPackageSizeInfo方法內(nèi)部調(diào)用getPackageSizeInfoLI(packageName, pStats)方法來(lái)完成包狀態(tài)獲取。
getPackageSizeInfoLI方法內(nèi)部調(diào)用Installer.getSizeInfo(String pkgName, String apkPath,String fwdLockApkPath, PackageStats
pStats),繼而將包狀態(tài)信息返回給參數(shù)pStats。getSizeInfo這個(gè)方法內(nèi)部是以本機(jī)Socket方式連接到Server,
然后向server發(fā)送一個(gè)文本字符串命令,格式:getsize apkPath fwdLockApkPath 給server。Server將結(jié)果返回,并解析到pStats
中。掌握這個(gè)調(diào)用知識(shí)鏈即可。
第二步、 由于需要獲得系統(tǒng)級(jí)的服務(wù)或類(lèi),我們必須加入Android系統(tǒng)形成的AIDL文件,共兩個(gè):
IPackageStatsObserver.aidl 和 PackageStats.aidl文件。并將其放置在android.pm.content包路徑下。
IPackageStatsObserver.aidl 文件
[java] view plaincopyprint?
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文件
[java] view plaincopyprint?
package android.content.pm;
parcelable PackageStats;
第三步、 創(chuàng)建一個(gè)類(lèi)繼承至IPackageStatsObserver.Stub (樁,)它本質(zhì)上實(shí)現(xiàn)了Binder機(jī)制。當(dāng)我們把該類(lèi)的一個(gè)實(shí)例通過(guò)getPackageSizeInfo()調(diào)用時(shí),并該函數(shù)繼而啟動(dòng)了啟動(dòng)中間流程 去獲取相關(guān)包得信息大小,當(dāng)掃描完成后,最后將查詢信息回調(diào)至該類(lèi)的onGetStatsCompleted(in PackageStats pStats, boolean succeeded)方法,信息大小封裝在此實(shí)例上。例如:
[java] view plaincopyprint?
//aidl文件形成的Bindler機(jī)制服務(wù)類(lèi)
public class PkgSizeObserver extends IPackageStatsObserver.Stub{
/*** 回調(diào)函數(shù),
* @param pStatus ,返回?cái)?shù)據(jù)封裝在PackageStats對(duì)象中
* @param succeeded 代表回調(diào)成功
*/
@Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
throws RemoteException {
// TODO Auto-generated method stub
cachesize = pStats.cacheSize ; //緩存大小
datasize = pStats.codeSize ; //數(shù)據(jù)大小
codesize = pStats.codeSize ; //應(yīng)用程序大小
}
}
第四步、 最后我們可以獲取 pStats的屬性,獲得它們的屬性值,通過(guò)調(diào)用系統(tǒng)函數(shù)Formatter.formateFileSize(long size)轉(zhuǎn)換
為對(duì)應(yīng)的以kb/mb為計(jì)量單位的字符串。
很重要的一點(diǎn):為了能夠通過(guò)反射獲取應(yīng)用程序大小,我們必須加入以下權(quán)限,否則,會(huì)出現(xiàn)警告并且得不到實(shí)際值。
[java] view plaincopyprint?
流程圖如下:
Demo說(shuō)明:
在第一部分應(yīng)用得基礎(chǔ)上,我們添加了一個(gè)新功能,點(diǎn)擊任何一個(gè)應(yīng)用后后,彈出顯示該應(yīng)用的包信息大小的對(duì)話框。
截圖如下:
工程圖: 程序效果圖:
1、dialg_app_size.xml 文件
[html] view plaincopyprint?
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="數(shù)據(jù)大小:">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="應(yīng)用程序大小:">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、另外的資源文件或自定義適配器復(fù)用了第一部分,請(qǐng)知悉。
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
LayoutInflater infater = null ;
//全局變量,保存當(dāng)前查詢包得信息
private long cachesize ; //緩存大小
private long datasize ; //數(shù)據(jù)大小
private long codesize ; //應(yīng)用程序大小
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
queryAppInfo(); // 查詢所有應(yīng)用程序信息
BrowseApplicationInfoAdapter browseAppAdapter = new BrowseApplicationInfoAdapter(
this, mlistAppInfo);
listview.setAdapter(browseAppAdapter);
listview.setOnItemClickListener(this);
}
// 點(diǎn)擊彈出對(duì)話框,顯示該包得大小
public void onItemClick(AdapterView arg0, View view, int position,long arg3) {
//更新顯示當(dāng)前包得大小信息
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) ; //數(shù)據(jù)大小
TextView tvcodesize = (TextView) dialog.findViewById(R.id.tvcodesize) ; // 應(yīng)用程序大小
TextView tvtotalsize = (TextView) dialog.findViewById(R.id.tvtotalsize) ; //總大小
//類(lèi)型轉(zhuǎn)換并賦值
tvcachesize.setText(formateFileSize(cachesize));
tvdatasize.setText(formateFileSize(datasize)) ;
tvcodesize.setText(formateFileSize(codesize)) ;
tvtotalsize.setText(formateFileSize(totalsize)) ;
//顯示自定義對(duì)話框
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() ; // 取消顯示對(duì)話框
}
});
builder.create().show() ;
}
public void queryPacakgeSize(String pkgName) throws Exception{
if ( pkgName != null){
//使用放射機(jī)制得到PackageManager類(lèi)的隱藏函數(shù)getPackageSizeInfo
PackageManager pm = getPackageManager(); //得到pm對(duì)象
try {
//通過(guò)反射機(jī)制獲得該隱藏函數(shù)
Method getPackageSizeInfo = pm.getClass().getDeclaredMethod("getPackageSizeInfo", String.class,IPackageStatsObserver.class);
//調(diào)用該函數(shù),并且給其分配參數(shù) ,待調(diào)用流程完成后會(huì)回調(diào)PkgSizeObserver類(lèi)的函數(shù)
getPackageSizeInfo.invoke(pm, pkgName,new PkgSizeObserver());
}
catch(Exception ex){
Log.e(TAG, "NoSuchMethodException") ;
ex.printStackTrace() ;
throw ex ; // 拋出異常
}
}
}
//aidl文件形成的Bindler機(jī)制服務(wù)類(lèi)
public class PkgSizeObserver extends IPackageStatsObserver.Stub{
/*** 回調(diào)函數(shù),
* @param pStatus ,返回?cái)?shù)據(jù)封裝在PackageStats對(duì)象中
* @param succeeded 代表回調(diào)成功
*/
@Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
throws RemoteException {
// TODO Auto-generated method stub
cachesize = pStats.cacheSize ; //緩存大小
datasize = pStats.dataSize ; //數(shù)據(jù)大小
codesize = pStats.codeSize ; //應(yīng)用程序大小
totalsize = cachesize + datasize + codesize ;
Log.i(TAG, "cachesize--->"+cachesize+" datasize---->"+datasize+ " codeSize---->"+codesize) ;
}
}
//系統(tǒng)函數(shù),字符串轉(zhuǎn)換 long -String (kb)
private String formateFileSize(long size){
return Formatter.formatFileSize(MainActivity.this, size);
}
// 獲得所有啟動(dòng)Activity的信息,類(lèi)似于Launch界面
public void queryAppInfo() {
PackageManager pm = this.getPackageManager(); // 獲得PackageManager對(duì)象
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
// 通過(guò)查詢,獲得所有ResolveInfo對(duì)象.
List
// 調(diào)用系統(tǒng)排序 , 根據(jù)name排序
// 該排序很重要,否則只能顯示系統(tǒng)應(yīng)用,而不能列出第三方應(yīng)用程序
Collections.sort(resolveInfos,new ResolveInfo.DisplayNameComparator(pm));
if (mlistAppInfo != null) {
mlistAppInfo.clear();
for (ResolveInfo reInfo : resolveInfos) {
String activityName = reInfo.activityInfo.name; // 獲得該應(yīng)用程序的啟動(dòng)Activity的name
String pkgName = reInfo.activityInfo.packageName; // 獲得應(yīng)用程序的包名
String appLabel = (String) reInfo.loadLabel(pm); // 獲得應(yīng)用程序的Label
Drawable icon = reInfo.loadIcon(pm); // 獲得應(yīng)用程序圖標(biāo)
// 為應(yīng)用程序的啟動(dòng)Activity 準(zhǔn)備Intent
Intent launchIntent = new Intent();
launchIntent.setComponent(new ComponentName(pkgName,activityName));
// 創(chuàng)建一個(gè)AppInfo對(duì)象,并賦值
AppInfo appInfo = new AppInfo();
appInfo.setAppLabel(appLabel);
appInfo.setPkgName(pkgName);
appInfo.setAppIcon(icon);
appInfo.setIntent(launchIntent);
mlistAppInfo.add(appInfo); // 添加至列表中
}
}
}
}
獲取應(yīng)用程序信息大小就是這么來(lái)的,整個(gè)過(guò)程相對(duì)而言還是挺簡(jiǎn)單的,比較難理解的是AIDL文件的使用和回調(diào)函數(shù)的處理。
仔細(xì)研究后,才有所理解。
推薦文章
2024-11-28
2024-06-25
2024-01-04
2023-11-06
2023-10-30
2023-10-13
2023-10-10
穩(wěn)定
產(chǎn)品高可用性高并發(fā)貼心
項(xiàng)目群及時(shí)溝通專(zhuān)業(yè)
產(chǎn)品經(jīng)理1v1支持快速
MVP模式小步快跑承諾
我們選擇聲譽(yù)堅(jiān)持
10年專(zhuān)注高端品質(zhì)開(kāi)發(fā)聯(lián)系我們
友情鏈接: