Managing the Android back button

How to enable double pressing on the Android physical button to dismiss and kill the app

  •         
    var frameModule = require("ui/frame");
    var application = require("application")
    
    var activity = application.android.startActivity ||
            application.android.foregroundActivity ||
            frameModule.topmost().android.currentActivity ||
            frameModule.topmost().android.activity;
    var lastPress;
    
    activity.onBackPressed = function() {
        var timeDelay = 500
        if (lastPress + timeDelay > java.lang.System.currentTimeMillis()) {
            var startMain = new android.content.Intent(android.content.Intent.ACTION_MAIN);
            startMain.addCategory(android.content.Intent.CATEGORY_HOME);
            startMain.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(startMain);
    
            // If you want to kill the app totally, use these codes instead of above
            // activity.finish();
            // java.lang.System.exit(0);
    
        } else {
            frameModule.topmost().goBack();
        }
        lastPress = java.lang.System.currentTimeMillis();
    }