APK安装(OkHttp下载)

1.在清单文件中增加请求安装权限

**InstallUtil 类 **


<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>  

public class InstallUtil {

        public static final int UNKNOWN_CODE = 2019;
        public static void installApk(Context context, String path) {
            if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
                startInstallO(context,path);
            }else if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
                startInstallN(context,path);
            }else {
                startInstall(context,path);
            }
        }

        /**
         *android1.x-6.x
         *@param path 文件的路径
         */
        private static void startInstall(Context context, String path) {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.parse("file://" + path), "application/vnd.android.package-archive");
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(install);
        }

        /**
         * android7.x
         * @param path 文件路径
         */
        @RequiresApi(api = Build.VERSION_CODES.N)
        private static void startInstallN(Context context, String path) {
            //参数1 上下文, 参数2 在AndroidManifest中的android:authorities值, 参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, "com.example.senior_download", new File(path));
            //  "com.example.senior_download"为自己项目包名
            
            Intent install = new Intent(Intent.ACTION_VIEW);
            //由于没有在Activity环境下启动Activity,设置下面的标签
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            context.startActivity(install);
        }

        /**
         * android8.x
         */
        @RequiresApi(api = Build.VERSION_CODES.O)
        private static void startInstallO(final Context context, String path) {
		// 权限进行处理
            boolean isGranted = context.getPackageManager().canRequestPackageInstalls();
            if (isGranted) startInstallN(context,path);//安装应用的逻辑(写自己的就可以)
            else new AlertDialog.Builder(context)
                    .setCancelable(false)
                    .setTitle("安装应用需要打开未知来源权限,请去设置中开启权限")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface d, int w) {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                            Activity act = (Activity) context;
                            act.startActivityForResult(intent, UNKNOWN_CODE);
                        }
                    })
                    .show();
        }
    }

在MainActivity里回调

//授权 可以安装apk的权限后,回调此方法,进行安装
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == UNKNOWN_CODE) {
            InstallUtil.installApk(this, Environment.getExternalStorageDirectory() + File.separator + "banmi_330.apk");//再次执行安装流程,包含权限判等
        }
    }

    private static final String TAG = "MainActivity";

Ok获取网络数据

private void ok() {
        OkHttpClient okHttpClient = new OkHttpClient();

        Request request = new Request.Builder().url(apk).build();

        okHttpClient.newCall(request).enqueue(new Callback() {

            private int progess;

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                // 下载 outputStream inputStream
                InputStream inputStream = response.body().byteStream();
                //文件的总长度
                long max = response.body().contentLength();
                String path = Environment.getExternalStorageDirectory() + File.separator + "banmi_330.apk";
                File file = new File(path);

                //当文件不存在,创建出来
                if (!file.exists()) {
                    file.createNewFile();
                }

                FileOutputStream fileOutputStream = new FileOutputStream(file);

                byte[] bytes = new byte[1024];

                int readLength = 0;
                long cureeLength = 0;

                while ((readLength = inputStream.read(bytes)) != -1) {
                    fileOutputStream.write(bytes, 0, readLength);

                    cureeLength += readLength;

                    progess = (int) (cureeLength * 100 / max);
                    progressBar.setProgress(progess);
                    Log.d(TAG, "onResponse: " + progess + "%");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Result.setText(progess+"%");
                        }
                    });
                }

                inputStream.close();
                fileOutputStream.close();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                        InstallUtil.installApk(MainActivity.this, Environment.getExternalStorageDirectory() + File.separator + "banmi_330.apk");
                        // 调用Apk工具类
                    }
                });
            }
        });
    }

内容提供者注册

  <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.baidu.download.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

//file_paths
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <paths>
        <root-path name="download" path="" />
    </paths>
</resources>

你可能感兴趣的:(Android)