0

How to add a listener to home button? i.e I want to add some functionality when home button is pressed. How do I do it? I did the following, but it is not working for home button. It's working only for back button.

public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
                   // some functionality

    }

    if (keyCode == KeyEvent.KEYCODE_HOME)
    {

        // some functionality

    }

    // // TODO Auto-generated method stub
    return super.onKeyDown(keyCode, event);

}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
tejasvi
  • 195
  • 1
  • 8

5 Answers5

1

You must override onAttachedToWindow() first.

@Override
    public void onAttachedToWindow() {
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); 
        super.onAttachedToWindow();
    }

In addition, you need to add the permission:

<uses-permission android:name="android.permission.DISABLE_KEYGUARD "></uses-permission>
biegleux
  • 13,179
  • 11
  • 45
  • 52
chiefhsing
  • 11
  • 2
1

don't do that. its not correct to do that because the only use of home button is to exit from the application at any point. you can use isFinishing() if u want to execute any code while leaving an activity. have a look into this.

Community
  • 1
  • 1
Seshu Vinay
  • 13,560
  • 9
  • 60
  • 109
0

You can't do that. The Android policy forbids that a App can overwrite or listen to the Homebutton.
Maybe you can accomplish what you want with overwriting onDetachFromWindow.

Thommy
  • 5,070
  • 2
  • 28
  • 51
0

You can't but you could use onPause(). The application will be paused when the home button is clicked.

Warpzit
  • 27,966
  • 19
  • 103
  • 155
0

How to add a listener to home button?

You don't. The HOME button always brings up the user's chosen home screen. You can elect to make your app be a home screen, by supporting CATEGORY_HOME in an activity, but then it had better really work as a home screen.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491