我想从onCreate方法内部完成一个活动.当我打电话时finish(),onDestroy()没有立即调用,代码不断流过finish().onDestroy()直到onCreate()结束括号后才调用.
根据onCreate()developer.android.com/reference上的说明.
您可以在此函数中调用finish(),在这种情况下,将立即调用onDestroy(),而不执行任何其余的活动生命周期(onStart(),onResume(),onPause()等).
我问的原因是:我想检查传递给Bundle的数据onCreate().当然我可以控制传递的内容onCreate,但我仍然认为应该在交付时进行检查.
我的代码包含class A,它启动Activity B.我认为不应该调用最后两个"if of clause子句"标签,因为语句中的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
Run Code Online (Sandbox Code Playgroud)
我的代码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
Run Code Online (Sandbox Code Playgroud)
以下是我的代码的结果:
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:INFO/tag(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:INFO/tag(699):B类:onDestroy
tri*_*ggs 116
我猜这是因为finish()不会导致onCreate方法返回.您可以尝试简单地添加
finish();
return;
Run Code Online (Sandbox Code Playgroud)
或者使用if else
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutb);
if(good data){
//do stuff
}else{
finish();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 23
finish()在onCreate()将控制返回到系统之前似乎不起作用.请参考这篇文章:关于android中的finish().如果您不希望在调用完成后执行任何代码,则必须考虑此问题.
希望能帮助到你.