how can i create run app even user close it android - 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

Related

Separate background thread pointing on an old ViewModel after restating app

I have an app that do BLE scan on the background and alert the user by playing a sound and shows up a popup with a button to snooze. So if the user click on that button the app will stop playing the alert sound and dismiss the popup for a while (default duration is one minute)
So if the app in background mode it still works and can play the alert sound and then when I reopen the app by clicking on the service notification it shows the popup
So I'm calculating the spent time after the user click on dismiss button on a separate thread using some variables in the viewModel because I need them in other place.
Here is my code
Thread {
while (true) {
val previous = tagDetailsAlertsViewModel.stopAlertingAt.value
val durationMin = PreferenceManager.getDefaultSharedPreferences(this).getString("dismiss_duration", "1")!!.toInt()
val diff = (Date().time - previous!!.time) / 1000 / 60
if ( diff >= durationMin && tagDetailsAlertsViewModel.isStopAlerting() ) {
tagDetailsAlertsViewModel.setStopAlerting(false)
}
}
}.start()
The code above is to check always if the duration past to alert again the user
binding.btnDismiss.setOnClickListener {
tagDetailsAlertsViewModel.stopAlertingAt.value = Date()
tagDetailsAlertsViewModel.setStopAlerting(true)
}
So the problem here is when I close the app and open it again the line code below will point always on the last value before I close the app
val previous = tagDetailsAlertsViewModel.stopAlertingAt.value
But here it change correct the value
tagDetailsAlertsViewModel.stopAlertingAt.value = Date()
So if I understood correctly is that the background thread still use the mode ViewModel with the old value and I can't figure out how to fix that.
I'm using Koin Module for my viewModels

Xamarin Forms Android Pie Not Getting Current Location in App Background Sleep Mode

I want to get current location, when app went into sleep mode or Background.Currently i am using > Plugin.Geolocator.CrossGeolocator.Current DLL in App OnSleep() , But Its Working Till Android 8.1 but Android Pie Not updating current Location Values.. How to Achieve in Android Pie?
Sample Code :
protected override async void OnSleep()
{
var minute = TimeSpan.FromSeconds(30);
Device.StartTimer(minute, () =>
{
await Task.Run(async () =>
{
TimeSpan t = TimeSpan.FromSeconds(10);
var locator = Plugin.Geolocator.CrossGeolocator.Current;
locator.DesiredAccuracy = 5;
var position = await locator.GetPositionAsync(timeout: t);
//API Method
});
});
}
You can not just spin up a thread and expect it to keep running after the OS places the app into the background or battery saving mode.
You will have to setup an Android Service (and foreground it) at a minimum to handle your location updates.
Background Execution Limits
https://developer.android.com/about/versions/oreo/background
Foreground Services
https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services
Schedule tasks with WorkManager
https://developer.android.com/about/versions/pie/android-9.0

Repeatedly background task ionic framework

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

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