我想从onCreate
方法内部完成一项活动。当我调用时finish()
,onDestroy()
没有立即调用,代码不断流过finish()
。onDestroy()
直到onCreate()
大括号结束才被调用。
根据onCreate()
developer.android.com/reference上的描述。
您可以从此函数内调用finish(),在这种情况下,将立即调用onDestroy(),而不会执行其余的活动生命周期(onStart(),onResume(),onPause()等)。
我问的原因是:我想检查传递给的捆绑包中的数据onCreate()
。当然,我可以控制传递给的内容onCreate
,但我仍然认为应该在交付时进行检查。
我的代码包含A
启动Activity的类B
。我相信不应调用最后两个“ if子句之外”标签,因为语句中的finish
方法if
应该已经破坏了活动。它与if子句无关,因为第二个finish()
调用之后的标记行仍然被读取。
我的代码:
A级
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// goToBButton: when pressed sends message to class B.
Button goToBButton = (Button)this.findViewById(R.id.go_to__b_btn);
goToBButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick (View v) {
Log.i(TAG,"A Class: goToBButton, onClick");
Intent i = new Intent(A.this, B.class);
startActivityForResult(i,REQ_TO_B);
}
});
} // end onCreate
我的代码ClassB
public class B extends Activity{
private static final String TAG = "tag";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutb);
// set as true, should always print Tag: one line before first finish"
if (true) {
Log.i(TAG,"B Class: one line before 1st finish");
finish();
}
// shouldn't get here after first finish
Log.i(TAG,"B Class: outside of if clause, before second finish");
finish();
// shouldn't get here after second finish
Log.i(TAG,"B Class: outside of if clause, after finish");
} // end onCreate
@Override
public void onStart () {
super.onStart();
Log.i(TAG,"B Class: onStart");
}
@Override
public void onRestart() {
super.onRestart();
Log.i(TAG,"B Class: onRestart");
}
@Override
public void onResume () {
super.onResume();
Log.i(TAG,"B Class: onResume");
}
@Override
public void onPause () {
super.onPause();
Log.i(TAG,"B Class: onPause");
}
@Override
public void onStop () {
super.onStop();
Log.i(TAG,"B Class: onStop");
}
@Override
public void onDestroy () {
super.onDestroy();
Log.i(TAG,"B Class: onDestroy");
}
} // end B Class
这是我的标签的结果:
11-26 15:53:40.456:INFO / tag(699):A类:goToBButton,onClick
11-26 15:53:40.636:INFO / tag(699):A类:onPause
11-26 15:53:40.865:信息/标签(699):B类:第一完成前一行
11-26 15:53:40.896:INFO / tag(699):B类:if子句之外,第二次完成之前
11-26 15:53:40.917:INFO / tag(699):B类:if子句之外,完成后
11-26 15:53:41.035:INFO / tag(699):A类:onResume
11-26 15:53:41.165:信息/标签(699):B类:onDestroy