If FirstActivity
is the root of the task, and it finishes itself and launches SecondActivity
, then calling isTaskRoot()
in SecondActivity
immediately will return false
, because the FirstActivity
's finishing happens asynchronously and thus isn't done yet. Waiting for a second and then calling isTaskRoot()
returns true.
public class FirstActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); finish(); startActivity(new Intent(this, SecondActivity.class)); } }
public class SecondActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected void onResume() { super.onResume(); ((TextView)findViewById(R.id.tv1)) .setText("isTaskRoot() in onResume(): " + isTaskRoot()); new Handler().postDelayed(new Runnable() { @Override public void run() { ((TextView)findViewById(R.id.tv2)) .setText("isTaskRoot() after 1s: " + isTaskRoot()); } }, 1000); } }
Is there a way to …
(optimally) find out whether the activity will be the task root eventually, or,
(better than nothing) get some sort of notification/callback once the task is in its "final" state and thus isTaskRoot()
will return the "truth"?
You opened the new activity from another activity with startActivityForResult. In that case you can just call the finishActivity() function from your code and it'll take you back to the previous activity.
On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.
A task is a collection of activities that users interact with when trying to do something in your app. These activities are arranged in a stack—the back stack—in the order in which each activity is opened. For example, an email app might have one activity to show a list of new messages.
I've had a similar problem and I wanted tight control over exactly who the root activity is. In my case, the root could only be one of my own activities (not 3rd party ones), so I was able to use the following approach:
I extended the Application
class, added a weak reference to an activity called currentRootActivity
and added synchronized getter and setter.
Then I managed this state by myself when activities were created / destroyed. My use case was a little special because I was looking to replace one root with another, so I knew exactly where to reset my new state variable, but I'm pretty sure you can do the same.
I was even able to add this state logic in a shared base class for all of my activities. So this wasn't as disgusting as it sounds :)
As mentioned in the comments, the activity method isFinishing
might also come in handy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With