我已经在我的Android应用程序中实现了一个ListView。我使用ArrayAdapter类的自定义子类绑定到这个ListView。在重写的ArrayAdapter.getView(…)方法中,我分配了一个OnClickListener。在OnClickListener的onClick方法中,我想启动一个新活动。我得到了一个异常:

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

我怎样才能得到ListView(当前活动)正在工作的上下文?


当前回答

如果使用数据绑定,只需获取上下文

binding.root.context

这解决了我的问题。

其他回答

从视图的Activity上下文外部调用startActivity()

val context = activity.applicationContext
openBrowser(context, MenuUrl.TERM_CONDITION)

Do

   1. val context = binding.root.context // If you are using view binding
   2. val context = yourView.context // If you are not use view binding
    openBrowser(context, MenuUrl.TERM_CONDITION)

谢谢你!

在我看来,最好在Activity.class的代码中使用startActivity()方法。如果您在适配器或其他类中使用它,则会导致该结果。

在Android 28(Android P)启动活动

if ((intent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) == 0
        && (targetSdkVersion < Build.VERSION_CODES.N
                || targetSdkVersion >= Build.VERSION_CODES.P)
        && (options == null
                || ActivityOptions.fromBundle(options).getLaunchTaskId() == -1)) {
    throw new AndroidRuntimeException(
            "Calling startActivity() from outside of an Activity "
                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
                    + " Is this really what you want?");
}

所以最好的方法是添加FLAG_ACTIVITY_NEW_TASK

Intent intent = new Intent(context, XXXActivity.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);

你可以用addFlags而不是setFlags来实现

myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

根据文档,它做到了:

添加额外的标志到意图(或与现有的标志值)。


EDIT

当你使用可能改变历史堆栈的标志时要小心,Alex Volovoy的回答说:

...避免设置标志,因为它会干扰正常的事件和历史堆栈流。

芬兰湾的科特林版本

val intent = Intent(Intent.ACTION_EDIT, ContactsContract.Profile.CONTENT_URI)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
this.startActivity(intent)