同步获取Firebase用户令牌 [英] Getting Firebase user token synchronously

查看:84
本文介绍了同步获取Firebase用户令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取Firebase令牌以验证对Rest API的调用.我可以使用以下代码异步生成令牌.

I am trying to get a Firebase token to authenticate my calls to a Rest API. I can generate the tokens asynchronously with the following code.

    FirebaseUser mUser = App.getFirebaseAuth().getCurrentUser();
    if (mUser!=null) {
        mUser.getIdToken(false)
                .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
                    public void onComplete(@NonNull Task<GetTokenResult> task) {
                        if (task.isSuccessful()) {
                            ID_TOKEN = task.getResult().getToken();
                        } else {
                            Log.e(App.TAG, "Firebase Token task ended with error.");
                        }
                    }
                });
    } else {
        Log.i(App.TAG,"User is null, no Firebase Token available");
    }

ID_TOKEN是保存结果的静态字符串变量. 问题是,我正在构建请求并添加身份验证标头.

The ID_TOKEN is a static string variable that holds the result. The issue is, I am constructing my request and adding the authentication headers.

        headers.put("Authentication",
                "Bearer  + ID_TOKEN);

问题在于,由于Firebase令牌是异步检索的,因此某些人认为ID_TOKEN变量为空.我尝试强制线程使用

The issue is, since the Firebase token is retrieved asynchronously, sometims the ID_TOKEN variable is empty. I tried forcing the thread to wait for the task using

Tasks.await(任务)

Tasks.await(task)

但是我得到一个例外,说不能在主线程中调用await.

But I get an exception saying await cannot be invoked in the main thread.

还有其他方法可以同步获取令牌,还是让线程等待任务完成?

Is there any other way to get the token synchronously, or make the thread wait until the tasks finishes?

推荐答案

强制某项在主线程上同步运行是一个非常糟糕的主意.它可能会锁定您的应用程序,并可能导致其进入ANR.这就是为什么当您尝试运行Tasks.await()时Android会抱怨的原因-它知道可能存在问题.

It's a really bad idea to force something to run on the main thread synchronously. It could lock up your app and possibly cause it to ANR. That's why Android it complains when you try to run Tasks.await() - it knows there could be a problem.

学习如何进行异步编程以正确的方式进行操作要好得多.您将必须在必须提供的侦听器中接收令牌.

It's far better to learn how to do do asynchronous programming to do this the right way. You will have to receive the token in the listener that you have to provide.

请阅读此博客了解有关Firebase API为何异步的更多信息.

Please read this blog to learn more about why the Firebase APIs are asynchronous.

这篇关于同步获取Firebase用户令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆