各种答案和注释都声称finish()可以跳过onPause()和onStop()并直接执行onDestroy()。公平地讲,关于此的Android文档(http://developer.android.com/reference/android/app/Activity.html)指出“活动正在完成或被系统破坏”,这虽然模棱两可,但可能暗示finish()可以跳转到onDestroy()。
同样,finish()上的JavaDoc也令人失望(http://developer.android.com/reference/android/app/Activity.html#finish()),并且实际上并未注意到为完成而调用了哪些方法()。
所以我写了这个迷你应用程序,下面记录了每个条目的状态。它包含一个调用finish()的按钮-因此您可以查看触发了哪些方法的日志。该实验表明,finish()实际上确实也调用了onPause()和onStop()。这是我得到的输出:
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onCreate
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onStart
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onResume
2170-2170/? D/LIFECYCLE_DEMO﹕ User just clicked button to initiate finish()
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onPause
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onStop
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onDestroy
package com.mvvg.apps.lifecycle;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AndroidLifecycle extends Activity {
private static final String TAG = "LIFECYCLE_DEMO";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "INSIDE: onCreate");
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) findViewById(R.id.myId);
Button button = new Button(this);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(AndroidLifecycle.this, "Initiating finish()",
Toast.LENGTH_SHORT).show();
Log.d(TAG, "User just clicked button to initiate finish()");
finish();
}
});
layout.addView(button);
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "INSIDE: onStart");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "INSIDE: onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "INSIDE: onDestroy");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "INSIDE: onPause");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "INSIDE: onResume");
}
}