Android 安装apk包方法/监听升级

http://blog.csdn.net/heikefangxian23/article/details/38582261

通过指定intent.setDataAndType(uri, "application/vnd.android.package-archive");

直接吊起installer intent.setAction(Intent.ACTION_INSTALL_PACKAGE);

https://stackoverflow.com/questions/19825636/action-install-package

如果想监听用户是否升级(比如做强制升级)
广播是不奏效的,用startActivityForResult(intent)
此时吊起了安装界面,如果用户点back,可认为并没有升级,你就可以在回调里去做事情了。

附上代码

private void installApk() {
        File saveFile = new File(getApkSavePath());
        if (!saveFile.exists()) return;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(ApplicationCache.getContext(), "com.xxxx.fileprovider", saveFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(saveFile);
        }
        // Service中启动的Activity需要显示的设置Intent.FLAG_ACTIVITY_NEW_TASK
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.setData(uri);
        intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
        if (isForceUpgrade) startActivityForResult(intent, 0x666);
        else startActivity(intent);
    }

    //只有强制升级才调用startActivityForResult
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       //如果进入了该回调则认为只是打开了系统installer界面,但是点击了返回,比较缓和的方案是给一个弹窗
       //强制方案就是forceStop
        if (requestCode == 0x666) showInstallDialog();
    }

你可能感兴趣的:(Android 安装apk包方法/监听升级)