Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Hosted-services / Cordova

Chocolatechip-UI, Cordova and Android - Handling Physical Back Button Events

5.00/5 (1 vote)
22 Aug 2015CPOL2 min read 12.2K  
How to handle Android physical back button events with Chocolatechip-UI and Cordova.

Introduction

This tip describes how to handle the app navigation events when the physical back button is pressed on the Android device, when using Chocolatechip-UI framework along with Cordova for building hybrid apps.

Background

You must know the basics of building a Cordova app for Android, and also some basic knowledge of Chocolatechip-UI framework and its markup.

Chocolatechip-UI
http://chocolatechip-ui.com/

Apache Cordova - Getting Started with Android
http://cordova.apache.org/docs/en/2.5.0/guide_getting-started_android_index.md.html

Using the Code

Once you have created your Cordova project and added the required Chocolatechip-UI and JQuery references to your index.html file, you must determine which <article> tag you want to have the exit app behavior, so that when the user is on it and presses the back button, we can exit the app.

Once you choose it, add the class 'exit-enable' on it. Below is an example of an index.html file with simple parent and child articles and a simple navigation:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, 
    	maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="msapplication-tap-highlight" content="no">
    <title>My App</title>
    <link rel="stylesheet" 
    	href="./frameworks/chui_3.8/chui-android-3.8.10.min.css">    
    <script src="./frameworks/jquery-2.1.1.min.js"></script>
    <script src="./frameworks/chui_3.8/chui-3.8.10.min.js"></script>
</head>
<body >
    <nav class='current'>
        <h1>Parent Article</h1>
    </nav>
    <!-- We want this article to be main one. 
    When user presses the device back button and this article is visible, it will close the app.
      For this, we add the 'exit-enable' class on it.
    -->
    <article id='home' class='current exit-enable'>
        <section>
            <ul class='list'>
                <li data-goto='child-article' class='nav'>
                    <h3>Child Article 1</h3>
                </li>
            </ul>
        </section>
    </article>
    <nav class='next'>
        <button class='back'></button>
        <h1>Child Article 1</h1>
    </nav>
    <article id='child-article' class='next'>
        <section>
            <ul class='list'>
                <li data-goto='child-article-2' class='nav'>
                    <h3>Child Article 2</h3>
                </li>
            </ul>
            <p>You are in the child article 1</p>
        </section>
    </article>
    <nav class='next'>
        <button class='back'></button>
        <h1>Child Article 2</h1>
    </nav>
    <article id='child-article-2' class='next'>
        <section>
            <ul class='list'>
                <li>
                    <h3>You are in a very deep article now.</h3>
                </li>
            </ul>
            <p>Try to go back using the device's back button.</p>
        </section>
    </article>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
</body>
</html>

You can read more about Chocolatechip-UI's navigation syntax and markup here.

In the JavaScript initialization code, we add an event listener for backbutton event.

Note: It is important to listen to the deviceready event before setting the callback function for backbutton event. You can implement this as you wish, depending on your project structure. Below is an example of how to listen to the deviceready event:

index.js file:

JavaScript
document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
    //Physical Back Button events
    document.addEventListener('backbutton', onBackKeyDown);
}

Below is the onBackKeyDown function:

JavaScript
function onBackKeyDown(event){

    //prevent the default back button event
    event.preventDefault();

    //if there is any popup opened, then close it using the native ChUI method call
    if ($('.popup.opened').length) {
        console.log('manually closing popup.');
        $('.popup.opened').UIPopupClose();
    }

    //Check if current article allows user to exit.
    //If you want your app to close when the user presses the back button from a specific article,
    //you just need to set a class 'exit-enable' on it. Example:
    //
    //<article id='home' class='current exit-enable'>
    //    <section>....</section>
    //</article>
    //

    //if article contains exit-enable class, then call cordova exitApp method
    else if ($('article.current').hasClass('exit-enable')) {
        console.log('exiting app...');
        navigator.app.exitApp();             
    }
    //When you navigate to an article, Chocolatechip-ui will always set the .previous class to the
    //previous article.
    //Thus, it is easy to determine if there is a backwards navigable article.
    //If there is one, just navigate back to it.
    else if($('article.previous').length) {
        
        console.log('navigating back to article.');
        //call ChUI native navigation method, passing the article id
        $.UIGoBack();
    }


}

Note: If your app layout looks weird when running it in your device, consider including the Crosswalk plugin in your project: https://crosswalk-project.org/documentation/cordova/cordova_4.html.

However, it's out of scope of this tip.

Points of Interest

Chocolatechip-UI is a great framework for creating hybrid apps with native look and feel, and Apache Cordova provides all the device capabilities we need in order to create a complete functional mobile app.
As Chocolatechip-UI already contains a very good, built-in navigation engine that differs a lot from default Cordova navigation events, the solution above makes it easy to integrate the back button functionalities in a decoupled, efficient way in your app.

History

  • 26th August, 2015: Added 'close popup' functionality on back button event.
  • 24th August, 2015: Updated ChUI navigation method call

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)