Ответ 1
Недавно я реализовал такую функцию в своем проекте. Я использовал Ionic, и я использовал режим фона плагина Cordova от Katzer. (сейчас я запускаю фоновый процесс с помощью симулятора iOS 9.2).
Вот фрагмент кода, чтобы заставить его работать:
// 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 () {
// The code that you want to run repeatedly
}, 3000);
}
}, false);
Здесь пример Ionic 2 ES6 готов:
// Import the Ionic Native plugin
import { BackgroundMode } from 'ionic-native';
// Run when the device is ready
document.addEventListener('deviceready', () => {
// 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.
BackgroundMode.setDefaults({
title: 'TheTitleOfYourProcess',
text: 'Executing background tasks.'
});
// Enable background mode
BackgroundMode.enable();
// Called when background mode has been activated
// note: onactive now returns an returns an observable that emits when background mode is activated
BackgroundMode.onactivate.subscribe(() => {
// The code that you want to run repeatedly
});
}, false);