Android9.0 静默安装源码的实现
网上基本都停在8.0就没人开始分析Android9.0如何静默apk的代码,这是我自己之前研究9.0的framework整理出来的,真实源码整理
importandroid.content.BroadcastReceiver;
importandroid.content.Context;
importandroid.content.IIntentReceiver;
importandroid.content.IIntentSender;
importandroid.content.Intent;
importandroid.content.IntentFilter;
importandroid.content.IntentSender;
importandroid.content.pm.ApplicationInfo;
importandroid.content.pm.PackageInfo;
importandroid.content.pm.PackageInstaller;
importandroid.content.pm.PackageManager;
importandroid.net.Uri;
importandroid.os.Bundle;
importandroid.os.Environment;
importandroid.os.IBinder;
importandroid.os.RemoteException;
importandroid.util.Log;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.lang.reflect.Constructor;
importjava.lang.reflect.Field;
importjava.lang.reflect.InvocationTargetException;
importjava.util.concurrent.SynchronousQueue;
importjava.util.concurrent.TimeUnit;
/**
*作者:
*邮箱:709847739#qq.com
*时间:2019/2/21-9:21
*desc:
*version:1.0
*/
publicclassPackageManagerCompatP{
privatefinalstaticStringTAG=PackageManagerCompatP.class.getSimpleName();
publicstaticfinallongMAX_WAIT_TIME=25*1000;
publicstaticfinallongWAIT_TIME_INCR=5*1000;
privatestaticfinalStringSECURE_CONTAINERS_PREFIX="/mnt/asec";
privateContextmContext;
publicPackageManagerCompatQ(Contextcontext){
this.mContext=context;
}
privatestaticclassLocalIntentReceiver{
privatefinalSynchronousQueuemResult=newSynchronousQueue<>();
privateIIntentSender.StubmLocalSender=newIIntentSender.Stub(){
@Override
publicvoidsend(intcode,Intentintent,StringresolvedType,IBinderwhitelistToken,
IIntentReceiverfinishedReceiver,StringrequiredPermission,Bundleoptions){
try{
mResult.offer(intent,5,TimeUnit.SECONDS);
}catch(InterruptedExceptione){
thrownewRuntimeException(e);
}
}
};
publicIntentSendergetIntentSender(){
Class>aClass=null;
try{
aClass=Class.forName("android.content.IntentSender");
}catch(ClassNotFoundExceptione){
e.printStackTrace();
}
if(aClass==null){
returnnull;
}
try{
Constructor>[]declaredConstructors=aClass.getDeclaredConstructors();
for(Constructor>declaredConstructor:declaredConstructors){
Log.i(TAG,"declaredConstructor.toString():"+declaredConstructor.toString());
Log.i(TAG,"declaredConstructor.getName():"+declaredConstructor.getName());
Class>[]parameterTypes=declaredConstructor.getParameterTypes();
for(Class>parameterType:parameterTypes){
ClassaClass1=parameterType.getClass();
Log.i(TAG,"parameterTypes...aClass1:"+aClass1.getName());
}
}
}catch(Exceptione){
e.printStackTrace();
}
Constructorconstructor=null;
try{
constructor=aClass.getDeclaredConstructor(IIntentSender.class);
}catch(NoSuchMethodExceptione){
e.printStackTrace();
}
if(constructor==null){
returnnull;
}
Objecto=null;
try{
o=constructor.newInstance((IIntentSender)mLocalSender);
}catch(IllegalAccessExceptione){
e.printStackTrace();
}catch(InstantiationExceptione){
e.printStackTrace();
}catch(InvocationTargetExceptione){
e.printStackTrace();
}
return(IntentSender)o;
//newIntentSender((IIntentSender)mLocalSender)
}
publicIntentgetResult(){
try{
returnmResult.take();
}catch(InterruptedExceptione){
thrownewRuntimeException(e);
}
}
}
privatePackageManagergetPm(){
returnmContext.getPackageManager();
}
privatePackageInstallergetPi(){
returngetPm().getPackageInstaller();
}
privatevoidwriteSplitToInstallSession(PackageInstaller.Sessionsession,StringinPath,
StringsplitName)throwsRemoteException{
longsizeBytes=0;
finalFilefile=newFile(inPath);
if(file.isFile()){
sizeBytes=file.length();
}else{
return;
}
InputStreamin=null;
OutputStreamout=null;
try{
in=newFileInputStream(inPath);
out=session.openWrite(splitName,0,sizeBytes);
inttotal=0;
byte[]buffer=newbyte[65536];
intc;
while((c=in.read(buffer))!=-1){
total+=c;
out.write(buffer,0,c);
}
session.fsync(out);
}catch(IOExceptione){
e.printStackTrace();
}finally{
IoUtils.closeQuietly(out);
IoUtils.closeQuietly(in);
IoUtils.closeQuietly(session);
}
}
/**
*入口方法
*StringapkPackageName="";//填写安装的包名
*StringapkPath="";//填写安装的路径
**/
publicvoidtestReplaceFlagSdcardInternal(StringapkPackageName,StringapkPath)throwsException{
//Donotrunondeviceswithemulatedexternalstorage.
if(Environment.isExternalStorageEmulated()){
return;
}
intiFlags=0x00000008;//PackageManager.INSTALL_EXTERNAL0x00000008
intrFlags=0;
//这个暂时用不上
//InstallParamsip=sampleInstallFromRawResource(iFlags,false);
Uriuri=Uri.fromFile(newFile(apkPath));
GenericReceiverreceiver=newReplaceReceiver(apkPackageName);
intreplaceFlags=rFlags|0x00000002;//PackageManager.INSTALL_REPLACE_EXISTING0x00000002
try{
invokeInstallPackage(uri,replaceFlags,receiver,true);
//assertInstall(ip.pkg,iFlags,ip.pkg.installLocation);
}catch(Exceptione){
Log.e(TAG,"Failedwithexception:"+e);
}finally{
//cleanUpInstall(ip);
}
}
//classInstallParams{
//UripackageURI;
//
//PackageParser.Packagepkg;
//
//InstallParams(StringoutFileName,intrawResId)throwsPackageParserException{
//this.pkg=getParsedPackage(outFileName,rawResId);
//this.packageURI=Uri.fromFile(newFile(pkg.codePath));
//}
//
//InstallParams(PackageParser.Packagepkg){
//this.packageURI=Uri.fromFile(newFile(pkg.codePath));
//this.pkg=pkg;
//}
//
//longgetApkSize(){
//Filefile=newFile(pkg.codePath);
//returnfile.length();
//}
//}
//
//privateInstallParamssampleInstallFromRawResource(intflags,booleancleanUp)
//throwsException{
//returninstallFromRawResource("install.apk",android.R.raw.install,flags,cleanUp,false,-1,
//PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
//}
//privatevoidcleanUpInstall(InstallParamsip){
//
//}
privatevoidcleanUpInstall(StringpkgName)throwsException{
if(pkgName==null){
return;
}
Log.i(TAG,"Deletingpackage:"+pkgName);
try{
finalApplicationInfoinfo=getPm().getApplicationInfo(pkgName,
PackageManager.MATCH_UNINSTALLED_PACKAGES);
if(info!=null){
//PackageManager.DELETE_ALL_USERS
finalLocalIntentReceiverlocalReceiver=newLocalIntentReceiver();
//这是卸载,不调用
//getPi().uninstall(pkgName,
//0x00000002,
//localReceiver.getIntentSender());
localReceiver.getResult();
assertUninstalled(info);
}
}catch(IllegalArgumentException|PackageManager.NameNotFoundExceptione){
e.printStackTrace();
}
}
privatestaticvoidassertUninstalled(ApplicationInfoinfo)throwsException{
FilenativeLibraryFile=newFile(info.nativeLibraryDir);
Log.e(TAG,"Nativelibrarydirectory"+info.nativeLibraryDir
+"shouldbeerased"+nativeLibraryFile.exists());
}
privatevoidinvokeInstallPackage(UripackageUri,intflags,GenericReceiverreceiver,
booleanshouldSucceed){
mContext.registerReceiver(receiver,receiver.filter);
synchronized(receiver){
finalStringinPath=packageUri.getPath();
PackageInstaller.Sessionsession=null;
try{
finalPackageInstaller.SessionParamssessionParams=
newPackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
try{
//sessionParams.installFlags=flags;
FieldinstallFlags=sessionParams.getClass().getDeclaredField("installFlags");
installFlags.set(sessionParams,flags);
}catch(NoSuchFieldExceptione){
e.printStackTrace();
}catch(IllegalAccessExceptione){
e.printStackTrace();
}
finalintsessionId=getPi().createSession(sessionParams);
session=getPi().openSession(sessionId);
writeSplitToInstallSession(session,inPath,"base.apk");
finalLocalIntentReceiverlocalReceiver=newLocalIntentReceiver();
session.commit(localReceiver.getIntentSender());
finalIntentresult=localReceiver.getResult();
finalintstatus=result.getIntExtra(PackageInstaller.EXTRA_STATUS,
PackageInstaller.STATUS_FAILURE);
if(shouldSucceed){
if(status!=PackageInstaller.STATUS_SUCCESS){
Log.e(TAG,"Installationshouldhavesucceeded,butgotcode"+status);
}
}else{
if(status==PackageInstaller.STATUS_SUCCESS){
Log.e(TAG,"Installationshouldhavefailed");
}
//We'llnevergetabroadcastsincethepackagefailedtoinstall
return;
}
//Verifywereceivedthebroadcast
longwaitTime=0;
while((!receiver.isDone())&&(waitTime
就这一个类的封装,我也是看framework扣出来的
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。