官方文档: https ://developer.android.com/guide/app-bundle/in-app-updates
约束:应用内更新仅适用于运行 Android 5.0(API 级别 21)或更高版本的设备
第一步: 添加依赖:
dependencies {
implementation 'com.google.android.play:core:1.5.0'
...
}
第 2 步:检查更新可用性并在可用时开始
创建 AppUpdateManagerFactory 的实例
appUpdateManager = AppUpdateManagerFactory.create(context);
为 FLEXIBLE 更新请求的响应注册监听器
appUpdateManager.registerListener(listener);
之后得到 appUpdateInfo
Task<AppUpdateInfo> appUpdateInfo = appUpdateManager.getAppUpdateInfo();
appUpdateInfo.addOnSuccessListener(new OnSuccessListener<AppUpdateInfo>() {
@Override
public void onSuccess(AppUpdateInfo appUpdateInfo) {
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE) {
if (appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
Log.d("App update A", "Flexible");
int updateType = FLEXIBLE;
requestUpdate(appUpdateInfo, updateType);
} else if (appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
Log.d("App update B", "IMMEDIATE");
int updateType = IMMEDIATE;
requestUpdate(appUpdateInfo, updateType);
}
}
}
});
在那个 requestUpdate() 方法之后,
private void requestUpdate(AppUpdateInfo appUpdateInfo, int updateType) {
try {
appUpdateManager.startUpdateFlowForResult(appUpdateInfo, updateType, HomeActivity.this, MY_REQUEST_CODE);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
第三步:监听更新状态
最后是听者
InstallStateUpdatedListener listener = new InstallStateUpdatedListener() {
@Override
public void onStateUpdate(InstallState state) {
Log.d("installState", state.toString());
if (state.installStatus() == InstallStatus.DOWNLOADED) {
// After the update is downloaded, show a notification
// and request user confirmation to restart the app.
// SnackBarManager.getSnackBarManagerInstance().showSnackBar(GaanaActivity.this, "An update has just been downloaded.", true);
popupSnackbarForCompleteUpdate();
}
}
};
popupSnackbarForCompleteUpdate() 方法,
private void popupSnackbarForCompleteUpdate() {
Snackbar snackbar =
Snackbar.make(findViewById(android.R.id.content), "An update has just been downloaded.", Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("Restart", view -> appUpdateManager.completeUpdate());
snackbar.setActionTextColor(getResources().getColor(android.R.color.white));
snackbar.show();
}
第 4 步:获取更新状态的回调
您也可以捕获结果,
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_REQUEST_CODE) {
System.out.println("App Update = " + resultCode);
if (resultCode != RESULT_OK) {
System.out.println("Update flow failed! Result code: " + resultCode);
// If the update is cancelled or fails,
// you can request to start the update again.
}
}
}
您还必须取消注册侦听器
@Override
public void onDestroy() {
super.onDestroy();
Log.d("installState", "destroy");
appUpdateManager.unregisterListener(listener);
}