gpt4 book ai didi

在 Activity 以外的类中使用的 Android Context

转载 作者:行者123 更新时间:2023-11-30 01:08:33 25 4
gpt4 key购买 nike

在我的主要 Activity 中:

 LoginUser.loginUser(username.getText().toString(),password.getText().toString(), getApplication());

所以在我的 LoginUser 类中,我想启动一个这样的对话框:

new AlertDialog.Builder(context).set.....

但是失败了,像这样获取故障信息:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

我也想用like

Intent intent = new Intent(context, ABC.class)
context.startActivity(intent);

同样失败。并像这样获取故障信息:

android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

我很困惑所有这些,有人可以帮助我吗?非常感谢!

最佳答案

我不完全确定你在做什么,但对于第一个问题,你似乎在尝试使用非 Activity 上下文来显示对话框。

TL;DR,您不能使用具有应用程序上下文的 AlertDialog,它需要一个 Activity。考虑这样的事情:

new AlertDialog.Builder(<activity>)

第二个问题也类似,你可以用application context来启动一个activity,但是你需要把它作为一个新的task来启动。为此,您需要添加一个标志。 (虽然,这不被认为是好的做法)

Intent intent = new Intent(context, MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

检查 here了解更多关于在 Android 中您可以做什么和不能做什么的信息。

关于在 Activity 以外的类中使用的 Android Context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38670180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com