简体   繁体   中英

Override back button with moveTaskToBack in Android 4.4.2 KitKat

I'm using Cordova 3.3 to create an Android app. I want to override the back button(why is not important) and I'm using this approach:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

I also tried this approach:

@Override
public void onBackPressed()
{
    moveTaskToBack(true);
}

However, none of this works in Android 4.4.2 (KitKat), onDestroy() is still called for some reason..

I also tried setting a boolean "taskInBack" variable, but since onDestroy() is called, the variable doesn't help..

I tried this on different versions of Android, and it seems to work fine in all except KitKat.

Does anyone know why this doesn't work? Could it be Cordova related, or is it Android related?

Since you are using Cordova, why not use the backbutton event from Cordova instead of writing native code?

I use a function (like the following) to control the use of the back button in my apps. The most common use is that the back button does nothing unless the user is on a view that has a view to go back to.

Try this:

document.addEventListener("backbutton", onBackKeyDown, false);

function onBackKeyDown() {
    // Handle the back button
}

Full reference: http://docs.phonegap.com/en/3.3.0/cordova_events_events.md.html#backbutton

Currently Cordova does not expose the Android native method moveTaskToBack() ..

If you need that feature, you can try this Cordova plugin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM