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

标签 android android-intent android-activity android-alertdialog android-context

在我的主要 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/

相关文章:

android - MainActivity NoClassDefFoundError

android - "Activity"类中成员变量的持久化

android - 是否可以安装自己的拨号器应用程序来处理来电和去电?

android - 如何从Android中的原始文件夹一个接一个地播放音频文件

java - 如何在 2 秒内不允许用户交互

java - 导入 GreenDroid 时出现问题

android - 如何只旋转图像,而不是 Imageview

android - 如何在不撰写邮件的情况下发送邮件?

java - 一项 Activity 中基于所选 ListView 项的多个上下文菜单

android - 将抽屉导航项目与 fragment 同步