问题描述:假设当前Activity为A,如果这时用户打开一个新的Activity B,那么B的onResume和A的onPause哪个先执行呢?
废话少说,上代码,Activity A :
public class AActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_a); } public void goToBActivity(View view) { startActivity(new Intent(this, BActivity.class)); } @Override protected void onPause() { super.onPause(); System.out.println("AActivity.onPause"); } @Override protected void onStop() { super.onStop(); System.out.println("AActivity.onStop"); } }
BActivity:
public class BActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_b); } @Override protected void onStart() { super.onStart(); System.out.println("BActivity.onStart"); } @Override protected void onResume() { super.onResume(); System.out.println("BActivity.onResume"); } }
Log:
03-31 17:08:56.144 4861-4861/com.art.exploration I/System.out: AActivity.onPause 03-31 17:08:56.187 4861-4861/com.art.exploration I/System.out: BActivity.onStart 03-31 17:08:56.189 4861-4861/com.art.exploration I/System.out: BActivity.onResume 03-31 17:08:56.569 4861-4861/com.art.exploration I/System.out: AActivity.onStop
通过上述测试可以发现,在android 5.0系统上,旧的AActivity的onPause先调用,然后新的BActivity才会启动。
在Android Activity源码中对onPause的解释里有这样一句话:
When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A‘s {@link #onPause} returns, so be sure to not do anything lengthy here.
意思是当活动B在活动A前面启动时,该回调将在A上被调用。在A的onPause返回之前,B不会被创建,所以请确保在这里不做任何事情,及不能做耗时操作,会影响B的启动。
通过分析这个问题,我们知道onPause和onStop都不能做耗时操作,尤其是onPause,也就是说尽量在onStop中操作,从而不影响新的Activity尽快显示出来并切换到前台。
注:这篇博客是笔者根据《Android开发艺术探索》一书案例做的实测,希望能帮助到大家。