bhaRATh
bhaRATh

Reputation: 797

How To Exit app by double tap on back button in NativeScript Apps

Exit app on double tap on back button in Nativescript

Please help me with snippet of code

Upvotes: 0

Views: 2539

Answers (2)

aditya_adi_98
aditya_adi_98

Reputation: 24

for Angular

import * as application from 'tns-core-modules/application';

exitapp=0
ngOnInit() {
application.android.on(application.AndroidApplication.activityBackPressedEvent, this.handleBackButton, this);
}

handleBackButton(args: any) {
        this.ngZone.run(() => {
            args.cancel = true;
            if (this.routerExtensions.canGoBack()) {
                this.routerExtensions.back();
            }else{
                
                this.exitapp++
                this.getData.toast('Press again to exit')
                if(this.exitapp==2){
                    application.android.foregroundActivity.finish();
                }
                setTimeout(()=>{
                    this.exitapp=0
                },2000)
            }
        })
    }

Upvotes: 0

Dean Le
Dean Le

Reputation: 2094

Here is the solution that I have found:

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();
}

Hope this helps.

Upvotes: 3

Related Questions