Search code examples
androidandroid-homebutton

Prevent home button from going to home screen when it's on lock-screen


I'm trying to make a lockscreen for android. Whenever I press the home button, it brings me back to the home screen. I tried various apps from google play. The Go Locker app does not let you to go to home screen unless you unlock the screen. I don't want my application to return to home screen unless I swipe the screen to unlock it. Is there anyway to do this functionality? It's been 3 days and I couldn't find anything about it.

Thanks a lot.


Solution

  • Here is some code:

    @Override
    public void 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 re implement as it was a normal button event.

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean res = super.onKeyDown(keyCode, event);
        switch (keyCode) {
        case KeyEvent.KEYCODE_HOME: {
            // Your Home button logic;
            return false;
        }
        return res;
    }
    

    Warning: 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 application being removing the battery, so code properly, handle all the cases.

    OR

    Came across this method of overriding the home button click, hope it works for you:

    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 application 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())) {
            //your code goes here.
        }
    }
    

    You do not get a key event.