The mobile device's back button registers a double activation

I'm encountering an issue with my function that utilizes the back button on Android Phones. Instead of going back one page as intended, it's going back two pages.

Here is a snippet of my current code:

function onBackKeyDown()
{
    currentPage = $.mobile.activePage.attr('id');
    if(currentPage == "createUser")
    {
        $.mobile.changePage("#logIn");
        alert("Return To Login Page");
        currentPage = "";
    }
    // More conditions follow...
}

For instance, when I am in the `cardDetails` page and press the back button, it goes back to `createUser` and then continues back to `logIn`. I have tried resetting the `currentPage` variable and adding more conditional statements but the issue persists.

Requested Java Code:

import android.os.Bundle;
import org.apache.cordova.DroidGap;

public class FnBApp extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
        }
    }

Any assistance on this matter would be highly appreciated.

Sincerely, John

Answer №1

To prevent the default behavior of the android back button, you should consider overloading it instead of just detecting and acting on it.

If you want to catch the back key event, make sure to remove your key listener or return true when encountering KEY_BACK.

For handling background services effectively, look into using startForeground() and ensure that you have an ongoing notification. Otherwise, Android may terminate your service to free up memory.

@Override
public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent setIntent = new Intent(Intent.ACTION_MAIN);
   setIntent.addCategory(Intent.CATEGORY_HOME);
   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(setIntent);
}

For app-specific pseudocode implementation:

public class FnBApp extends DroidGap {
    ....
    @Override
    public void onBackPressed() {
       Log.d("CDA", "onBackPressed Called");
       // Check if super.getUrl shows a specific page before loading a new one
       if() {
           super.loadUrl("file://android_asset/www/index.html#login");
       };
    }

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

Answer №2

Are you utilizing Cordova and looking to make your code compatible with devices other than Android? If so, eliminating the need for Java is key. As for the original question, could this code snippet be a solution?:

    function onDeviceReady() {
    // Register the event listener
    document.addEventListener("backbutton", onBackKeyDown, false);
}

(source: this post)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

ASP/VB.NET Client-Side Script Generation/Registration

I am currently updating outdated "Web 1.0" code to align with modern standards. Is there a more efficient way to create and add a client-side script without having to concatenate numerous lines into a StringBuilder and then registering it to the page usin ...

Learn how to extract an entire table from a website using Kimono Labs, rather than just the first ten rows

Currently, I am utilizing Kimono labs to generate an API for scraping data from the table on this specific website. However, the website only displays the initial 10 rows of the table by default, limiting my API output to just 10 rows. Is there a method to ...

Maximizing the potential of .delegate in combination with .closest

$('.inputRadio').parent().click(function (e) { //implement delegate method here }); Looking for assistance on how to integrate the delegate method in the provided function. Any suggestions? ...

What is the best way to fill an array with ng-repeat in AngularJS?

How can I populate an array of objects with data using ng-repeat for a specific id in AngularJS version 1.4? { "tagTypeDetails": [ { "id": 3, "type": "Project Type", "Tags": [ {"id": 21, "name": "Residential"}, {"id ...

What is the best method for changing a prop in a different component?

I have a list of accounts in my page.js file and I need to access this list in another component that is also rendered within the page.js file: var accounts = []; ... <div className="main"> <LeftPanel accounts={accounts}/> </di ...

Sending information to a personalized mat-grid element using properties

I am currently working on enhancing the functionality of the angular material mat-tree component by building a custom component. The main objective is to create a table with expandable and collapsible rows in a hierarchical structure. I have managed to ach ...

Utilizing BehaviourSubject for cross-component communication in Angular

My table is populated with data from a nodeJS API connected to methods inside my service. I attempted using a Behavior Subject in my service, initialized as undefined due to the backend data retrieval: Service: import { Injectable } from "@angular/core" ...

Extract the color of an individual character

There is a code snippet in JavaScript using p5.js that functions as a video filter: const density = ' .:░▒▓█' //const density = ' .tiITesgESG' //let geist; let video let asciiDiv let playing = false let ...

How do I navigate to a different page in a Flask app after an ajax post depending on a condition detected in the view?

Within my flask application, I have a sales page where users can input information that is then saved to the database using an ajax post request. The twist is that there are only a limited number of consoles available for users to record their sales. If on ...

Angular controller within dynamically loaded content using Ajax

I am facing an issue with loading files via Ajax and applying Angular in my project. Here is the link to the Plunker where you can see the problem: http://plnkr.co/MxXzlenAuGcDy8iljKYX The problem I am encountering is that the content of sidebar.html loa ...

Is it possible to utilize $(this) within the $.post() function?

I seem to be having trouble accessing $(this) from inside the $.post section. It works perfectly fine outside of it. Here is the JavaScript code: $('.idea').each(function(){ var title = $(this).html(); $.post("votes.php", { t ...

The Autocomplete field's label remains visible even after the form is submitted

I am currently developing a feature that allows users to select an option in the Autocomplete component. In the parent component, I pass these props: const filterDropdownConfig: FilterSelectAutocomplete = { data: scenariosList, label: { className: &apos ...

RethinkDB is throwing a ReferenceError because the connection variable has not been defined

Utilizing Express.js and Rethink, I am attempting to execute a straightforward post to a route that saves data to the database. The initial connection is successful and logs the message Connected to Rethink, but when I try to use the connection to insert ...

Leveraging a React dropdown to update the value of a distinct variable

Currently, I am working on developing a React page that incorporates a dropdown menu for monthly expenses (food, rent, etc.). The objective is to dynamically update the TransTotal value based on the selection from the dropdown. Below is the snippet of my c ...

Typescript is experiencing an error due to the use of attr("disabled", false) causing a disruption

Within my ts file, I'm using the code snippet below: $('input[type=hidden]').attr("disabled", false); The code functions as intended, however, an error persists: Argument of type 'false' is not assignable to parameter of typ ...

Revolutionizing Gallery Filtering with Bootstrap

I've been attempting to create a filtering gallery for the past three days without any success. None of the codes I came across, or wrote myself, seem to be working. I am using the bootstrap 4 starter template that comes with the latest JQuery version ...

The execution of Node.js callback function is not triggered

After setting up an API that queries a MongoDB and returns JSON Objects, I decided to modularize the code. I moved the MongoDB functionality to a separate file called queryMongo.js, which is now called in the POST request of main.js. Here is the main.js co ...

AnimatedModel - Difficulty with functioning of multiple model boxes

I am attempting to set up multiple model lightboxes for various content using the Animated Model plugin Animated Model. It is functioning with a single link, but when I try to create a duplicate box, it does not work. I believe this is due to the model ta ...

What is the best location to store the JWT bearer token?

Exploring options for storing JWT tokens in a Bearer header token for my application. Looking for the most efficient storage mechanism. Would love some insight on how to accomplish this using jQuery. Any recommendations for a secure method? ...

Retrieve information from jsonObject

Can anyone help me with counting the number of passes and fails for each subject in a JSON object array? Here is an example: [{"Subject":"Maths","status:"Pass"},{"Subject":"Maths","status:"Pass"}, {"Subject":"Maths","status:"Fail"},{"Subject":"Maths ...