在activity中,拦截onkeydown方法,对back键进行处理,然后调用 activity的moveTaskToBack (boolean nonRoot)方法即可将整个应用最小化,效果和按home键一样,注意不是finish()退出。
参数为false代表只有当前activity是task根,指应用启动的第一个activity时,才有效;
如果为true则忽略这个限制,任何activity都可以有效。
moveTaskToBack调用后,task中activity的顺序不会发生变化,例如A启动B,B中调用此方法退到后台,重新启动应用会调用B中的onRestart-onStart-onResume方法,不会重新调用onCreate,而且在B中按下back键返回的还是A,这就是退到后台的功能。
另外在activity中按下back键,实际是调用了finish方法,应用退出。虽然应用已经退出,但进程没有被杀死,android中一个应用运行于独立的一个虚拟机实例中,所以在重新启动应用时一个类中的静态对象还保持着运行时的状态,注意在合适位置复位这些状态。
官方文档:
public boolean moveTaskToBack (boolean nonRoot)
Move 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.