Skip to content Skip to sidebar Skip to footer

How Do Make Hardware Back Button Become Exit App

I found this code but its for javascript: document.addEventListener('deviceready', onDeviceReady, false); function onDeviceReady(){ document.addEventListener('backbutton', fun

Solution 1:

Angular is JavaScript. This code requires no modification to work with angular, you just need to add it to your app.

Solution 2:

This is a sample code for illustration that uses Angular ui-router framework which is a standard now:

Read the code comments for better understanding. Please modify the below to your needs. You have to call the exit code only when the cordova library is loaded. So call the angular initialization code inside deviceready event callback.

Sample HTML code:

<!DOCTYPE html><html><head><scriptsrc="angular.min.js"type="text/javascript"charset="utf-8"></script><scriptsrc="angular-ui-router.js"type="text/javascript"charset="utf-8"></script></head><bodyng-app="myApp"><divui-view></div><scriptsrc="app.js"type="text/javascript"charset="utf-8"></script></body></html>

Sample JS code: Call after the cordova is loaded inside deviceready

angular.module('myApp', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider' , function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/page1")
    $stateProvider
    .state('page1', {             
          url: "/page1",
          template: '<div><div>{{topmsg}}</div><a  ui-sref="page2">Middle</a></div>',
          controller: function ($scope) {
            $scope.topmsg = "loaded top!";
            console.log("Page 1");
          }
    })

    .state('page2', {             
          url: "/page2",
          template: '<div>{{topmsg}}</div>',
          controller: function ($scope) {
            $scope.topmsg = "Pages 2";
            console.log("Page 2");
          }
    });        
}])

.run(function($rootScope, $state){
    $rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams, options){
        console.log("state - "+ toState.name);
            //debugger;if(toState.name == "page2"){
            //Add Your closing code here//navigator.app.exitApp();
        }       
    }); 
});

Explaination:

I have created two pages. Just for illustration while navigating to the second page i am closing the app by calling navigator.app.exitApp().

Refer this documentation for parameters that are available on stage change event.

Note: iOS Appstore rejects your app if you quit the app from code.

Post a Comment for "How Do Make Hardware Back Button Become Exit App"