从 FirebaseInstanceId.getInstance().getId() 迁移到 FirebaseInstallations.getInstance().getId()

aer*_*xr1 5 java android kotlin firebase-cloud-messaging

我必须从已弃用的同步 api 迁移FirebaseInstanceId.getInstance().getId();到新的异步 firebase api:

FirebaseInstallations.getInstance().getId().addOnCompleteListener( task -> {
                                if (!task.isSuccessful()) {
                                    Log.w(TAG, "getInstanceId failed", task.getException());
                                    return;
                                }
                                // Get new Instance ID 
                                String id = task.getResult();
                            });
Run Code Online (Sandbox Code Playgroud)

我的问题是,在我的旧项目中,在我的代码的许多不同点中,已经调用了类似以下方法的方法,并且所有被调用者都期望在没有回调的情况下在线响应同步:

public static String getDeviceId() {
    if (deviceId == null) {
        initDeviceId();
    }
    return deviceId;
}

private static void initDeviceId() {
    deviceId = FirebaseInstanceId.getInstance().getId();
}
Run Code Online (Sandbox Code Playgroud)

如何在不重写所有项目的情况下迁移代码?我想过以这种方式编辑上述方法:

public static String getDeviceId() {
    if (deviceId == null) {
        deviceId = workerThread.submit(initDeviceId()).get()
    }
    return deviceId;
}

private fun initDeviceId():Callable<String?>{
    return Callable {
        val latch = CountDownLatch(1)
        var result:String ?= null
        FirebaseInstallations.getInstance().id.addOnCompleteListener{ 
            task -> result = task.result
                    latch.countDown()
        }
        
        latch.await()
        result
    }
}
Run Code Online (Sandbox Code Playgroud)

但以这种方式我冒着阻塞主线程的风险。