Prevent my application from being idle (Cordova/Android)

I have recently developed an Android app using a node.js webpack project.

After installing the app on my phone, I observed that it enters a sleep mode along with the phone. Consequently, a JavaScript timer I set up stops functioning as intended:

pingTimer=setInterval(ping,pingInterval);

I am looking for a way to prevent my app from going to sleep, at least for the time being. Eventually, I will consider allowing the app to enter a sleep state, but for now, I need it to stay awake while the phone sleeps.

UPDATE

I attempted to follow the steps outlined in this guide:

Unfortunately, I did not achieve the desired result.

Answer №1

If you're looking for the ideal solution, consider utilizing the WakeLock API.

Include the necessary permission in the manifest file to enable the wakeLock.

<uses-permission android:name="android.permission.WAKE_LOCK" />

Subsequently, based on your modifications as suggested in MDN, you can implement the following:

function forPingTimer(){
 var lock =  window.navigator.requestWakeLock('screen');
 //set a timeout or wait until the timer expires
}

To release the lock, use the lock.unlock(); function.

Alternatively

For a Cordova application, you may also utilize the plugin Insomnia. The necessary changes in the config file are outlined in the documentation and can be easily implemented as follows:

function forPingTimer(){
//keep the app awake indefinitely or specify a timeout, or encapsulate it in a promise
//Simply call window.plugins.insomnia.keepAwake() to prevent sleep
}
//To allow the device to sleep again after the timer expires, use window.plugins.insomnia.allowSleepAgain()

Answer №2

If you want to keep your cordova android app active and prevent it from sleeping, one of the simplest solutions is to utilize the Insomnia-PhoneGap-Plugin. This versatile plugin is compatible with various platforms such as Android, iOS, and Windows.

Using the plugin is straightforward. The keepAwake function within the plugin ensures that the device remains awake, while the allowSleepAgain function allows the device to go back to sleep when needed. For more detailed information, you can visit the official insomnia plugin link.

We hope this information proves valuable for you. Best of luck!

Answer №3

To clarify the syntax, first install the cordova-plugin-insomnia plugin. Then, incorporate a basic interval timer into your code:

// initiate an interval timer
var mainloopid = setInterval(mainloop, 1000);
function mainloop {
    // invoke the plugin every (let's say) one second to prevent your app from sleeping
    window.plugins.insomnia.keepAwake();
}

Make sure to call the plugin's keepAwake method regularly (at least before your device attempts to sleep.) This is crucial for any display clocks, and the interval timer can be part of the timer responsible for updating seconds in a clock. This method essentially overrides the device setting that dictates, for instance, "sleep after 15 seconds". It's like setting an Android Device to "sleep never" mode while your app is active.

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

I'm curious as to why a webpage tends to load more quickly when CSS files are loaded before script files. Can anyone shed some

While watching a video, I came across some concepts that were a bit difficult for me to grasp. The video mentions that scripts are 'serialized' and can block subsequent files from loading. According to this explanation, Script 1 would load first ...

How to disable the onChange event in PrimeNG p-dropdown?

I'm currently utilizing PrimeNG's dropdown component. Each option in the list includes an icon that, when clicked, should trigger a specific method. Additionally, I need to execute another method when the onChange event of the dropdown is trigger ...

What could be causing webpack to struggle in locating the loader?

Check out my package.json: { "name": "redux-todo", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "webpack-dev-server" }, "devDependencies": { "babel": "^6.5.2", "babel-loader": "^6.2.5", "bab ...

The getElementByID function will return null in this instance, as it has not been loaded

Hello everyone, I am facing an issue while trying to access an element by its ID in JavaScript as it keeps returning null. This problem arises because the element is not fully loaded when the DOM is initially created, due to a plugin called Restrict Conte ...

What is the method for obtaining the div ID's from this form?

This is the scenario I am working on: my app takes the text inputted by the user and exports it to a specific website that contains similar elements. For example, if the user enters a title in the app and clicks a button, the app will transfer that value t ...

Combining jQuery form validation with a PHP script on a single webpage

After implementing jQuery form validation and redirecting using the function btn_onclick() { window.location.href = "http://localhost/loginprivate.php";} from index.php to loginprivate.php, my web app's PHP script is not being executed. The user is re ...

Is the Ajax response value consistently 1?

I am facing an issue where a JavaScript in an HTML page is sending two variables to a PHP script, which then echoes one of the variables at the end. However, the response value always remains 1. Despite trying methods like alerting, console.log, and puttin ...

What is the best way to determine if a checkbox has been selected in ExtJS?

I have a panel with a checkbox inside it. I am trying to figure out how to check if the checkbox is selected or not using an external function. Can someone please assist me with this? this.currentManagerPanel = new Ext.Panel({ border: false, wid ...

Issues with merging styles in TinyMCE 4

I've exhausted all the current configuration options and I'm still unable to resolve this issue. My goal is to have the style tag appended to the selected element without generating an additional span. For example: <p>Hello World!</p> ...

What is the best way to smoothly scroll to another page using a specific id?

My website consists of multiple pages and I am looking for a code that will allow for smooth scrolling navigation to another page when loading on a specific id or section. For example, in the navbar I have multiple pages with links. When clicking on a lin ...

The combination of MUI CardContent and flexBox seems to have issues when used in conjunction with typography and chips

Take a look at this React code using MUI. It's designed to create a Card that showcases Character Information. const CharacterPreview = ({ characterKey }: CharacterPreviewProps) => { return ( <Card sx={{ maxWidth: 256, borderRadius: 4 }}&g ...

Angular's ng-include functionality allows developers to dynamically load

As a beginner in angular.js, I've written my first 'hello world' script. I'm attempting to use ng-include to bring in a navbar from the local file /templates/nav.html. Despite following a tutorial closely, I'm struggling to underst ...

Converting CSV into an Array of Hash Tables

Currently, I am working on parsing a CSV file and creating an array of hashes. While I initially implemented this using my own code, I feel that it may not be the most efficient solution. My aim is to utilize the CSV-Parser library, but so far, I have only ...

Flot causes the x-axis display to show incorrect time after a certain period of time

Recently, I encountered an issue with jquery flot while working on a real-time chart. Everything seemed to be functioning properly at first, but after some time had passed, I noticed a significant problem. Initially, the chart was updating correctly; howe ...

Choose from the select2 multiselect options and lock certain selected choices from being altered

I have coded a select dropdown with preselected options, some of which I want to keep fixed so that users cannot change them. To achieve this, I implemented the following code: <select id="select2-multiple" name="users" multiple="multiple" style="width ...

Combining various API requests within a Vue component, which includes a for loop

I'm delving into the world of API chaining, specifically trying to link two different API calls within a 'notes' Vue component. My knowledge of promises is basic at best, but I'm eager to enhance my skills in this area. The initial API ...

Odd behaviour when using JSON in CouchDB

I have developed an updates handler in CouchDB with test code like this (before inserting into Couch I am removing newlines): function (doc, req) { if (req['userCtx']['roles'].indexOf('editor') < 0) { return [ ...

Executing a PHP script to initiate a ping transmission

I have a project to complete for my university involving the development of a simple application. However, I lack experience in this area and am unsure how to proceed. The objective is straightforward: I want to send ping requests to 50 IP addresses at t ...

Any tips on loading all KML files from a folder with geoXML3?

In my JavaScript code, I am using geoXML3 to successfully load, parse, and display the KML file below. var geoXml = new geoXML3.parser({map: map, singleInfoWindow: true}); geoXml.parse('/myapp/resources/kml/fileone.kml'); However, the / ...

Creating a Vue.js v-for loop to dynamically display a series of DIVs in segments

Here is the code I am currently working with: <div class="container-fluid" id="networdapp" style="display:none;"> <div class="row" > <div v-for="(result,i) in results" :key="i" class="col-sm-6" > <div class=" ...