android反射示例
(1)挂断电话
//通过类加载器加载ServiceManager类
Class<?> clazz = getClassLoader().loadClass("android.os.ServiceManager");
//通过反射得到当前方法即getService()
Method method = clazz.getDeclaredMethod("getService", String.class);
//使用方法getService(),得到返回值
IBinder ibinder = (IBinder) method.invoke(null, TELEPHONY_SERVICE);
//通过远程服务得到aidl
ITelephony itelephony = ITelephony.Stub.asInterface(ibinder);
//使用被阉割的方法
itelephony.endCall();
(2)获取缓存大小,应用大小
PackageManager pm = getPackageManager();
try {
Class<?> loadClass = Class.froName("android.content.pm.PackageManager");
Method method = loadClass.getDeclaredMethod("getPackageSizeInfo", String.class,IPackageStatsObserver.class);
//receiver : 类的实例,隐藏参数,方法不是静态的必须指定
method.invoke(pm, "com.example.popupwindow",mStatsObserver);
} catch (Exception e) {
e.printStackTrace();
}
IPackageStatsObserver.Stub mStatsObserver = new IPackageStatsObserver.Stub() {
public void onGetStatsCompleted(PackageStats stats, boolean succeeded) {
long cachesize = stats.cacheSize;//缓存大小
long codesize = stats.codeSize;//应用程序的大小
long datasize = stats.dataSize;//数据大小
String cache = Formatter.formatFileSize(getApplicationContext(), cachesize);
String code = Formatter.formatFileSize(getApplicationContext(), codesize);
String data = Formatter.formatFileSize(getApplicationContext(), datasize);
}
};
(3)清除所有缓存
//获取缓存
PackageManager pm = getPackageManager();
//反射获取缓存
try {
Class<?> loadClass = Class.froName("android.content.pm.PackageManager");
Method method = loadClass.getDeclaredMethod("freeStorageAndNotify", Long.TYPE, IPackageDataObserver.class);
//receiver : 类的实例,隐藏参数,方法不是静态的必须指定
method.invoke(pm, Integer.MAX_VALUE, mDataObserver);
} catch (Exception e) {
e.printStackTrace();
}
IPackageDataObserver mDataObserver = new IPackageDataObserver() {
@Override
public IBinder asBinder() {
return null;
}
@Override
public void onRemoveCompleted(String packageName, boolean succeeded) throws RemoteException {
}
};