Repeatedly background task ionic framework - android

I'm using ionic-framework / cordova for building my app.
I've installed this plugin cordova-plugin-background-mode for working in background mode.
Q: But now how can I do a task that repeats every 30 minutes in background?
Do you know another plugin that does this?
Thanks

According to the repository that you used the code must look like this:
// Run when the device is ready
document.addEventListener('deviceready', function () {
// Android customization
// To indicate that the app is executing tasks in background and being paused would disrupt the user.
// The plug-in has to create a notification while in background - like a download progress bar.
cordova.plugins.backgroundMode.setDefaults({
title: 'TheTitleOfYourProcess',
text: 'Executing background tasks.'
});
// Enable background mode
cordova.plugins.backgroundMode.enable();
// Called when background mode has been activated
cordova.plugins.backgroundMode.onactivate = function () {
// Set an interval of 30 minutes (1800000 milliseconds)
setInterval(function () {
// The code that you want to run repeatedly
}, 1800000);
}
}, false);

You can use $timeout and $interval for this task with centain period of time
Angular doc for interval

Related

Running a background worker in React Native Expo for intensive tasks

I would like to create a background-worker/-service that is running in the background that executes jobs that are queued. For example if a user is downloading a image, receiving a message or uplading files.
The idea would be like having a loop that waits for a semaphore to release:
class BackgroundWorker {
async process() {
while (true) {
const job = await this.jobQueue.waitAsync(); // waits for a job being enqueued
// process job...
}
}
}
I saw in the expo documentation that it is possible to use the TaskManager or the BackgroundFetch but these classes are not guaranteed to be executed in the interval that you can specify (https://docs.expo.dev/versions/latest/sdk/task-manager/ and https://docs.expo.dev/versions/latest/sdk/background-fetch/). I was using the BackgroundFetch and set the minimumInterval to 10 seconds. It was executing the function every minute. I need a solution where I can react directly to events.
Another question is, if it's possible to run these kind of workers in the background while the application is closed/terminated or running in the background.

Persistent background worker in Android Flutter App that fetch Web API every 30 seconds

I'm developing Android only app on Flutter. My app needs to call some Web APIs in the background every 30 seconds. The background worker should keep running even if the user or Android OS closes my app's main activity.
I know that doing something in the background too frequently will drain the battery very quickly and it is considered bad practice. But still, I need to do it every 30 seconds.
The target platform of my app is Android 7.0 or higher.
Any ideas how can I implement this in Flutter?
Try to add Timer I have already use Timer (below code) in my app my problem is solved
Timer: A count-down timer that can be configured to fire once or
repeatedly.
Declare Timer inside your class
Timer timer;
int counter = 0;
Create initState() method for timer
#override
void initState() {
super.initState();
timer = Timer.periodic(
Duration(seconds: 30),
(Timer t) => addValue(),
);
}
Create function for addValue it is increased
void addValue() {
setState(() {
counter++;
});
}
your page auto reload every 30 seconds
OR you just use setState method inside your API call function like below
setState(() { });

How to awake the app when user shake the mobile phone in flutter

I am using CallKeep to awake the app (for shake detection I am using Shake plugin) when shaking the mobile, I want to up the flutter app when user shake the phone and app is killed.
I know I can use background_fetch: ^1.0.0, but problem is that it only allows after every 15 minutes, I want to listen shake event all the time.
Please help me out I am stuck here.
Thanks in advance
Check the code snippet and API documentation carefully. There is a property inside of configure called minimumFetchInterval. You can adjust the value and check if it works, should work.
api-doc Following code snippet is placed under Android part in api doc.
BackgroundFetch.configure(BackgroundFetchConfig(
minimumFetchInterval: 15, // <-- minutes
stopOnTerminate: false,
startOnBoot: true
), (String taskId) async { // <-- Event callback
// This callback is typically fired every 15 minutes while in the background.
print('[BackgroundFetch] Event received.');
// IMPORTANT: You must signal completion of your fetch task or the OS could
// punish your app for spending much time in the background.
BackgroundFetch.finish(taskId);
}, (String taskId) async { // <-- Task timeout callback
// This task has exceeded its allowed running-time. You must stop what you're doing and immediately .finish(taskId)
BackgroundFetch.finish(taskId);
})

how can i create run app even user close it android

want create app cordova and ionic for android to alaram in some times like 2:50 and i want program run even close the program
i use katzer/cordova-plugin-background-mode plugin , but when i close program , it be close and dont still run in background this is code
// Run when the device is ready
document.addEventListener('deviceready', function () {
// Android customization
// To indicate that the app is executing tasks in background and being paused would disrupt the user.
// The plug-in has to create a notification while in background - like a download progress bar.
cordova.plugins.backgroundMode.setDefaults({
title: 'TheTitleOfYourProcess',
text: 'Executing background tasks.'
});
// Enable background mode
cordova.plugins.backgroundMode.enable();
// Called when background mode has been activated
cordova.plugins.backgroundMode.onactivate = function () {
// Set an interval of 3 seconds (3000 milliseconds)
setInterval(function () {
var dd = new date();
var h = dd.getHours();
var m = dd.getMinutes();
if(h == 2 && m ==50){
alert("2:50");
}
}, 3000);
}
}, false);
how can i make app still run even user close the program like , alarm clock or some program reminder ?
Have you tried:
http://developer.android.com/guide/components/services.html
this might be helpful

What happens to JavaScript execution (settimeout, etc.) when iPhone/Android goes to sleep?

I have a jQuery Mobile web app which targets iOS and Android devices. A component of the application is a background task, which periodically checks for a.) changes to local data and b.) connectivity to the server. If both are true, the task pushes the changes.
I'm using a simple setTimeout()-based function to execute this task. Each failure or success condition calls setTimeout() on the background task, ensuring that it runs on 30 second intervals. I update a status div with the timestamp of the last task runtime for debugging purposes.
In any desktop browser, this works just fine; however, on iOS or Android, after some period of time, the task stops executing. I'm wondering if this is related to the power conservation settings of the devices--when iOS enters stand-by, does it terminate JavaScript execution? That is what appears to happen.
If so, what is the best way to resume? Is there an on-wake event which I can hook into? If not, what other options are there which don't involve hooking into events dependent on user interaction (I don't want to bind the entire page to a click event just to restart the background task).
Looks like Javascript execution is paused on MobileSafari when the browser page isn't focused. It also seems if setInterval() events are late, they are simply fired as soon as the browser is focused. This means we should be able to keep a setInterval() running, and assume the browser lost/regained focus if the setInterval function took much longer than usual.
This code alerts after switching back from a browser tab, after switching back from another app, and after resuming from sleep. If you set your threshold a bit longer than your setTimeout(), you can assume your timeout wouldn't finish if this fires.
If you wanted to stay on the safe side: you could save your timeout ID (returned by setTimeout) and set this to a shorter threshold than your timeout, then run clearTimeout() and setTimeout() again if this fires.
<script type="text/javascript">
var lastCheck = 0;
function sleepCheck() {
var now = new Date().getTime();
var diff = now - lastCheck;
if (diff > 3000) {
alert('took ' + diff + 'ms');
}
lastCheck = now;
}
window.onload = function() {
lastCheck = new Date().getTime();
setInterval(sleepCheck, 1000);
}
</script>
Edit: It appears this can sometimes trigger more than once in a row on resume, so you'd need to handle that somehow. (After letting my android browser sleep all night, it woke up to two alert()s. I bet Javascript got resumed at some arbitrary time before fully sleeping.)
I tested on Android 2.2 and the latest iOS - they both alert as soon as you resume from sleep.
When the user switches to another app or the screen sleeps, timers seem to pause until the user switches back to the app (or when the screen awakens).
Phonegap has a resume event you can listen to instead of polling for state (as well as a pause event if you want to do things before it is out of focus). You start listening to it after deviceReady fires.
document.addEventListener("deviceready", function () {
// do something when the app awakens
document.addEventListener('resume', function () {
// re-create a timer.
// ...
}, false);
}, false);
I use angular with phonegap and I have a service implemented that manages a certain timeout for me but basically you could create an object that sets the timer, cancels the timer and most importantly, updates the timer (update is what is called during the 'resume' event).
In angular I have a scopes and root scope that I can attach data to, my timeout is global so I attach it to root scope but for the purpose of this example, I'll simply attach it to the document object. I don't condone that because you need should apply it to some sort of scope or namespace.
var timeoutManager = function () {
return {
setTimer: function (expiresMsecs) {
document.timerData = {
timerId: setTimeout(function () {
timeoutCallback();
},
expiresMsecs),
totalDurationMsecs: expiresMsecs,
expirationDate: new Date(Date.now() += expiresMsecs)
};
},
updateTimer: function () {
if (document.timerData) {
//
// Calculate the msecs remaining so it can be used to set a new timer.
//
var timerMsecs = document.timerData.expirationDate - new Date();
//
// Kill the previous timer because a new one needs to be set or the callback
// needs to be fired.
//
this.cancelTimer();
if (timerMsecs > 0) {
this.setTimer(timerMsecs);
} else {
timeoutCallback();
}
}
},
cancelTimer: function () {
if (document.timerData && document.timerData.timerId) {
clearTimeout(document.timerData.timerId);
document.timerData = null;
}
}
};
};
You could have the manager function take a millisecond parameter instead of passing it into set, but again this is modeled somewhat after the angular service I wrote. The operations should be clear and concise enough to do something with them and add them to your own app.
var timeoutCallback = function () { console.log('timer fired!'); };
var manager = timeoutManager();
manager.setTimer(20000);
You will want to update the timer once you get the resume event in your event listener, like so:
// do something when the app awakens
document.addEventListener('resume', function () {
var manager = timeoutManager();
manager.updateTimer();
}, false);
The timeout manager also has cancelTimer() which can be used to kill the timer at any time.
You can use this class github.com/mustafah/background-timer based on #jlafay answer , where you can use as follow:
coffeescript
timer = new BackgroundTimer 10 * 1000, ->
# This callback will be called after 10 seconds
console.log 'finished'
timer.enableTicking 1000, (remaining) ->
# This callback will get called every second (1000 millisecond) till the timer ends
console.log remaining
timer.start()
javascript
timer = new BackgroundTimer(10 * 1000, function() {
// This callback will be called after 10 seconds
console.log("finished");
});
timer.enableTicking(1000, function(remaining) {
// This callback will get called every second (1000 millisecond) till the timer ends
console.log(remaining);
});
timer.start();
Hope it helps, Thank you ...
You should use the Page Visibility API (MDN) which is supported just about everywhere. It can detect if a page or tab has become visible again and you can then resume your timeouts or carry out some actions.

Categories

Resources