Titanium JIRA Archive
Titanium SDK/CLI (TIMOB)

[TIMOB-14658] iOS7: Background Service no longer functions

GitHub Issuen/a
TypeBug
PriorityHigh
StatusClosed
ResolutionCannot Reproduce
Resolution Date2013-08-27T09:23:31.000+0000
Affected Version/sRelease 3.1.1
Fix Version/s2013 Sprint 18, 2013 Sprint 18 API
ComponentsiOS
Labelsios7, iphone
ReporterMartin Williamson
AssigneeIngo Muschenetz
Created2013-07-24T10:28:10.000+0000
Updated2017-03-31T20:31:33.000+0000

Description

Since iOS 7 beta 3, using a background service with a setTimeout poll time, no longer runs after 1 iteration, after that it just seems to stop. *Global that initiates the service*
var service;

if (Titanium.Platform.name == 'iPhone OS'){
	// Globe event handelers
	Ti.App.addEventListener('pause', function(e){ 
		if (Ti.App.Properties.getBool('track')) {
			service = Ti.App.iOS.registerBackgroundService({url:'/service/bg.js'});	
		}
	});
			
	// Stop background service on launch.
	Ti.App.addEventListener('resume', function(e){
		
		if (service != null) {
			service.stop();
			service.unregister();
		};
	});
};
*bg.js*
// Background service script
// NOTE: Runs in background when enabled by user to track device and report back to ETMS system.
// This is for use by company security departments to ensure safety of user.


	if (!Ti.Geolocation.locationServicesEnabled) {
		Ti.App.iOS.scheduleLocalNotification({
		    alertBody: 'Location services are not enabled.',
		    date:new Date(new Date().getTime() + 1000) // 1 second after unregister
		}); 
	}
		
	//var tracking = require('business/tracking');
	
	var lastTrackDate = 0;
	var doTrack = false;
	
	function track() {	
			trackGPS('track');
			lastTrackDate = new Date().getTime();
			setTimeout(track, Ti.App.Properties.getInt('trackingpolltime'));
	};
	track();

	var nowTime;
	var stayaliveInerval = 311000;
	var nextstayalivepoll;
	function stayalive() {
		nowTime = new Date().getTime();
		if (lastTrackDate + stayaliveInerval <= nowTime) {	
			trackGPS('update');
		}
		nextstayalivepoll = (nowTime - lastTrackDate) > stayaliveInerval ? stayaliveInerval : stayaliveInerval - (nowTime - lastTrackDate);
		Ti.API.info(new Date() + ' - GPS Stay Alive:' + nextstayalivepoll);
		setTimeout(stayalive, nextstayalivepoll);
	}
	stayalive();
	
	
	// Event listener for GPS
	function trackGPS(trackType)
	{
		if (trackType == 'track') {
			doTrack = true;
		}
		else {
			doTrack = false;
		};
		
		Ti.Geolocation.addEventListener('location', getPosition);		
	};
	
	
	function getPosition(e) {
	    if(e.error){
	    	Ti.API.info(new Date() + ' - GPS error');
	    }
	    else {
	    	Ti.Geolocation.purpose = "Determine device location on users request.";
	    	Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_HIGH;
		    Ti.Geolocation.distanceFilter = 0;
		  
		    Ti.Geolocation.getCurrentPosition(function(e){
		        if(e.error){	
		        Ti.API.info(new Date() + ' - GPS error');
		        }
		        else {
			        //Get the GPS goods
			        var longitude = e.coords.longitude;
			        var latitude = e.coords.latitude;
			        var altitude = e.coords.altitude;
			        var accuracy = e.coords.accuracy;
			        var timestamp = e.coords.timestamp;
			        
			        if (accuracy < 50) {
			        	Ti.API.info(new Date() + ' - GPS accuracy good,  background event listener:' + e.coords.accuracy);
						
					if (doTrack == true) {
						Ti.API.info(new Date() + ' - Contacting web service');
						SendTrackingInfo(e.coords.latitude, e.coords.longitude);
					}; 
					
					Titanium.Geolocation.removeEventListener('location', getPosition);	
			        };
		        };
		    });
	    }; 
	};
	
	var client = null;
	
	function SendTrackingInfo(latitude, longitude) {
	
	 	client = Ti.Network.createHTTPClient({
		    onload : function(e) {Ti.API.info(new Date() + ' - Background web service conected');},
	   		onerror : function(e) {Ti.API.info(new Date() + ' - Background web service NOT conected');},
	   	 	timeout : 28000
		});
		
		// Prepare and send the connection.
		client.open("GET", 
			//'http://192.168.0.23/tracking/TrackingService/Track?deviceid=' +
		//	Ti.App.Properties.getString('deviceid') +
		//	'&longitude='+longitude+'&latitude='+latitude+'&clientid=' +
		//	Ti.App.Properties.getString('clientid') +
		//	'&trackingtypeid=1');
		
	//	client.send();

	alert('Service Called');

	};

Comments

  1. Daniel Sefton 2013-07-24

    Hi Martin, Please can you provide a reproducible test case that we can drop into an app.js and run? Thanks!
  2. Martin Williamson 2013-07-25

    here you go. [moved to description]
  3. Vishal Duggal 2013-08-27

    Could not reproduce. IOS7 DP5
  4. Martin Williamson 2013-09-02

    After upgrading to iOS 7 beta 6 and using the latest release of titanium, this appears to function but not as intended, while the device is awake it seems to work on or before the interval, however with the screen off it does not report after 1-2 iterations, however it then sends a load of reports once the device is awake again (screen on and unlocked) as if it was caching them for later, providing the interval has passed several times
  5. Ingo Muschenetz 2013-09-03

    [~anvil_martin] I wonder if that's related to TIMOB-14617?
  6. Martin Williamson 2013-09-05

    Ingo Muschenetz - I think it is, I am doing a lot of investigation into this at the moment is this breaks our core functionality (a tracking application that runs in the background). I have yet to produce any solid or reproducible results, even tracking at one minute intervals as soon as the screen goes off it stops tracking and doesn't always seem to resume on wake up or after any set amount of time, I am beginning to think that there have been some changes to the implementation of the distance filtering as well. After Installing and pointing Titanium at Xcode 5 DP 6, the simulator runs the code perfectly and doesn't die off when locked, however on the device (iphone 5 iOS 7 beta 6) the background service stops after 2 iterations. I also cannot seem to attach it to the debugger either, both just sit on the network waiting for a connection so, any suggestions on debugging it on the device?
  7. Martin Williamson 2013-09-06

    After a lot more investigation, it turns out that as of iOS 7, background services are killed after 3 minutes, you have to use the new methods they have implemented to run, we are changing to location based (using distance filter) with a keep alive function for now which seems to work
  8. Lee Morris 2017-03-31

    Closing ticket with reference to the above comment.

JSON Source