10

I was wondering if I can override the action of the back and home button is some cases. Normally these buttons should just react like they always do, but in a case some setting is true I want to override the buttons and let them call my own methods.

I´m using these two methods to override these buttons:

  @Override
  public void onBackPressed() {    
  // call my backbutton pressed method when boolean==true
    }

  @Override
  public void onAttachedToWindow()    {                                                                                       this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);    
   super.onAttachedToWindow(); 
   // call my homebutton pressed method when boolean==true
   }
Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115
Diego
  • 4,011
  • 10
  • 50
  • 76

6 Answers6

37

I was wondering if I can override the action of the back and home button is some cases.

Yes you can do override Home button.

I have developed an application which disable hard button, you can have a look. I have taken a toggle button which locks all hard button to work except Power button

public class DisableHardButton extends Activity {
    /** Called when the activity is first created. */
    TextView mTextView;
    ToggleButton mToggleButton;
    boolean isLock=false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mTextView=(TextView) findViewById(R.id.tvInfo);
        mToggleButton=(ToggleButton) findViewById(R.id.btnLock);


        mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub
            isLock=isChecked;
            onAttachedToWindow();
        }
    });
   }
@Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        if ( (event.getKeyCode() == KeyEvent.KEYCODE_HOME) && isLock) {
            mTextView.setText("KEYCODE_HOME");
            return true;
        }
        else
            return super.dispatchKeyEvent(event);
    }
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub

        if( (keyCode==KeyEvent.KEYCODE_BACK) && isLock)
        {
            mTextView.setText("KEYCODE_BACK");
            return true;
        }
           else
             return super.onKeyDown(keyCode, event);
    }
@Override
    public void onAttachedToWindow()
    {  
        System.out.println("Onactivity attached :"+isLock);
        if(isLock)
        {   
            this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);     
            super.onAttachedToWindow();
        }
        else
        {
            this.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION);     
            super.onAttachedToWindow();
        }
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvInfo"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <ToggleButton
        android:id="@+id/btnLock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOff="UnLocked"
        android:textOn="Locked" />

</LinearLayout>
Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115
  • 1
    Wow, this is great, exactly what I´m looking for! – Diego Apr 05 '12 at 10:47
  • 1
    Didn't knew this, thought you couldn't change it, +1 :) – Bigflow Apr 05 '12 at 12:05
  • If I first let an optionmenu popup and press the home button it still goes to the homescreen, any idea how to catch that call? – Diego Apr 05 '12 at 18:10
  • pleasure :), @LarsDiego dint get you? – Mohammed Azharuddin Shaikh Apr 06 '12 at 05:43
  • 6
    IIRC this way of overriding the home button thankfully no longer works as of Android 4.0 – Kristopher Micinski Apr 26 '12 at 12:57
  • 40
    Yes, fortunately, this approach does not work on Android 4.0.3. – CommonsWare May 10 '12 at 22:40
  • @CommonsWare is there is any way to make this happen in ICS and Jelly bean ?most of the SO posts say no, and onAttachedWindow with the setType throws an exception – Rat-a-tat-a-tat Ratatouille Oct 28 '13 at 06:16
  • @DharaShah: "is there is any way to make this happen in ICS and Jelly bean ?" -- have your app be a HOME screen. – CommonsWare Oct 28 '13 at 10:30
  • @CommonsWare sir i have, but it still doesnt work, i tried using onAttachedWindow bt then returns an illegalstateException, and i even tried onWindowFocus but that throws an exception in the log, with the message that custom window properties have been maintained. I knw its not valid to have the home button behave the way users may find it overwhelming but thats a requirement :( – Rat-a-tat-a-tat Ratatouille Oct 28 '13 at 10:33
  • 1
    @CommonsWare i added android:launchMode="singleInstance" android:stateNotNeeded="true" to the activity that should be displayed and thus when clicking on home, i get a selection box to select from. This is the only way to make it work ya sir ? – Rat-a-tat-a-tat Ratatouille Oct 29 '13 at 08:49
  • @CommonsWare i just realized that making the activity a home screen activity, displays the app name in the set of launchers but when clicking on a textview to exit, the same app opens when actually the original launcher should open :(. – Rat-a-tat-a-tat Ratatouille Oct 29 '13 at 13:00
  • but i just want to know only-is user pressed home button or not? but in your solution when user press home button activity not go to invisible state it in remain same state. while after pressing home button application no longer visible. and this code also not working on 4.1.x and 4.2.x – neeraj kirola Aug 08 '14 at 09:17
  • For the versions greater than 4.0 this will help to disable HARD Home button. https://github.com/shaobin0604/Android-HomeKey-Locker – X-HuMan Nov 29 '14 at 22:26
  • 1
    " Window type can not be changed after the window is added." I got this error. How does that code work for everyone expect me? – ffttyy Sep 09 '15 at 22:05
4

You call super.onBackPressed() to call the normal method. Exemple :

@Override
public void onBackPressed() {    
    if (activated) {
       //doyourthing
    } else {
       super.onBackPressed()
    }
}
NitroG42
  • 5,336
  • 2
  • 28
  • 32
3

No you can not. What you can do is to ovveride the method and manage the boolean inside it:

for instance:

 public void onBackPressed() {    // call my backbutton pressed method when boolean==true

      if (myCondition) {
          // take care of my needs
       } else 
            // call super to let the back behavior be "normal"

  }
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
2

Regarding overriding the behaviour of Home Button you are out of luck.

However if your app is a specific one and have limited targeted audience, like inter-organization app, hospital kiosk, restaurant ordering, you can try making your app as Home (the launcher app). You can find a good example here: How to Write Custom Launcher App in Android

And to override the back key events, lot of examples are there.

For example:

  1. Catch keypress with android
  2. Override back button to act like home button
  3. Android - How To Override the "Back" button so it doesn't Finish() my Activity?
Community
  • 1
  • 1
Adil Soomro
  • 37,609
  • 9
  • 103
  • 153
1

make your boolean variable member variable

boolean temp;

@Override
        public void onBackPressed() {    // call my backbutton pressed method when boolean==true

if(temp)
//your methode
else
finish();
            }
vipin
  • 2,851
  • 4
  • 18
  • 32
1

I use this:

public void onBackPressed() {

        switch (screen) {
        case 1:
            screen = 99;
            setContentView(R.layout.menu);
            break;

        case 99:
            finish();
            break;

        }
        return;
    }

When I am in a other screen (other then menu screen), I set the variable screen to 1. When I press the back button, it goes back to the menu screen (instead of killing the app). and give the screen variable the number 99, then when you hit the back button again, it kills the app.

However, you can't change the home button.

vipin
  • 2,851
  • 4
  • 18
  • 32
Bigflow
  • 3,616
  • 5
  • 29
  • 52