Calling startActivity() from outside of an Activit

2019-01-03 04:29发布

I have implemented a ListView in my Android application. I bind to this ListView using a custom subclass of the ArrayAdapter class. Inside the overridden ArrayAdapter.getView(...) method, I assign an OnClickListener. In the onClick method of the OnClickListener, I want to launch a new activity. I get the exception:

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

How can I get the Context that the ListView(the current Activity) is working under?

21条回答
\"骚年 ilove
2楼-- · 2019-01-03 04:31

If you got error because of using create chooser like below:

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"));

Set the flag to create chooser like this :

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);
查看更多
乱世女痞
3楼-- · 2019-01-03 04:31

My situation was a little different, I'm testing my app using Espresso and I had to launch my Activity with ActivityTestRule from the instrumentation Context (which is not the one coming from an Activity).

    fun intent(context: Context) = Intent(context, HomeActivity::class.java)
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

I had to change the flags and add an or bitwise ( | in Java) with Intent.FLAG_ACTIVITY_NEW_TASK

So it results in:

    fun intent(context: Context) = Intent(context, HomeActivity::class.java)
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
查看更多
三岁会撩人
4楼-- · 2019-01-03 04:33
Intent viewIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);    
viewIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);    
startActivity(viewIntent);   

i hope this will work.

查看更多
Bombasti
5楼-- · 2019-01-03 04:33
Intent i= new Intent(context, NextActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
查看更多
看我几分像从前
6楼-- · 2019-01-03 04:34

Instead of using (getApplicationContext) use YourActivity.this

查看更多
家丑人穷心不美
7楼-- · 2019-01-03 04:35

This error goes when startactivity doesn't know which is his activity. So you must add activity before startActivity()

you must set

activity.startActivity(yourIntent);
查看更多
登录 后发表回答