Search code examples
javaandroidkiosk-modedevice-admin

Android: Stop Back Button From Exiting LockTask / Kiosk Mode


I want to implement a KioskMode, I'm targeting only Android L, since this is a very specific App.

I already went through the process of setting my App as DeviceAdmin, and DevicePolicyManager.isLockTaskPermitted(this.getPackageName()) already returns true.

I then start a LockTask via startLockTask().

Everything is fine, but when I hold down the backbutton, the app still exits the kiosk mode.

I have overridden onKeyPress to show a custom Dialog for unlocking the app, but this does not hinder android to automatically exit my lock task if the user holds down back.

I don't really know what to do at the moment and would be thankful for every input.

I now have overridden

@Override
public boolean onKeyDown(int KeyCode, KeyEvent event)
{
    if(KeyCode == KeyEvent.KEYCODE_BACK)
    {
        BackDownButtonPressed = true;
        if(VolDownPressed)
            showTaskLockDialog();
        return true;
    }
    else if(KeyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
    {
        VolDownPressed = true;
        if(BackDownButtonPressed)
            showTaskLockDialog();
        return true;
    }
    return  super.onKeyDown(KeyCode, event);
}

@Override
public boolean onKeyUp(int KeyCode, KeyEvent event) {
    if(KeyCode == KeyEvent.KEYCODE_BACK)
    {
        BackDownButtonPressed = false;
        return true;
    }
    else if(KeyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
    {
        VolDownPressed = false;
        return true;
    }
    return super.onKeyUp(KeyCode, event);
}

@Override
public void onBackPressed()
{
    return;
}

@Override
public boolean onNavigateUp() {
    return true;
}

@Override
public boolean dispatchKeyEvent (KeyEvent event)
{
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
        return true;
    }
    return true;
}

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        //do something or nothing in your case
        return true;
    }
    return super.onKeyLongPress(keyCode, event);
}

For the record, I am using a Samsung SM-T700 Tablet with Cyanogenmod CM12.1


Solution

  • Just to close this topic..

    I couldn't figure out a perfect solution to this day. My current workaround is receiving an event if the user leaves the kiosk mode and just entering the kiosk mode again.

    Sadly this leaves the user with 2 toasts saying "screen unpinned" and "screen pinned", which is unfortunate. But this satisfies my current needs.