2023年8月10日 星期四

以下是一个简单的Android版本更新的代码示例:

首先,在AndroidManifest.xml文件中添加文件读写和网络访问的权限:


创建一个版本更新的类,例如UpdateManager.java:

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Environment;

public class UpdateManager {
    private Context mContext;
    private String mUpdateUrl;

    public UpdateManager(Context context, String updateUrl) {
        mContext = context;
        mUpdateUrl = updateUrl;
    }

    public void checkUpdate() {
        // 在这里检查版本更新的逻辑,例如从服务器获取最新版本号和新版本的下载地址

        // 假设获取到最新版本号为latestVersion和下载地址为downloadUrl
        int currentVersion = BuildConfig.VERSION_CODE;
        int latestVersion = 2;
        String downloadUrl = "http://www.example.com/apk/app.apk";

        if (latestVersion > currentVersion) {
            showUpdateDialog(downloadUrl);
        }
    }

    private void showUpdateDialog(final String downloadUrl) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("版本更新")
                .setMessage("发现新版本,是否立即更新?")
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startDownload(downloadUrl);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void startDownload(String downloadUrl) {
        DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(downloadUrl);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        // 设置下载文件存放的路径
        String apkName = "app.apk";
        String destinationUri = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + apkName;
        request.setDestinationUri(Uri.parse("file://" + destinationUri));
        // 设置在什么网络情况下进行下载
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        // 设置是否显示下载通知栏
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // 开始下载
        downloadManager.enqueue(request);
    }
}

在需要检查版本更新的地方调用UpdateManager类的checkUpdate方法,例如在MainActivity的onCreate方法中:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String updateUrl = "http://www.example.com/api/check_update";
    UpdateManager updateManager = new UpdateManager(this, updateUrl);
    updateManager.checkUpdate();
}

在这个示例中,我们通过检查服务器上的最新版本号和下载地址来判断是否需要进行版本更新。如果需要更新,就显示一个对话框询问用户是否立即更新,然后使用DownloadManager开始下载新版本的APK文件。

作者:李世民  创建时间:2023-08-10 18:03
最后编辑:李世民  更新时间:2023-08-10 18:05