分析
- onPause():Activity失去焦点,但仍然可见。
- onStop():Activity在后台,不可见(完全被另一个Activity挡住,或者程序后台运行)。
几种情况
- 锁屏的时候,会依次调用onPause()和onStop()。
- Toast、Dialog、Menu,三者都不会使Activity调用onPause()。
- 一个非全屏的Activity在前面时,后面的Activity只调用onPause()。
Dialog
不会调用onPause()和onStop()
非全屏Activity
会调用onPause(),不会调用onStop()
全屏Activity
会调用onPause()和onStop()
代码
MainActivity
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView textView;
private Button button1;
private Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast toast = Toast.makeText(getApplicationContext(),
"默认的Toast", Toast.LENGTH_SHORT);
toast.show();
}
});
button1.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new Builder(MainActivity.this);
builder.setMessage("测试onPause");
builder.setPositiveButton("确认", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
return true;
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,
SecondActivity.class));
}
});
}
@Override
protected void onPause() {
System.out.println("onPause---");
super.onPause();
}
@Override
protected void onStop() {
System.out.println("onStop---");
super.onStop();
}
// 创建菜单选项
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
}
SecondActivity
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_xml);
}
}