Flutter应用版本检测:本地版本与应用商店版本对比及更新提示
实现App Store/Play Store版本检测与更新提示功能
iOS(Swift)实现方案
1. 获取当前应用版本
从App的Info.plist中读取当前安装的版本号:
func getCurrentAppVersion() -> String? { return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String }
2. 拉取App Store中的最新版本
调用苹果官方iTunes Search API获取对应App的最新版本信息,记得替换成你的App Bundle ID:
func fetchAppStoreLatestVersion(completion: @escaping (String?, Error?) -> Void) { guard let url = URL(string: "https://itunes.apple.com/lookup?bundleId=com.yourcompany.yourapp") else { completion(nil, NSError(domain: "InvalidURL", code: -1, userInfo: nil)) return } let task = URLSession.shared.dataTask(with: url) { data, _, error in guard let data = data, error == nil else { completion(nil, error) return } do { let result = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] let results = result?["results"] as? [[String: Any]] let latestVersion = results?.first?["version"] as? String completion(latestVersion, nil) } catch { completion(nil, error) } } task.resume() }
3. 版本号对比逻辑
针对多段式版本号(如1.2.3),拆分成分量逐一比较:
func isNewVersionAvailable(currentVersion: String, storeVersion: String) -> Bool { let currentComponents = currentVersion.split(separator: ".").compactMap { Int($0) } let storeComponents = storeVersion.split(separator: ".").compactMap { Int($0) } let maxCount = max(currentComponents.count, storeComponents.count) for i in 0..<maxCount { let currentVal = i < currentComponents.count ? currentComponents[i] : 0 let storeVal = i < storeComponents.count ? storeComponents[i] : 0 if storeVal > currentVal { return true } else if storeVal < currentVal { return false } } return false }
4. 弹出更新提示
检测到新版本时,用系统弹窗引导用户跳转至App Store:
func showUpdateAlert(storeVersion: String) { let alert = UIAlertController(title: "发现新版本 \(storeVersion)", message: "更新后可获得更好的体验,立即更新?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "稍后再说", style: .cancel)) alert.addAction(UIAlertAction(title: "立即更新", style: .default) { _ in guard let url = URL(string: "itms-apps://itunes.apple.com/app/id<你的AppID>") else { return } if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } }) DispatchQueue.main.async { UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true) } }
整合调用
在App启动阶段(如SceneDelegate的sceneDidBecomeActive)执行检测:
func checkForUpdates() { guard let currentVersion = getCurrentAppVersion() else { return } fetchAppStoreLatestVersion { [weak self] storeVersion, error in guard let storeVersion = storeVersion, error == nil else { // 版本获取失败,正常进入应用 return } if self?.isNewVersionAvailable(currentVersion: currentVersion, storeVersion: storeVersion) == true { self?.showUpdateAlert(storeVersion: storeVersion) } // 无新版本,正常进入应用 } }
Android(Kotlin)实现方案
推荐使用Google官方Play Core App Update API,避免网页爬取的兼容性问题。
1. 添加依赖
在build.gradle(Module level)中添加Play Core库依赖:
dependencies { implementation 'com.google.android.play:app-update:2.1.0' }
2. 初始化更新管理器
private val appUpdateManager by lazy { AppUpdateManagerFactory.create(applicationContext) }
3. 检测更新
private const val REQUEST_CODE_UPDATE = 1001 fun checkForAppUpdates() { val appUpdateInfoTask = appUpdateManager.appUpdateInfo appUpdateInfoTask.addOnSuccessListener { appUpdateInfo -> // 强制更新(用户必须更新才能继续使用) if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) { appUpdateManager.startUpdateFlowForResult( appUpdateInfo, AppUpdateType.IMMEDIATE, this, REQUEST_CODE_UPDATE ) } else if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) { // 灵活更新(用户可选择稍后更新) showFlexibleUpdateDialog(appUpdateInfo) } // 无新版本或更新不可用,正常进入应用 }.addOnFailureListener { // 更新检测失败,正常进入应用 } } // 灵活更新的自定义弹窗 private fun showFlexibleUpdateDialog(appUpdateInfo: AppUpdateInfo) { AlertDialog.Builder(this) .setTitle("发现新版本") .setMessage("新版本已上线,是否现在更新?") .setPositiveButton("立即更新") { _, _ -> appUpdateManager.startUpdateFlowForResult( appUpdateInfo, AppUpdateType.FLEXIBLE, this, REQUEST_CODE_UPDATE ) } .setNegativeButton("稍后再说", null) .show() }
4. 处理更新结果
在onActivityResult中处理更新完成后的逻辑:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE_UPDATE) { if (resultCode != RESULT_OK) { // 更新失败,可提示用户稍后重试 } } }
启动检测
在MainActivity的onCreate或onResume中调用检测方法:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) checkForAppUpdates() }
注意事项
- 网络请求需在后台线程执行,避免阻塞UI
- 版本对比逻辑需覆盖多段式版本号的各种情况(如
1.3vs1.2.5) - 若商店版本获取失败,默认让应用正常启动,不要阻塞用户使用
- Android端使用Play Core API时,需确保应用已发布至Play Store(测试可使用内部测试轨道)
内容的提问来源于stack exchange,提问作者Ranjith
相关产品推荐
相关产品推荐

