Close the application on back button of android phones

I'm developing a app using angularjs and ionic framework. It has a logout option also. When i logout from my app it goes straight to the home page.But if i press the back button it'll go to page that can be accessed only if you are logged in. How can i create a option to close the app if you press the back button from the home page? I use angularjs.

I used this way but did not work

document.addEventListener("backbutton", function(e){
    if($.mobile.activePage.is('/templates/playlists')){
        /* 
         Event preventDefault/stopPropagation not required as adding backbutton
          listener itself override the default behaviour. Refer below PhoneGap link.
        */
        //e.preventDefault();
        navigator.app.exitApp();
    }
    else {
        navigator.app.backHistory()
    }
}, false);

Your code is good.

But, I'm not sure about the second line : are you sure that the active page id is /templates/playlists ?

Normally, the value you should pass to the $.mobile.activePage.is function should contain a page id (which could be retrieved like this : $.mobile.activePage.attr('id')).

(by the way, I don't know which of jQuery Mobile you are using, but the $.mobile.activePage.is was deprecated).