如果 FirstActivity
是任务的根,并完成自身和发射 SecondActivity
,然后调用 isTaskRoot()
在 SecondActivity
立即返回假
,因为 FirstActivity
的整理异步发生,因而还没有完成。等待一秒钟的然后的调用 isTaskRoot()
返回true。
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 …
(最佳)找出活动是否将任务根的最终的,或者,
获得某种形式的通知/回调,一旦任务是在它的最后的状态,因此(聊胜于无) isTaskRoot()
将返回真理?
(better than nothing) get some sort of notification/callback once the task is in its "final" state and thus isTaskRoot()
will return the "truth"?
我有一个类似的问题,我想严格控制究竟是谁的根系活力。在我的情况下,根只能是我自己的活动(没有第三方的),所以我能够使用下面的方法:
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:
我延长了应用程序
类,增加了一个弱引用名为 currentRootActivity
的活动,并添加同步的getter和setter
I extended the Application
class, added a weak reference to an activity called currentRootActivity
and added synchronized getter and setter.
然后我通过自己管理该状态时创建/销毁活动。我用例是有点特别,因为我一直在寻找代替一个根与另一个,所以我知道确切位置重置我新的状态变量,但我是pretty的肯定,你可以这样做。
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 :)
正如评论,活动方法 isFinishing
也可能会派上用场。
As mentioned in the comments, the activity method isFinishing
might also come in handy.