I. Demand analysis

1. Query the online version number and compare it with the local version number. 2. If the online version is larger than the local version, download the online version. 3. Install the downloaded version number and replace the current old version

Second, the permissions

According to the above requirements, we can know that the permissions needed should be network permissions, local file write permissions, local file read permissions. Use network permissions to get the online version number, download it and save it locally, and then get it locally when you install it. In addition, in 8.0, Google put the management of the installation permissions of unknown apps on each app. Each app has a setting switch that allows the installation of unknown apps, so permissions are also required here

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>-- 8.0 installation permissionCopy the code

Three, steps,

1. First determine whether users above 8.0 need to check whether they have permissions. Some users directly check version updates without applying for them

if(! checkInstall()){if (conn) {
                this.checkUpdate(splashView);
            } else {
                Toast.makeText(this, "Please check the network ~", Toast.LENGTH_LONG).show(); }} /** * If you want your application to automatically install the new version of apK, you must enable this permission for your applicationcheckInstall() {
        boolean haveInstallPermission;
        if(build.version.sdk_int >= build.version_codes.o) {haveInstallPermission = getPackageManager().canRequestPackageInstalls();if(! HaveInstallPermission) {/ / no access android. Support. V7. App. The AlertDialog AlertDialog = new android.support.v7.app.AlertDialog.Builder(this) .setTitle("Please enable unknown source privileges.")
                        .setMessage("Application requires permission to install apps from unknown sources. Please go to Settings to enable permission.")
                        .setCancelable(false)
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        Toast.makeText(WelcomeActivity.this, "You have refused permission, the application cannot work properly!", Toast.LENGTH_SHORT).show();
                                        finish();
                                    }
                                })
                        .setPositiveButton("Go set", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                toInStallPermissionSettingActivity();
                            }
                        }).create();
                alertDialog.show();
                return true; }}return false;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void toInStallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:"+ getPackageName()); Intent Intent = new Intent(settings. action_manage_unknown_sources, packageURI); startActivityForResult(intent, REQUEST_CODE_INSTALL_PERMISSION); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data);if (resultCode==RESULT_OK&&requestCode==REQUEST_CODE_INSTALL_PERMISSION){
            if (conn) {
                this.checkUpdate(splashView);
            } else {
                Toast.makeText(this, "Please check the network ~", Toast.LENGTH_LONG).show(); }}else {
            finish();
            Toast.makeText(WelcomeActivity.this, "You have refused permission, the application cannot work properly!", Toast.LENGTH_SHORT).show(); }}Copy the code

2 Network request detection update

Public void checkUpdate(final View splashView) {// Create okHttpClient object okHttpClient mOkHttpClient = new OkHttpClient(); Request request = new Request.Builder().url(Urls.UPDATEXML).build(); //http://ushevapp-10060464.cos.myqcloud.com/version.xml mOkHttpClient.newCall(request).enqueue( new okhttp3.Callback() {
                    @Override
                    public void onFailure(okhttp3.Call call, IOException e) {
                        Message msg = new Message();
                        msg.what = 0;
                        mmHandler.sendMessage(msg);
                        Log.d("h_bl"."Failure");
                    }

                    @Override
                    public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                        InputStream is = null;
                        byte[] buf = new byte[2048];
                        int len = 0;
                        String SDPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                        try {
                            is = response.body().byteStream();
                            ParseXmlService pxs = new ParseXmlService();
                            stringStringHashMap = pxs.parseXml(is);
                            Message msg = new Message();
                            msg.what = 1;
                            mmHandler.sendMessage(msg);
                            Log.d("h_bl"."Check software update file downloaded successfully");
                        } catch (Exception e) {
                            Message msg = new Message();
                            msg.what = 0;
                            mmHandler.sendMessage(msg);
                            Log.d("h_bl"."Failed to download software update for document detection");
                        } finally {
                            try {
                                if(is ! = null) { is.close(); } } catch (IOException e) { } } } } );Copy the code

3, go to the service download APK, and then install

/** * download file :Okhttp */ private voidloadFileByOkhttp() {
        initNotification();
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
//                .addHeader("Accept-Encoding"."identity")
                .build();

        mOkHttpClient.newCall(request).enqueue(
                new Callback() {
                    @Override
                    public void onFailure(okhttp3.Call call, IOException e) {
                        cancelNotification();
                        Log.d("h_bl"."New version download failed");
                    }

                    @Override
                    public void onResponse(okhttp3.Call call, Response response) throws IOException {
                        InputStream is = null;
                        byte[] buf = new byte[2048];
                        int len = 0;
                        FileOutputStream fos = null;
                        try {
                            is = response.body().byteStream();
                            long total = response.body().contentLength();

                            File file = new File(destFileDir, destFileName);
                            fos = new FileOutputStream(file);
                            long sum = 0;
                            int progress = 0;
                            while((len = is.read(buf)) ! = -1) { fos.write(buf, 0, len); sum += len; Progress = (int) (sum * 1.0f/total * 100); updateNotification(progress); }if (progress == 100) {
                                cancelNotification();
                                installApk(file);

                            }
                            fos.flush();
                            Log.d("h_bl"."Apk file downloaded successfully");
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                if(is ! = null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } try {if(fos ! = null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); }}}}); }Copy the code

In addition, there is also an 8·0 pit, but there is no special processing for the download and no notification display, so look at the code

/** * Initializes Notification */ public voidinitNotification() {
        destFileDir = getTempDirectoryPath();
        notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder = new NotificationCompat.Builder(mContext, PUSH_CHANNEL_ID);
            NotificationChannel channel = new NotificationChannel(PUSH_CHANNEL_ID, PUSH_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.enableVibration(false);
            channel.setVibrationPattern(new long[]{0});
            channel.setSound(null, null);
            if(notificationManager ! = null) { notificationManager.createNotificationChannel(channel); } builder.setSmallIcon(R.mipmap.logo) .setContentText("0%")
                    .setContentTitle("Renewal of Housing Insurance Services")
                    .setChannelId(PUSH_CHANNEL_ID);
        } else {
            builder = new NotificationCompat.Builder(mContext)
                    .setSmallIcon(R.mipmap.logo)
                    .setContentText("0%")
                    .setContentTitle("Renewal of Housing Insurance Services");
        }
        notificationManager.notify(NOTIFY_ID, builder.build());
    }
Copy the code

Finally install APK, pay attention to some details, update the package and the old package should have the same signature file, otherwise it will fail to install, there is a pit 8.0, before later give permission to solve

/** * install software ** @param file */ private void installApk(file file) {Uri Uri = uri.fromfile (file); Intent install = new Intent(Intent.ACTION_VIEW); install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); install.setDataAndType(uri,"application/vnd.android.package-archive"); // Execute intent to install McOntext.startactivity (install); }Copy the code

Oh, now it should automatically update no problem can be solved, if you have any questions welcome to correct, learn from each other