Home button listener

后端 未结 4 748
面向向阳花
面向向阳花 2020-11-30 13:24

Using the setOnKeyListener I can able to listen for all physical buttons except Home and End button, is there any possibility to catch the action of Home button.

4条回答
  •  盖世英雄少女心
    2020-11-30 13:53

    You want to use public boolean dispatchKeyEvent(KeyEvent event), as covered here: http://developer.android.com/reference/android/app/Activity.html#dispatchKeyEvent%28android.view.KeyEvent%29.

    Use it like so:

        @Override
            public boolean dispatchKeyEvent(KeyEvent event)
            {
        // do whatever you want to do here, then return true if you handled the key code
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_BACK:
                    mBackDown = true;
                    return true;
                case KeyEvent.KEYCODE_HOME:
                    mHomeDown = true;
                    return true;
                }
    }
        return super.dispatchKeyEvent(event);  // let the default handling take care of it
        }
    

    Let me know if that works for you.

    EDIT: not sure why this doesn't work for you, but without looking through the rest of your code it would be hard to tell what exactly is going on. However, for your task, what I would recommend is that you use the finishOnTaskLaunch manifest attribute, as described at http://developer.android.com/guide/topics/manifest/activity-element.html#finish: properly used (set it to true) this will make sure that if your Activity is relaunched it will shutdown any existing instance.

提交回复
热议问题