Titanium Android - Execute a background task at regular intervals - android

I want to execute a background service in my titanium android app at regular intervals. I can achieve this by using interval service. Following is the code:
function startMovieAlertService()
{
var SECONDS = 1800;
// every 10 seconds
var intent = Titanium.Android.createServiceIntent(
{
url : 'MovieAlertService.js'
});
intent.putExtra('interval', SECONDS * 1000);
Titanium.Android.startService(intent);
}
But this service is closed by android system (or titanium) soon after the app is exited using back button. Now I want that this service executes at regular intervals, without being closed. This service will just check for some new data from web server. And this needs to be executed once per day. Please help me.

Related

Flutter run code after certain duration once app goes to background?

There is a particular feature of this application, called Forest, I would like to emulate.
Basically you start a timer in the application and you are not to switch out from it.
This timer counts down if the application is in the foreground and/or when the screen is off.
There is a given grace period of approximately 10 seconds where a user can switch out of the app (i.e. press home button). If they do not return within the grace period, the timer ends and the user fails. Else the timer continues counting.
Basically the application has to check if it is the background. If it is, start a 10 second timer. Once this timer expire, set a bit such then when the app is back to foreground, the user continues/fails.
I am unsure how do this as reading the Flutter/Dart documentation, the lifecycle states available in Flutter is abstracted away from us. Would I have to run some background code or trigger an interrupt? I looked at the plugins available but they do not allow for triggers below 15 minutes. How is this achieved in native Android/iOS code?
You can use Android alarm manager. Through which you can run some background task when alarm triggered.
import 'package:android_alarm_manager/android_alarm_manager.dart';
void printHello() {
final DateTime now = new DateTime.now();
final int isolateId = Isolate.current.hashCode;
print("[$now] Hello, world! isolate=${isolateId} function='$printHello'");
}
main() async {
final int helloAlarmID = 0;
runApp(...);
await AndroidAlarmManager.periodic(const Duration(minutes: 1), helloAlarmID, printHello);
}
prints 'Hello world' for every minute roughly even if app ends.
PS: example code provided above was taken from plugin example.

Android send commands to obd every sec or less for real time data

For now my app have a chat that comunicate via bluetooth with an OBD port in the car.
Now i want upgrade my project for real time information, so i want create a method that repeat some Array with a list of commands and repeat the sendMessage(message) every sec or 500 millisec (something for real time data).
There is some bestway to do that?
I have my Activity with 4 EditText for showing data and a Button with "start scan" and if pressed it becomes a "stop scan" and interrupt the infinite loop of commands.
In the same time i need to take back data and show results in the EditText.
EDIT
Or just use an AlarmManager?
EDIT 2
With this code not work properly because send only the first message after 5 sec and the second it lost...
How can i send all the commands into ArrayList one at a time every t millisec?
public void repeatCommand(){
for (final String command : commandArray){
final Handler handlerTimed = new Handler();
handlerTimed.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
sendMessage(command);
}
}, 5000);
}
/*String message = "010C\r";
sendMessage(message);*/
}
Sorry I didn't write android code for so long but I had your case so long ago.
You have to define a Service and start it in foreground with RETURN_STICKY and then write a handler with timer which execute your code per second (or what you like!). Then you can broadcast your result or how you want to communicate with your activity and use it.
Then start service and stop it with your button.
PS:
1. As far as I know alarmManager is not a good idea in this case.
Somehow you have to be sure that your Service will not be killed by android.

Change the period of a periodic task in Firebase JobDispatcher?

I was using GCM network manager, but then I heard that Firebase JobDispatcher includes GCM plus other features so I'm trying to use that.
I have successfully programmed a periodic task and it works fine, but the problem is that I need the period to change and not be fixed from the beginning.
The reason for that is, I'm using an activity recognition service and I want the next time the JobDispatcher executes the periodic task to be based on the detected current activity. For example if you're walking, the next time the task is triggered is after 30 minutes, while if you're in a car then the period is 5 minutes (mainly because if you're in a car it's more likely that your phone will provide different location values in a short while compared to when you're on foot).
This is the way I program the periodic task, as you can see I'm setting a fixed value, I want to know if the service that is triggered by this task can provide a feedback that'll change the period of the task.
final Builder builder = jobDispatcher.newJobBuilder()
.setTag(form.tag.get())
.setRecurring(form.recurring.get())
.setLifetime(form.persistent.get() ? Lifetime.FOREVER : Lifetime.UNTIL_NEXT_BOOT)
.setService(DemoJobService.class)
.setTrigger(Trigger.executionWindow(
form.getWinStartSeconds(), form.getWinEndSeconds()))
.setReplaceCurrent(form.replaceCurrent.get())
.setRetryStrategy(jobDispatcher.newRetryStrategy(
form.retryStrategy.get(),
form.getInitialBackoffSeconds(),
form.getMaximumBackoffSeconds()));
if (form.constrainDeviceCharging.get()) {
builder.addConstraint(Constraint.DEVICE_CHARGING);
}
if (form.constrainOnAnyNetwork.get()) {
builder.addConstraint(Constraint.ON_ANY_NETWORK);
}
if (form.constrainOnUnmeteredNetwork.get()) {
builder.addConstraint(Constraint.ON_UNMETERED_NETWORK);
}
To do this you'd need to have your onStartJob in DemoJobService.class cancel itself using your tag that you've saved in SharedPrefs / elsewhere (form.tag.get() in your example):
FirebaseJobDispatcher(GooglePlayDriver(context)).cancel(yourTag)
It can then reschedule the job with the updated parameters. Unfortunately there's currently no way to edit jobs, they must be cancelled and recreated!

Titanium (Android) check for running Services

I'm trying to implement a convenient-to-use system for handling status bar notifications for android, and i was thinking about the following:
Create a database, where i store when and what to show
Create a service what runs in the background using the 'interval' Service, what the API provides
In that service check if any notification needs to be shown according to the database, then show it.
The only problem is, that, i cannot detect, if i need to start the service or not. I tried these things, but none of them worked well so far:
1.) Save if the service was already started on the local storage:
// Do this on application startup
var isRunning = Ti.App.Properties.getBool("service_running", false);
if(!isRunning)
{
var service = Titanium.Android.createService(...);
service.addEventListener('start', function()
{
Ti.App.Properties.setBool("service_running", true);
});
service.addEventListener('stop', function()
{
Ti.App.Properties.setBool("service_running", false);
});
service.start();
}
This obviously won't work, because the android systems native onStop and onDestroy events will not be dispatched, if the Service doesn't terminates unusually (like the user force stops the app), so the stop event also won't be fired.
2.) Try to access any active service via Titanium.Android.getCurrentService(), but i got an error saying Titanium.Android has no method called getCurrentService(). This is pretty strange, because the IDEs code completion offered me this method.
3.) Use an Intent to clear the previously running Service
var intent = Titanium.Android.createServiceIntent
(
{
url : 'notification/NotificationService.js'
}
);
intent.putExtra('interval', 1000 * 60);
//Stop if needed
Titanium.Android.stopService(intent);
//Then start it
Titanium.Android.startService(intent);
But it seems like i need to have the same instance of Intent, that started the service to stop it, because doing this on application startup, then exiting and restaring it results in multiple Services to run.
At this point i ran out of ideas, on how to check for running services. Please if you know about any way to do this, let me know! Thanks for any hints!
EDIT
Here are the source materials which gave me the idea to try the above methods (maybe only i use them incorrectly):
The local storage: Titanium.App.Properties
The method for accessing running services: Titanium.Android.getCurrentService
The method for stoping a service with an Intent: Titanium.Android.stopService
And the full source for the NotificationHandler "class" and NotificationService.js that I wrote, and their usage: link
Use Bencoding AlarmManager and it will provide all you need to schedule an alarm notification : https://github.com/benbahrenburg/benCoding.AlarmManager
This module provides what you need. It's really easy - just set repeat to daily when sheduling a Notification or Service.
Refer https://gist.github.com/itsamiths/6248106 for fully functional code
I am checking if the service is started then show daily notification or else start service and then show daily notification
var isRunning = Ti.App.Properties.getBool("service_running", false);//get service running bool status
if (isRunning) {
Ti.API.info('service is running');
} else {
Ti.API.info('service is not running');
alarmManager.addAlarmService({
service : 'com.mkamithkumar.whatstoday.DailyEventNotificatoinService',
hour : "08",
repeat : 'daily'
});
}
I come one year late, but maybe this can help others in the future.
We had the same idea: run the service forever and do the checks on every cycle (I must check 20 different communications).
And I had the same problem: how to detect that the service is running, to don't run again to don't duplicate the checks.
To solve that problem, what I did is get the current time on every cycle and save it to store.
Then, before launch a new service, I check if the last execution was to far in time: if true, then the service was stopped, else is running.
Not very elegant, but was the only way I found to avoid the problem of the user killing the app (and the service).
This is my code for the "launcher" of the service. In my case, I test 30 seconds far away:
exports.createAndroidServiceForNotifications = function(seconds) {
var moment = require('alloy/moment');
var diffSeconds = moment().diff(Ti.App.Properties.getString('serviceLastRun', new Date().getTime() - 60000), 'second');
if (diffSeconds > 30) {
var now = new Date().getTime();
var delta = new Date(now + (seconds * 1000));
var deltaMS = delta - now;
var intent = Ti.Android.createServiceIntent({
url : 'notificationsService.js'
});
intent.putExtra('interval', deltaMS);
Ti.Android.startService(intent);
}
};

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