Question

Phonegap: 2.9.0

Android: 4.4.2

I want use the "Back Button": if current page is not Home Page, Back, else Exit the APP, but it dose not works, why?

Here is my code: MainActivity.java

import android.os.Bundle;
import android.view.KeyEvent;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import org.apache.cordova.*;

public class MainActivity extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setIntegerProperty("splashscreen", R.drawable.splash);
        super.loadUrl("http://www.mydomain.com", 0);
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if((keyCode == KeyEvent.KEYCODE_BACK) && appView.canGoBack())
        {
            appView.goBack();
            return false;
        }

        if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            dialog();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    protected void dialog() {
        AlertDialog.Builder builder = new Builder(MainActivity.this);
        builder.setMessage("Exit The APP?");
        builder.setTitle("Are You Sure");
        builder.setPositiveButton("OK",
            new android.content.DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            });
        builder.setNegativeButton("Cancel",
            new android.content.DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which){
                    dialog.dismiss();
                }
            });
        builder.create().show();
    }
}

Thanks for help and best wishes!

Was it helpful?

Solution

Even better, handle the event inside your cordova app, by wiring up an event listener...

document.addEventListener('backbutton', this.onBackKeyDown, false);

then, write your own logic...

onBackKeyDown: function() {
   ... insert your logic here...
}

This answer was inspired by this post. Please acknowledge which one works best for you.

OTHER TIPS

I used to use onBackPressed to prevent using the back button, but it doesn't seem to work the same in 4.4.2, using cordova 3.3. Maybe just move your existing code into this event...

@Override
public void onBackPressed() {
   ... insert your relevant onkeydown logic here.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top