Use the system DownloadManager to achieve automatic updates

First sort out the process: determine the version number --> update greater than the current version number -- "a pop-up box asks whether an update is required (confirm the update) --" use the system DownloadManager to download -- "after the download is complete, jump to the installation page -- "Uninstall after the installation is complete

There is a complete code behind

1. Determine the version number

Get the latest version information

    /**
     * 获取系统版本号
     * */
    public String getAppVersionCode(Context context) {
        int versioncode = 0;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            // versionName = pi.versionName;
            versioncode = pi.versionCode;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versioncode + "";
    }

 Then compare it with the versioncode returned by the interface, if it is smaller than the code returned by the interface, update it, otherwise it does not need to be updated

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main10);
        if (Integer.parseInt(getAppVersionCode(this))>1){
            ShowDialog();
        }
    }

2. A pop-up box asks if an update is required

When you find a new version, you can pop up a box to prompt whether it is updated. In this step, you can customize a beautiful pop-up box and write the download logic in the monitor of the OK button.

    /**
     * 弹框询问是否更新版本
     * */
    private void ShowDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("有新版本");
        builder.setMessage("更新内容");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                getAPK();
            }
        }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

3. Use the system DownloadManager to download

The download method is realized by using the system DownloadManager, which is very simple

    /**
     * 下载apk
     * */
    public void getAPK(){
        DownloadManager mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        String apkUrl = "https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk";
        Uri resource = Uri.parse(apkUrl);
        DownloadManager.Request request=new DownloadManager.Request(resource);
        //下载的本地路径,表示设置下载地址为SD卡的Download文件夹,文件名为mobileqq_android.apk。
        request.setDestinationInExternalPublicDir("Download", "mobileqq_android.apk");
        //start 一些非必要的设置
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setVisibleInDownloadsUi(true);
        request.setTitle("");
        //end 一些非必要的设置
        mDownloadManager.enqueue(request);
    }

 During the download process, you will check the progress in the message notification bar. Here you can update the apk version. Click to install the program, but we want to jump directly to the installation page after downloading, and then go down

4. Jump to the installation page after the download is complete

We need to define a broadcast

/**
 * Created by Forrest.
 * User: Administrator
 * Date: 2020/12/28
 * Description:
 */
public class DownLoadCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())){
            long id=intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);
            Toast.makeText(context, "下载任务已经完成!", Toast.LENGTH_SHORT).show();
            DownloadManager.Query query=new DownloadManager.Query();
            DownloadManager dm= (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            query.setFilterById(id);
            Cursor c=dm.query(query);
            if (c!=null){
                try {
                    if (c.moveToFirst()){
                        String filename=c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                        int status=c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
                        if (status==DownloadManager.STATUS_SUCCESSFUL){
                            Uri uri=Uri.fromFile(new File(filename));
                            if (uri!=null){
                                Intent intent1=new Intent(Intent.ACTION_VIEW);
                                intent1.setDataAndType(uri,"application/vnd.android.package-archive");
                                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(intent1);
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    return;
                }finally {
                    c.close();
                }
            }
        }
    }
}

Then register in the manifest file

    <application
        android:name="com.dhy.health.app.MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        //......
        <receiver android:name="com.dhy.health.utils.DownLoadCompleteReceiver">
            <intent-filter>
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
            </intent-filter>
        </receiver>
        //......
    </application>

After the download is complete, it will automatically jump to the installation page. You only need to click Install. After the installation is successful, select Finish or Open. No matter which one you click, you will be asked whether to delete the downloaded installation package. Delete it and it will be ok. Does not take up memory space

Paste the complete code below

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

import com.dhy.health.svndemo.R;

public class Main10Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main10);
        if (Integer.parseInt(getAppVersionCode(this))>1){
            ShowDialog();
        }
    }
    /**
     * 获取系统版本号
     * */
    public String getAppVersionCode(Context context) {
        int versioncode = 0;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            // versionName = pi.versionName;
            versioncode = pi.versionCode;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versioncode + "";
    }

    /**
     * 获取系统版本名称
     * */
    public String getAppVersionName(Context context) {
        String versionName=null;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }
    /**
     * 弹框询问是否更新版本
     * */
    private void ShowDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("有新版本");
        builder.setMessage("更新内容");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                getAPK();
            }
        }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 下载apk
     * */
    public void getAPK(){
        DownloadManager mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        String apkUrl = "https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk";
        Uri resource = Uri.parse(apkUrl);
        DownloadManager.Request request=new DownloadManager.Request(resource);
        //下载的本地路径,表示设置下载地址为SD卡的Download文件夹,文件名为mobileqq_android.apk。
        request.setDestinationInExternalPublicDir("Download", "mobileqq_android.apk");
        //start 一些非必要的设置
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setVisibleInDownloadsUi(true);
        request.setTitle("");
        //end 一些非必要的设置
        mDownloadManager.enqueue(request);
    }
}

 

Guess you like

Origin blog.csdn.net/lanrenxiaowen/article/details/111832274