Android 静默安装和静默卸载实现

静默安装和卸载都是有PackageManager来处理的,我直接在CustomizedService.java类里实现这个方法,其他的文件我就不一一列出了.如下是静默卸载和安装接口silentUninstallPackage和silentInstallPackage,这两个接口都可以做成带有返回值的接口,静默卸载接口我觉得带有返回值意义不大,所以我就只做了一个带返回值的静默安装接口

import android.content.pm.PackageManager;
import android.content.pm.IPackageDeleteObserver;
import android.content.pm.PackageManager;
import android.content.pm.IPackageInstallObserver;
import android.app.PackageInstallObserver;
import android.content.pm.VerificationParams;
import android.content.pm.IPackageManager;   //import这些类
import android.widget.Toast;   private static final int INSTALL_SUCCEED = 8;private final Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case INSTALL_SUCCEED:Toast.makeText(mContext,"应用已安装成功!",Toast.LENGTH_LONG).show();}}};class PackageDeleteObserver extends IPackageDeleteObserver.Stub {public void packageDeleted(String packageName, int returnCode) {}}//静默卸载接口public void silentUninstallPackage (String packageName) {long jh = Binder.clearCallingIdentity();Slog.d("lei","silentUninstallPackage start = "+ packageName);PackageDeleteObserver observer = new PackageDeleteObserver();mContext.getPackageManager().deletePackage(packageName, observer,PackageManager.DELETE_ALL_USERS);Binder.restoreCallingIdentity(jh);}//静默安装接口public int silentInstallPackage(String PackagePath) {Slog.d("lei","silentInstallPackage start = "+ PackagePath);long jh = Binder.clearCallingIdentity();final Uri apkURI = Uri.fromFile(new File(PackagePath));final int installFlags = PackageManager.INSTALL_ALL_USERS | PackageManager.INSTALL_REPLACE_EXISTING;LocalPackageInstallObserver obs = new LocalPackageInstallObserver();try {VerificationParams verificationParams = new VerificationParams(apkURI,null, null,-1, null);IPackageManager mPm = IPackageManager.Stub.asInterface(ServiceManager.getService("package"));mPm.installPackageAsUser(PackagePath, obs.getBinder(), installFlags,null, verificationParams, null, 0);synchronized (obs) {while (!obs.finished) {try {obs.wait();} catch (InterruptedException e) {}}if (obs.result == PackageManager.INSTALL_SUCCEEDED) {Slog.d("lei","success");mHandler.sendEmptyMessage(INSTALL_SUCCEED);} else {Slog.d("lei","failure");}}} catch (RemoteException e) {}finally{Binder.restoreCallingIdentity(jh);}return obs.result;}class LocalPackageInstallObserver extends PackageInstallObserver {boolean finished;int result;String extraPermission;String extraPackage;@Overridepublic void onPackageInstalled(String name, int status, String msg, Bundle extras) {synchronized (this) {finished = true;result = status;if (status == PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION) {extraPermission = extras.getString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION);extraPackage = extras.getString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE);}notifyAll();}}}

本文链接:https://my.lmcjl.com/post/12324.html

展开阅读全文

4 评论

留下您的评论.