我是Android新手。我正在编写一个应用程序来使用Log语句跟踪Activity生命周期。我想杀死我的应用程序,以便查看正在调用的onDestroy()事件。我添加了一个调用完成的按钮来执行此操作,但我无法终止该应用。我也尝试过System.exit(0),但我的应用程序终止了。我做错了什么?
public class MainActivity extends Activity {
private static final String LOG_DISPLAY = "DEBUG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(LOG_DISPLAY, "onCreate called");
}
@Override
protected void onPause() {
super.onPause();
Log.d(LOG_DISPLAY, "onPause called");
}
@Override
protected void onResume() {
super.onResume();
Log.d(LOG_DISPLAY, "onResume called");
}
@Override
protected void onStop() {
super.onStop();
Log.d(LOG_DISPLAY, "onStop called");
}
@Override
protected void onStart() {
super.onStop();
Log.d(LOG_DISPLAY, "onStart called");
}
@Override
protected void onRestart() {
super.onStop();
Log.d(LOG_DISPLAY, "onRestart called");
}
public void addListenerOnButton() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
finish();
//System.exit(0);
}
});
}
}
答案 0 :(得分:3)
您必须覆盖onDestroy
才能检查是否已调用它,并调用addListenerOnButton
方法:
试试这个:
public class MainActivity extends Activity {
private static final String LOG_DISPLAY = "DEBUG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(LOG_DISPLAY, "onCreate called");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(LOG_DISPLAY, "onDestroy called");
}
@Override
protected void onPause() {
super.onPause();
Log.d(LOG_DISPLAY, "onPause called");
}
@Override
protected void onResume() {
super.onResume();
Log.d(LOG_DISPLAY, "onResume called");
}
@Override
protected void onStop() {
super.onStop();
Log.d(LOG_DISPLAY, "onStop called");
}
@Override
protected void onStart() {
super.onStop();
Log.d(LOG_DISPLAY, "onStart called");
}
@Override
protected void onRestart() {
super.onStop();
Log.d(LOG_DISPLAY, "onRestart called");
}
public void addListenerOnButton() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
MainActivity.this.finish();
//System.exit(0);
}
});
}
}
答案 1 :(得分:2)
首先添加缺少的onDestroy
实现以显示日志:
@Override
protected void onDestroy() {
Log.d(LOG_DISPLAY, "onDestroy called");
super.onDestroy();
}
然后只需打开活动并使用硬件back
按钮退出。您将看到onDestroy
日志。
您也可以通过编程方式调用finish()
同样效果,不要忘记在addListenerOnButton
onCreate
电话