取消生物特征认证时发出吐司的问题

时间:2019-10-12 19:04:31

标签: android kotlin

用户取消BiometricPrompt时,创建Toast时遇到一些问题。

我遇到了错误:

java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()

这是我要影响的区域的代码:

object : BiometricPrompt.AuthenticationCallback()
            {
                override fun onAuthenticationError(errorCode: Int, errString: CharSequence?) {
                    super.onAuthenticationError(errorCode, errString)
                    Toast.makeText(applicationContext, "Authentication Error. Please try again :)", Toast.LENGTH_LONG)
                        .show()
                }

                // onAuthSucceeded would be here.

                override fun onAuthenticationFailed() {
                    super.onAuthenticationFailed()
                    Toast.makeText(applicationContext, "Authentication Failed. Please try again :)", Toast.LENGTH_LONG)
                        .show()
                }
            }

我尝试在Toast.makeText之前添加Looper.prepare(),但这无济于事。

在此先感谢您的帮助:)

3 个答案:

答案 0 :(得分:0)

之所以会这样,是因为您在工作线程上调用Toast,

您可以使用以下代码在主线程上运行它。

activity.runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(activity, "Authentication Error. Please try again :)", Toast.LENGTH_SHORT).show();
  }
});

答案 1 :(得分:0)

发生此问题是因为在工作线程上调用了以上吐司

您可以使用以下代码在主线程上运行它。

Activity.runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(activity, "Authentication Error. Please try again :)", Toast.LENGTH_SHORT).show();
  }
});

答案 2 :(得分:0)

您必须在UI线程中调用Toast。在Kotlin中,就像下面的代码

runOnUiThread(
        object : Runnable {
            override fun run() {
                Toast.makeText(applicationContext, "Authentication Error. Please try again :)", Toast.LENGTH_LONG)
                        .show()
            }
        }
)
相关问题