android返回键不销毁应用返回主界面

来源:互联网 发布:java后端框架 编辑:程序博客网 时间:2024/06/05 06:41

类似【微信】以及【支付宝】等应用的功能,在某一Activity界面点击返回键,隐藏应用并显示主界面,此时的返回键功能类似于home键。

具体实现如下:

@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {     if (keyCode == KeyEvent.KEYCODE_BACK) {         moveTaskToBack(false);         return true;     }     return super.onKeyDown(keyCode, event);}

其中,moveTaskToBack是Activity里的方法:

    /**     * Move the task containing this activity to the back of the activity     * stack.  The activity's order within the task is unchanged.     *     * @param 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.     *     * @return If the task was moved (or it was already at the     *         back) true is returned, else false.     */    public boolean moveTaskToBack(boolean nonRoot) {        try {            return ActivityManagerNative.getDefault().moveActivityTaskToBack(                    mToken, nonRoot);        } catch (RemoteException e) {            // Empty        }        return false;    }

从函数的注释中可知,对boolean类型的参数说明如下:

**false:只有当前的Activity是task栈的栈底,即其他的Activity都必须被finish掉,此方法才起作用,在执行的过程中程序会判断当前activity是否在栈底,非栈底会报异常;
true:Task栈中任意的Activity都可以使该方法起作用,执行的过程中不会判断当前activity是否在栈底。**

阅读全文
0 0