package com.example.myipc;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.os.RemoteException;
import android.text.format.Formatter;
import java.lang.reflect.Method;
import java.util.List;
public class FileUtil {
private static ISizeView mISizeView;
private static Context mContext;
public static void getApplicationSize(Context context, ISizeView view) {
mISizeView = view;
mContext = context;
try {
queryPacakgeSize(getAppProcessName(context));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取当前应用程序的包名
* @param context 上下文对象
* @return 返回包名
*/
public static String getAppProcessName(Context context) {
//当前应用pid
int pid = android.os.Process.myPid();
//任务管理类
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//遍历所有应用
List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo info : infos) {
if (info.pid == pid)//得到当前应用
return info.processName;//返回包名
}
return "";
}
public static void queryPacakgeSize(String pkgName) throws Exception {
if (pkgName != null) {
//使用反射机制得到PackageManager类的隐藏函数getPackageSizeInfo
PackageManager pm =mContext.getPackageManager(); //得到pm对象
try {
//通过反射机制获得该隐藏函数
Method getPackageSizeInfo = PackageManager.class.getDeclaredMethod("getPackageSizeInfo" ,String.class, IPackageStatsObserver.class);
//调用该函数,并且给其分配参数 ,待调用流程完成后会回调PkgSizeObserver类的函数
getPackageSizeInfo.invoke(pm, pkgName, new PkgSizeObserver(mContext,pkgName));
} catch (Exception ex) {
ex.printStackTrace();
throw ex;