开发者

Home button listener

Using the setOnKeyListen开发者_开发技巧er 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.


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;


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜