java - int 方法返回错误值

标签 java android

我确信我的语法在某个地方是错误的...... 我有以下方法:

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/

相关文章:

java数组打印星号方框

java - Tomcat 不读取链接作为参数

android - 使用共享首选项单击后一分钟后显示 View

android - Hello World Android-错误创建

android - SQLite 数据库浏览器 - 导入国家字体时出现问题

Android build gradle 太慢(依赖解析)

javascript - Wicket - 使用 AJAX 刷新组件 - 文档元素后的垃圾

java - JVM如何维护类数据和堆对象之间的关系?

java - 如何通过 Java 包装器执行 IBM Watson Retrieve And Rank API 中的 searchAndRank 方法

java - 将媒体项添加到 MediaBrowserService