Home button listener

后端 未结 4 734
面向向阳花
面向向阳花 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.

    0 讨论(0)
  • 2020-11-30 13:59

    You do not need to catch Home button. If user press Home and some other Activity comes to foreground, your app goes to background and onPause() is called in your current Activity. You may override that function to clean search string or anything you need.

    UPDATE:

    More clean solution is to use flag FLAG_ACTIVITY_NO_HISTORY when starting that critical activity. So, when your activity goes to background system will close it properly for you.

    0 讨论(0)
  • 2020-11-30 14:04

    You may try this on Android 4.0+:
    1. Register a BroadcastReceiver for Intent.ACTION_CLOSE_SYSTEM_DIALOGS.
    2. Call Intent.getStringExtra("reason") to get the reason. Reasons are below:
    "homekey" for home key pressed;
    "assist" for home key long pressed;

    0 讨论(0)
  • 2020-11-30 14:06

    This is only possible if you modify the main android source code. Although this is not recommended for app purposes. But more geared towards hidden menus.

    public static final int KEYCODE_HOME
    
    Since: API Level 1
    Key code constant: Home key. This key is handled by the framework and is never delivered to applications.
    Constant Value: 3 (0x00000003)
    
    0 讨论(0)
提交回复
热议问题