Android使用adb和PackageInstaller两种方式安装apk

简单实现的一个案例,直接上代码 

PackageInstaller安装方式

//安装apk服务
public class InstallerApkService extends Service {

    private final static String TAG = "InstallerApkService";

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        installApk();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void installApk() {
        LogUtils.e(TAG,"==安装");
        PackageInstaller.Session session = null;
        try {
            PackageInstaller packageInstaller = getPackageManager().getPackageInstaller();
            packageInstaller.registerSessionCallback(new PackageInstaller.SessionCallback() {
                @Override
                public void onCreated(int sessionId) {
                    LogUtils.e(TAG,"==onCreated==sessionId: "+sessionId);
                }

                @Override
                public void onBadgingChanged(int sessionId) {
                    LogUtils.e(TAG,"==onBadgingChanged==sessionId: "+sessionId);
                }

                @Override
                public void onActiveChanged(int sessionId, boolean active) {
                    LogUtils.e(TAG,"==onActiveChanged==sessionId: "+sessionId);
                }

                @Override
                public void onProgressChanged(int sessionId, float progress) {
                    LogUtils.e(TAG,"===onProgressChanged=sessionId: "+sessionId+"===progress: "+progress);
                }

                @Override
                public void onFinished(int sessionId, boolean success) {
                    LogUtils.e(TAG,"===onFinished=sessionId: "+sessionId);
                }
            });
            PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
                    PackageInstaller.SessionParams.MODE_FULL_INSTALL);
            int sessionId = packageInstaller.createSession(params);
            session = packageInstaller.openSession(sessionId);

            try (OutputStream packageInSession = session.openWrite("package", 0, -1);
                 InputStream is = getAssets().open("dev-v1.0.1-release.apk")) {
                byte[] buffer = new byte[16384];
                int n;
                while ((n = is.read(buffer)) >= 0) {
                    packageInSession.write(buffer, 0, n);
                }
            }
            // 创建安装状态接收广播
            Intent intent = new Intent(getApplicationContext(), InstallerApkBroadcastReceiver.class);
            intent.setAction(PACKAGE_INSTALLED_ACTION);
            //此处也可以使用getService回调通知
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            IntentSender statusReceiver = pendingIntent.getIntentSender();
            // 提交会话,这将启动安装工作流
            session.commit(statusReceiver);
        } catch (IOException e) {
            throw new RuntimeException("Couldn't install package", e);
        } catch (RuntimeException e) {
            if (session != null) {
                session.abandon();
            }
            throw e;
        }
    }

    public static final String PACKAGE_INSTALLED_ACTION =
            "com.rishun.systemsetting.INSTALLER_SETTING";
    static class InstallStatusBroadcastReceiver extends BroadcastReceiver {

        private static final String TAG = "InstallStatus";

        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extras = intent.getExtras();
            if (PACKAGE_INSTALLED_ACTION.equals(intent.getAction())) {
                int status = extras.getInt(PackageInstaller.EXTRA_STATUS);
                String message = extras.getString(PackageInstaller.EXTRA_STATUS_MESSAGE);

                switch (status) {
                    case PackageInstaller.STATUS_PENDING_USER_ACTION:
                        break;

                    case PackageInstaller.STATUS_SUCCESS:
                        //安装成功
                        Log.d(TAG, "Install succeeded!");
                        break;

                    case PackageInstaller.STATUS_FAILURE:
                    case PackageInstaller.STATUS_FAILURE_ABORTED:
                    case PackageInstaller.STATUS_FAILURE_BLOCKED:
                    case PackageInstaller.STATUS_FAILURE_CONFLICT:
                    case PackageInstaller.STATUS_FAILURE_INCOMPATIBLE:
                    case PackageInstaller.STATUS_FAILURE_INVALID:
                    case PackageInstaller.STATUS_FAILURE_STORAGE:
                        Log.e(TAG, "Install failed!" + status + ", " + message);
                        break;
                    default:
                        Log.e(TAG, "Unrecognized status received from installer: " + status);
                }
            }
        }
    }

}

adb安装方式:

private boolean installApp(String packageName, String apkPath) {
        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        try {
            process = new ProcessBuilder("pm", "install", "-i", packageName, "-r", apkPath).start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
            LogUtils.e("安装异常" + e.getMessage());
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {
            }
            if (process != null) {
                process.destroy();
            }
        }
        String re = successMsg.toString();
        LogUtils.e("result-----" + re+"---apkPath: "+apkPath);
        //如果含有“success”认为安装成功
        return successMsg.toString().equalsIgnoreCase("success");
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值