0

Actually, in my app, I want to call a function when the user clicks the home button. Can anyone suggest to me how that can be done?

iknow
  • 8,358
  • 12
  • 41
  • 68
AndroidDev
  • 4,521
  • 24
  • 78
  • 126
  • 2
    Not at all related to the question, but this was the 100,000th android tagged question. – brc Sep 23 '11 at 05:15

3 Answers3

0

Android does not allow to override the home button, its restriction that android does not allow to let you override the home button

mayank_droid
  • 1,015
  • 10
  • 19
0

The only way to handle the home button action is by creating a home replacement activity. This is an activity with action 'main' and category 'home'. This is for security issues, to prevent applications from locking users.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • Is that simple, create an activity and modify the manifest so that the intent filter is for action main and category home. – K-ballo Sep 23 '11 at 05:19
  • can you please show me with an example if possible.Actually i dont have any idea for that – AndroidDev Sep 23 '11 at 05:23
  • Actually on click of home button i want to call a function which run on background so after writing this thing in manifest file how my work is done – AndroidDev Sep 23 '11 at 05:41
  • Be aware that if you modify your manifest to support action.MAIN category.HOME, your activity will be called from **every** application, not just yours. – Laurent' Sep 23 '11 at 06:22
-1

If you just want to to run some code when the home button is pressed, the you can place that code in onPause() since this method will always be called before the home screen is launched. Insert this code inside your activity.

@Override
protected void onPause() {

    // your code here, 
    // Note: should not be anything that takes too long time to execute 

    super.onPause();
}
HenrikS
  • 4,170
  • 3
  • 34
  • 33
  • Thats what my problem..actually the code that i have to write in onPause take time to execute as a result of which it when i click back button it wait in that activity for a sec of time and after that it exit from the activity..yeh you are right it solve the problem of clicking of home button but only when my code execution takes less time – AndroidDev Sep 23 '11 at 05:56
  • Maybe you should try to launch a new background Thread or an [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html) in onPause method. If you need feedback from your background operation, maybe onResume is a better place than onPause. – Laurent' Sep 23 '11 at 06:20
  • can i use onDetachedFromWindow() method – AndroidDev Sep 23 '11 at 06:36
  • `onPause()` can also run for a million other reasons. For example, if the user splits their screen and focuses on the screen not containing your activity, or simply pulls down the navigation drawer, or navigates to another Activity or... etc. – kenny_k Jun 22 '20 at 11:51