我确信我的语法在某个地方是错误的...... 我有以下方法:
private int getVersionStatus(){
// Creates instance of the manager.
AppUpdateManager appUpdateManager = AppUpdateManagerFactory.create(this);
// Returns an intent object that you use to check for an update.
Task<AppUpdateInfo> appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
// Checks that the platform will allow the specified type of update.
appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
versionCode=appUpdateInfo.updateAvailability();
Log.d("ADebugTag", "Value: " + String.valueOf(appUpdateInfo.updateAvailability()));
Log.d("ADebugTag", "Value123: " + String.valueOf(versionCode));
});
return versionCode;
}
当我从 onCreate()
调用该方法时,两个日志都打印正确的值,但返回的 int (versionCode) 不同......这是怎么回事?
最佳答案
这是因为 versionCode
在调用 addOnSuccessListener
之前返回。设置监听器后,getVersionCode()
返回,并最终调用 addOnSuccessListener
的 lambda。
使用您现在使用的 API,无法返回值。您可以做的是将回调作为参数传递给 getVersionCode()
。
一个例子:
interface Callback {
void setVersion(int version);
}
private void getVersionStatus(Callback callback){
// Creates instance of the manager.
AppUpdateManager appUpdateManager = AppUpdateManagerFactory.create(this);
// Returns an intent object that you use to check for an update.
Task<AppUpdateInfo> appUpdateInfoTask = appUpdateManager.getAppUpdateInfo();
// Checks that the platform will allow the specified type of update.
appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
callback.setVersion(appUpdateInfo.updateAvailability());
});
}
private void yourOtherFuncton() {
getVersionStatus(version -> {
Log.d("ADebugTag", "Value: " + String.valueOf(version));
});
}
这基本上与 PPartisan 的答案相同,具有您自己定义的接口(interface)。
关于java - int 方法返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58819417/