Android 提供應用程式內更新功能,有兩種更新模式:強制更新和靈活更新,滿足不同應用場景的需求。
這兩種模式各具特色,開發者可以根據應用需求選擇適合的更新方式,提升用戶體驗與更新效率。
// In your app's build.gradle file:
...
dependencies {
implementation 'com.google.android.play:app-update:2.1.0'
}
AppUpdateManager appUpdateManager = AppUpdateManagerFactory.create(this);
// 檢查是否有更新
Task<AppUpdateInfo> appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
appUpdateInfoTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
&& appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
try {
// 啟動立即更新流程
appUpdateManager.startUpdateFlowForResult(appUpdateInfo, this,
AppUpdateOptions.newBuilder(AppUpdateType.IMMEDIATE).build(), UPDATE_REQUEST_CODE
);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == UPDATE_REQUEST_CODE) {
if (resultCode != RESULT_OK) {
// 更新被取消或失敗
Toast.makeText(this, "更新失敗或被取消", Toast.LENGTH_SHORT).show();
}
}
}
Task<AppUpdateInfo> appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE &&
appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
// 發起彈性更新
try {
appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
this,
AppUpdateOptions.newBuilder(AppUpdateType.FLEXIBLE).build(),
FLEXIBLE_UPDATE_REQUEST_CODE
);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FLEXIBLE_UPDATE_REQUEST_CODE) {
if (resultCode != RESULT_OK) {
// 處理更新被取消的情況
Log.d("Update", "彈性更新取消");
} else {
Log.d("Update", "彈性更新成功啟動");
}
}
}
@Override
protected void onResume() {
super.onResume();
// 檢查更新是否下載完成
appUpdateManager.getAppUpdateInfo().addOnSuccessListener(appUpdateInfo -> {
if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
// 提示用戶重啟應用以完成更新
Snackbar.make(findViewById(android.R.id.content), "更新下載完成,請重啟應用以完成更新。",Snackbar.LENGTH_INDEFINITE)
.setAction("重新啟動", v -> {appUpdateManager.completeUpdate();}).show();
}
});
}