- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK) {
- moveTaskToBack(false);
- return true;
- }
- return super.onKeyDown(keyCode, event);
- }
里面的moveTaskToBack()是关键。
moveTaskToBack()方法:在activity中调用
参数说明:
参数为false——代表只有当前activity是task根,指应用启动的第一个activity时,才有效;
参数为true——则忽略这个限制,任何activity都可以有效。
说明:判断Activity是否是task根,Activity本身给出了相关方法:isTaskRoot()
moveTaskToBack调用后,task中activity的顺序不会发生变化,例如A启动B,B中调用此方法退到后台,重新启动应用会调用B中的onRestart-onStart-onResume方法,不会重新调用onCreate,而且在B中按下back键返回的还是A,这就是退到后台的功能。
另外在activity中按下back键,实际是调用了finish方法,应用退出。虽然应用已经退出,但进程没有被杀死,android中一个应用运行于独立的一个虚拟机实例中,所以在重新启动应用时一个类中的静态对象还保持着运行时的状态,注意在合适位置复位这些状态。
关于moveTaskToBack
public boolean moveTaskToBack (boolean nonRoot)
Since: API Level 1Move the task containing this activity to the back of the activity stack. The activity's order within the task is unchanged.
Parameters
nonRoot If false then this only works if the activity is the root of a task; if true it will work for any activity in a task.
Returns
If the task was moved (or it was already at the back) true is returned, else false.
贴上测试代码:
- <span style="font-size:14px;">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;
- public class MainActivity extends Activity {
- private Button tv;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- tv = (Button) findViewById(R.id.test);
- tv.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- /**
- * 会调用:onPause()和onStop()
- */
- moveTaskToBack(true);
- Log.e("====", "点击运行了moveTaskToBack()方法");
- }
- });
- }
- @Override
- protected void onPause() {
- Log.e("====", "onPause()");
- super.onPause();
- }
- @Override
- protected void onStop() {
- Log.e("====", "onStop()");
- super.onStop();
- }
- @Override
- protected void onDestroy() {
- Log.e("====", "onDestroy()");
- super.onDestroy();
- }
- @Override
- protected void onResume() {
- Log.e("====", "onResume()");
- super.onResume();
- }
- @Override
- protected void onStart() {
- Log.e("====", "onStart()");
- super.onStart();
- }
- @Override
- protected void onRestart() {
- Log.e("====", "onRestart()");
- super.onRestart();
- }
- }
- </span>
运行一下:
01-13 00:19:45.179: E/====(3801): 点击运行了moveTaskToBack()方法
01-13 00:19:45.199: E/====(3801): onPause()
01-13 00:19:45.662: E/====(3801): onStop()