18

I want to create my own 'home' screen on my android, and I want to call that home screen from my application.

How can I override the 'Home' button so that when it's pressed the application will be redirected to my home screen instead of the default home screen? Is it possible to override the home button?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Smith
  • 413
  • 3
  • 9
  • 24
  • check out [this post](https://stackoverflow.com/questions/4841686/how-to-make-a-launcher) which addresses making a Home Launcher which will be able to catch the Home button. – Richard Le Mesurier Aug 16 '18 at 12:26

8 Answers8

12

In AndroidManifest.xml

<activity
    ...
    android:launchMode="singleTask">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.HOME" />
        <category android:name="android.intent.category.DEFAULT" />
        ....
    </intent-filter>
</activity>

You need launchMode="singleTask" so the intent is delivered to the already running app instead of creating a new instance.

In the activity:

   @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (Intent.ACTION_MAIN.equals(intent.getAction())) {
            Log.i("MyLauncher", "onNewIntent: HOME Key");

        }
    }

You do not get a key event

bara
  • 2,964
  • 2
  • 26
  • 24
12

Override the method below.

@Override
public void onAttachedToWindow()
{  
    Log.i("TESTE", "onAttachedToWindow");
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
    super.onAttachedToWindow();  
}

With this method, the HOME Button stops working in this activity (only this activity). Then you just reimplement as it was a normal button event (the back button for instance).

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_HOME) {
        Log.i("TESTE", "BOTAO HOME");
        return true;
    }
    return super.onKeyDown(keyCode, event);    
}
lucasneo
  • 183
  • 2
  • 5
  • OK, with the onAttachedToWindow() override this actually works, but it could be pretty dangerous if all buttons are disabled, locking the user in, with the only way to exit the app being removing the battery... – ateiob Aug 09 '12 at 03:03
  • 8
    @ateiob: Fortunately, this security hole has been fixed, as of Android 4.0. – CommonsWare Aug 09 '12 at 10:39
  • 1
    @CommonsWare Thanks for this info. Is this really a **security** hole? Or just a "user frustration hole"? – ateiob Aug 10 '12 at 21:34
  • 2
    @ateiob: If malware prevents you from removing the malware, it is a security hole. – CommonsWare Aug 10 '12 at 21:44
  • 1
    @CommonsWare Can you provide a link to the changelog listing "HOME button override" bug fix please ? – David Andreoletti Jan 15 '14 at 03:11
  • 1
    @lucasneo there is no option called TYPE_KEYGUARD how to do this – YLS Mar 11 '17 at 07:56
6

The home button is supposed to do one thing and one thing only and consistently. Get the user back to the the HOME screen. Even if you could override it's behavior it would be an extremely user-unfriendly thing to do. So don't do it and solve your problem differently!

markus
  • 40,136
  • 23
  • 97
  • 142
  • actually i want to lock that screen when my own home-screen get occured.thats why i want to control HOME button on my own HOME-SCREEN – Smith Apr 05 '11 at 06:15
  • 1
    It just doesn't make sense IMO. – markus Apr 05 '11 at 06:20
  • 1
    I don't know what Smith wants to do with this, but overriding the home button is pretty much the standard for a launcher, e.g. to show the list of apps, so I don't see any harm in doing it on its own home screen – Aleadam Apr 05 '11 at 07:06
  • @Aleadam: Yeah, I guess there are use cases where it's ok. In general I don't like my home button to do anything unexpected. I think it also depends on the version of Android. With my HTC Desire HD and Android 2.2 I wouldn't like ANYthing to override my home button. List of apps shows when I click the up-arrow just above the home button. – markus Apr 05 '11 at 07:30
  • also, there are non-Market applications being programmed for Android that need this functionality, to restrict the usage of the device (e.g., company buys 100 phones for doing field surveys). – hoffmanc Jan 10 '12 at 16:46
  • @hoffmanc Restricting the usage of the device can be done in much more clever ways than disabling the home button... – ateiob Aug 09 '12 at 02:49
  • i am creating a screen lock app . it has to disable the home button. how do you suggest do handle this situation ? @markus – Sagar Nayak May 22 '16 at 06:13
  • For consumers, but if you are developing for commercial hardware theres a real case to disable. – beaumondo Feb 28 '17 at 08:43
  • This should be accepted answer. So many people wanting to do strange things in apps. Read and get some culture about the subject! or tell your managers to do so. If you want to limit device usage, implement a Launcher – voghDev May 28 '18 at 12:13
  • @voghDev This should not be the accepted answer because it simply doesn't answer the OP's very valid question. Don't think it's valid? I'm developing an Android TV app in which when it starts it plays a small intro video fetched from a server. One of the requirements is that the user should only be able to press the back button and no other button to skip the intro video early and go into the main activity of the app. Why the "back" button you may ask? Because on the remote of this specific TV the back button actually says "exit" on it so that's how the hotel manager wants it. – PrashanD Oct 20 '18 at 19:10
  • @PrashanD so your Android code depends on the text that is printed on a button of TV remote of a specific brand and model? this is what I mean when I say `strange things`. Anyway if there requirements are like this, you can workaround it with solutions like the given one – voghDev Oct 23 '18 at 11:04
  • @voghDev Yep, The hotel's management who has zero cares about SE, Android best practices or what is strange or not wants the app to be brand, remote and model specific. App's going nowhere in play store. Some of the board don't even know the TVs are android. They want us to "configure" the TVs the way they think is the experience for their guests and if we can't get it done they'll simply move on to a different project proposal because that's how we sold it. In that way, it's a good thing that Android is so customizable and this is far from the strangest thing we've had to do for this project. – PrashanD Oct 26 '18 at 02:51
  • @PrashanD Good point, you just said it. People sometimes has zero cares, and they should have some, as they finish asking for things like "I want an Android App exactly the same as this iOS App, all screens must be equal pixel-by-pixel". It is our task to give them this information so they update their old-fashioned mindset – voghDev Oct 26 '18 at 08:35
2

This answer will no longer work, not since Android 4.0.

The correct solution is to create an app that can intercept the Home intent, as per @bara's answer below.


You can override the home button as any other button:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_HOME)) {
        Toast.makeText(this, "You pressed the home button!", Toast.LENGTH_LONG).show();                     
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
Richard Le Mesurier
  • 29,432
  • 22
  • 140
  • 255
Aleadam
  • 40,203
  • 9
  • 86
  • 108
  • thanks alot as we discuss a lot on this topic..this Q. is asked at same time of that HOME-Screen Launcher Q..and you gave me solutions...thanks again... – Smith Apr 05 '11 at 06:56
  • 51
    This does not work on any version of Android, AFAIK, and certainly not in anything recent. – CommonsWare Jun 19 '12 at 16:02
  • @CommonsWare I initially thought you were right as I tested this by returning **true** immediately upon entering `Activity.onKeyDown()`: All buttons were indeed disabled, **except for the home button!** But then I tried the `onAttachedToWindow()` trick by @ucasneo below and **the home button is disabled too!** Fortunately, **long-pressing the back button** saved me from having to reboot my phone... – ateiob Aug 09 '12 at 03:06
  • @CommonsWare Then again, `onAttachedToWindow()` is only called once per activity launch, so if you disabled the `home` button (must be when the activity just started), you cannot re-enable it in the lifetime of that activity. So even though this approach is working, it has significant limitations. – ateiob Aug 09 '12 at 03:40
  • 1
    not working in lollipop . please edit the answer to latest solution @Aleadam – Sagar Nayak May 22 '16 at 06:09
0

Try this in activity

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            break;
        default:
            return super.onOptionsItemSelected(item);
    }
    return false;
}
Diana S.
  • 51
  • 1
  • 3
0

No we cant override home button but i fund a solution for this....:

public boolean isApplicationSentToBackground(final Context context)  {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
    ComponentName topActivity = tasks.get(0).topActivity;
    if (!topActivity.getPackageName().equals(context.getPackageName())) {
        return true;
    }
}
return false;
}


@Override
public void onStop() {

if (isApplicationSentToBackground(this)){
    //put your code here what u want to do

}
super.onStop();
}

make change to manifests file-

<uses-permission android:name="android.permission.GET_TASKS" />
RkKhanpuriya
  • 164
  • 1
  • 13
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Please read this [how-to-answer](http://stackoverflow.com/help/how-to-answer) for providing quality answer. – thewaywewere Jun 21 '17 at 13:29
0

If someone need to detect and ovveride HOME button behavior use thois appproach in KOTLIN

import android.content.Intent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.IntentFilter
import android.util.Log



class HomeWatcher(context: Context)  {

    val TAG = "hg"
    private var mContext: Context? = null
    private var mFilter: IntentFilter? = null
    private var mListener: OnHomePressedListener? = null
    private var mRecevier: InnerRecevier? = null

    // initializer block
    init {
        mContext = context
        mFilter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
    }

    fun setOnHomePressedListener(listener: OnHomePressedListener) {
        mListener = listener
        mRecevier = InnerRecevier()
    }

    fun startWatch() {
        if (mRecevier != null) {
            this.mContext!!.registerReceiver(mRecevier, mFilter)
        }
    }

    fun stopWatch() {
        if (mRecevier != null) {
            this.mContext!!.unregisterReceiver(mRecevier)
        }
    }

    internal inner class InnerRecevier : BroadcastReceiver() {
        val SYSTEM_DIALOG_REASON_KEY = "reason"
        val SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions"
        val SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps"
        val SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"

        override  fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                val reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY)
                if (reason != null) {
                    Log.e(TAG, "action:$action,reason:$reason")
                    if (mListener != null) {
                        if (reason == SYSTEM_DIALOG_REASON_HOME_KEY) {
                            mListener!!.onHomePressed()
                        } else if (reason == SYSTEM_DIALOG_REASON_RECENT_APPS) {
                            mListener!!.onHomeLongPressed()
                        }
                    }
                }
            }
        }
    }
}

MainActivity

class MainActivity : SimpleActivity(), RefreshRecyclerViewListener {

    private var launchers = ArrayList<AppLauncher>()
    private var mStoredPrimaryColor = 0
    private var mStoredTextColor = 0
    private var mStoredUseEnglish = false
    private var receiver: BroadcastReceiver? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        HomeButtonWatcher()
    }

    fun HomeButtonWatcher()
    {
        val mHomeWatcher = HomeWatcher(applicationContext)
        mHomeWatcher.setOnHomePressedListener(object : OnHomePressedListener {
            override fun onHomePressed() {
                // do something here...
                Toast.makeText(applicationContext, "onHomePressed", Toast.LENGTH_LONG).show()
            }

            override fun onHomeLongPressed() {
                // do something here...
                Toast.makeText(applicationContext, "onHomeLongPressed", Toast.LENGTH_LONG).show()
            }
        })
        mHomeWatcher.startWatch()

    }

   // Other code
}
NoWar
  • 36,338
  • 80
  • 323
  • 498
0

Scenario for why you want to control the HOME button. I wanted to create a custom lock screen for when the user puts the android device on charge. So they have to scan a certain code to login in again. Having the app disable these buttons (so the user can't navigate away from the app) allows the app to remain the dominant screen the user sees.

Roy Fagon
  • 61
  • 2
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33580368) – f.khantsis Jan 10 '23 at 00:54