33

I need to minimize the application when back button is pressed.

I use following code to catch hardware back button click event


help me with the code of minimize on back key pressed

@Override
public boolean onKeyDown(int keyCode, keyEvent event) {
    switch(keyCode) {
    case KeyEvent.KEYCODE_BACK;
    //minimize application
    return true;
    }
    return super.onKeyDown(keyCode, event);
}

3 Answers3

52

I think that you need to treat back event as home event. The code below is how I emulate home pressed when User press back button:

 public void minimizeApp() {
    Intent startMain = new Intent(Intent.ACTION_MAIN);
    startMain.addCategory(Intent.CATEGORY_HOME);
    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(startMain);
}
Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86
  • i am new here.. help me how to? –  Jan 27 '15 at 04:18
  • In each answer, there's a tick (check) image below up/down vote. You can tick it (from gray -> green) to accept this answer to avoid anyone re-answer this question. – Kingfisher Phuoc Jan 27 '15 at 04:21
  • @KingfisherPhuoc ,if there is another app opened behind my app, on calling `minimizeApp()` it minimises all apps opened in background .How to overcome this ? – karanatwal.github.io Feb 06 '17 at 12:44
49

This is a simple code to minimize the application

@Override
public void onBackPressed() {
        this.moveTaskToBack(true);
}
DarckBlezzer
  • 4,578
  • 1
  • 41
  • 51
  • 1
    You saved me ! After a week looking for "releasing the foreground" I finally found your wonderfull answer. Which exactly respond to my question, even if it is not the same as this one. – Jérémy Jan 16 '19 at 19:54
8

try this code, this will minimize Activity.

public boolean onKeyDown(int keyCode, KeyEvent event)  
{
     if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
     {
        this.moveTaskToBack(true);
        return true;
     }
    return super.onKeyDown(keyCode, event);
}

or

If you want to close the activity use this.finish() method to close the current running activity. instead of this.moveTaskToBack(true);

RajaReddy PolamReddy
  • 22,428
  • 19
  • 115
  • 166