我已经在我的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(当前活动)正在工作的上下文?


当前回答

使用这段代码。对我来说没问题。分享活动之外的东西:

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");

// Append Text
String Text = "Your Text Here"

intent.putExtra(Intent.EXTRA_TEXT, Text);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Intent shareIntent = Intent.createChooser(intent,"Share . . . ");
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
G.context.getApplicationContext().startActivity(shareIntent);

其他回答

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

Intent viewIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);    
viewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    
startActivity(viewIntent);   

我希望这能奏效。

如果你因为使用创建选择器而出错,如下所示:

Intent sharingIntent = new Intent(Intent.ACTION_VIEW);
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sharingIntent.setData(Uri.parse("http://google.com"));
startActivity(Intent.createChooser(sharingIntent, "Open With"));

设置标志以创建选择器,如下所示:

Intent sharingIntent = new Intent(Intent.ACTION_VIEW);
sharingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sharingIntent.setData(Uri.parse("http://google.com"));

Intent chooserIntent = Intent.createChooser(sharingIntent, "Open With");
chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(chooserIntent);

芬兰湾的科特林版本

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

因为添加标志会影响event_flow和stack_history,所以最好将“应用上下文”传递给非活动,从那里你需要以以下方式调用一个活动类:

“ActivityClassName。(当你以这种方式传递上下文时,它将包含你从非活动场景中调用一个活动所需的所有细节和信息)

所以不需要设置或添加标志,这将在任何情况下工作良好。