首先,說明,為了安全是無法在所有的Android 系統中進行靜默安裝的,我下面所講的靜默安裝的前提是必須是系統的簽名才行,好了,不多了,直接上代碼。
第一步,添加一個安裝回調接口
public interface OnInstalledPackaged {
public void packageInstalled(String packageName, int returnCode);
}
第二步,定義一個系統不可見的接口IPackageInstallObserver,所以包名是不能變的
package android.content.pm;
public interface IPackageInstallObserver extends android.os.IInterface {
public abstract static class Stub extends android.os.Binder implements android.content.pm.IPackageInstallObserver {
public Stub() {
throw new RuntimeException("Stub!");
}
public static android.content.pm.IPackageInstallObserver asInterface(android.os.IBinder obj) {
throw new RuntimeException("Stub!");
}
public android.os.IBinder asBinder() {
throw new RuntimeException("Stub!");
}
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags)
throws android.os.RemoteException {
throw new RuntimeException("Stub!");
}
}
public abstract void packageInstalled(java.lang.String packageName, int returnCode)
throws android.os.RemoteException;
}
第三步,實現ApplicationManager功能
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.content.Context;
import android.content.pm.IPackageInstallObserver;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.RemoteException;
public class ApplicationManager {
public final int INSTALL_REPLACE_EXISTING = 2;
public static final int INSTALL_SUCCEEDED = 1;
private PackageInstallObserver observer;
private PackageManager pm;
private Method method;
private OnInstalledPackaged onInstalledPackaged;
class PackageInstallObserver extends IPackageInstallObserver.Stub {
public void packageInstalled(String packageName, int returnCode) throws RemoteException {
if (onInstalledPackaged != null) {
onInstalledPackaged.packageInstalled(packageName, returnCode);
}
}
}
public ApplicationManager(Context context) throws SecurityException, NoSuchMethodException {
observer = new PackageInstallObserver();
pm = context.getPackageManager();
Class<?>[] types = new Class[] {Uri.class, IPackageInstallObserver.class, int.class, String.class};
method = pm.getClass().getMethod("installPackage", types);
}
public void setOnInstalledPackaged(OnInstalledPackaged onInstalledPackaged) {
this.onInstalledPackaged = onInstalledPackaged;
}
public void installPackage(String apkFile) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
installPackage(new File(apkFile));
}
public void installPackage(File apkFile) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
if (!apkFile.exists()) throw new IllegalArgumentException();
Uri packageURI = Uri.fromFile(apkFile);
installPackage(packageURI);
}
public void installPackage(Uri apkFile) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
method.invoke(pm, new Object[] {apkFile, observer, INSTALL_REPLACE_EXISTING, null});
}
}