Skip to content

Instantly share code, notes, and snippets.

@kosso
Created March 12, 2011 17:55
Show Gist options
  • Save kosso/867404 to your computer and use it in GitHub Desktop.
Save kosso/867404 to your computer and use it in GitHub Desktop.
Background Service notification for Titanium
/* Kosso : March 12th 2011
This the only way I managed to do this without the app crashing on resume.
Done slightly differently to the KS example, since they unregister the service and
do not use a setInterval timer.
*/
//############ in app.js :
// test for iOS 4+
function isiOS4Plus(){
if (Titanium.Platform.name == 'iPhone OS'){
var version = Titanium.Platform.version.split(".");
var major = parseInt(version[0]);
// can only test this support on a 3.2+ device
if (major >= 4){
return true;
}
}
return false;
}
if (isiOS4Plus()){
var service;
// Ti.App.iOS.addEventListener('notification',function(e){
// You can use this event to pick up the info of the noticiation.
// Also to collect the 'userInfo' property data if any was set
// Ti.API.info("local notification received: "+JSON.stringify(e));
// });
// fired when an app resumes from suspension
Ti.App.addEventListener('resume',function(e){
Ti.API.info("app is resuming from the background");
});
Ti.App.addEventListener('resumed',function(e){
Ti.API.info("app has resumed from the background");
// this will unregister the service if the user just opened the app
// is: not via the notification 'OK' button..
if(service!=null){
service.stop();
service.unregister();
}
Titanium.UI.iPhone.appBadge = null;
});
Ti.App.addEventListener('pause',function(e){
Ti.API.info("app was paused from the foreground");
service = Ti.App.iOS.registerBackgroundService({url:'bg.js'});
Ti.API.info("registered background service = "+service);
});
}
//############## end app.js changes
//############# in bg.js :
Ti.API.info("hello from a background service!");
var alertCount = 0;
var notification = null;
function notify(resp){
// This creates the notification alert on a 'paused' app
notification = Ti.App.iOS.scheduleLocalNotification({
alertBody:resp,
alertAction:"OK",
userInfo:{"hello":"world"},
badge:alertCount,
date:new Date(new Date().getTime() + 10)
});
}
function checkFeed(){
// silently ignore this if there's no network connection
if (Titanium.Network.online == false) {
return;
}
var t = new Date().getTime();
Ti.API.info('checking feed in bg.. '+t);
var xhr = Titanium.Network.createHTTPClient();
xhr.timeout = 1000000;
xhr.onerror = function(e){
Ti.API.info('IN ERROR ' + e.error);
};
xhr.onload = function(){
// demo to increase the badge number...
alertCount++;
var response = this.responseText;
Ti.API.info("the reply was: "+response);
// open the notification
notify(response);
};
xhr.open('GET','http://YOUR_SERVER.COM/service_test.php');
xhr.send();
/*
my service_test.php is simply:
<?php
echo "hello from a server at: ".date("r");
?>
*/
}
Ti.App.iOS.addEventListener('notification',function(){
Ti.API.info('background event received = '+notification);
Ti.App.currentService.stop();
Ti.App.currentService.unregister();
});
// Kick off a timer to trigger a function called 'checkFeed' every 10 seconds (= 10000 ms)
var timer = setInterval(checkFeed, 10000);
//####### END bg.js
@kosso
Copy link
Author

kosso commented Aug 23, 2011

When you change your SDK settings, have you made sure to delete the contents of your [PROJECT]/build/iphone/build/* folder before trying to rebuild?

If that doesn't fix your webViews, then there must be something wrong with your code. Webviews appear to be working fine in 1.7.2 for me.

@kosso
Copy link
Author

kosso commented Aug 23, 2011

Does your code attempt to do anything in different 'contexts'? Things have certainly changed in that respect since 1.6.2 which I had to change some code to deal with.

@H-Max
Copy link

H-Max commented Aug 23, 2011

Yep, been cleaning the build/iphone/build directory. This does not help. My webview is interacting quite a lot with the native code, and this is where the problem must be, but debugging webviews is a real PITA...

@H-Max
Copy link

H-Max commented Aug 23, 2011

Tried again using 1.7.2 and without worrying about my webviews. This does not help. I'm starting to fear it can't find the path to my bg.js (I don't know why, because it's in the same directory as the app.js...).

@kosso
Copy link
Author

kosso commented Aug 23, 2011

Best way to test that is to try outputting some Ti.API.info('hello from bg.js'); somewhere.

You should then see if it's finding it.

@H-Max
Copy link

H-Max commented Aug 23, 2011

That's what I did, at the top of my empty bg.js. And it never shows. I'm still searching why...

@H-Max
Copy link

H-Max commented Aug 23, 2011

Well, news : if I register the background event within my "pause" or "resumed" events, it won't work (in 1.6.2 or 1.7.2). BUT, if I just register it in app.js at the beginning of the app, it will work. Now I have to make sure the code won't run at all when the app is resumed, or I'm doomed...

@kosso
Copy link
Author

kosso commented Aug 23, 2011

Cool. Then you should see in the code above how to unregister it in the 'resumed' event ;)
Lines 36 - 45

@H-Max
Copy link

H-Max commented Aug 23, 2011

Except that I'm doomed if I can't register it back... I'll tell you how it goes.

@H-Max
Copy link

H-Max commented Aug 23, 2011

Looks like the backgroundService is really not running when I resume the app, without having to unregister it. That's pretty much what I wanted. In the first place, why did you write your code that way ?

@kosso
Copy link
Author

kosso commented Aug 23, 2011

Hmm that 'should' work ;) I had a few shaky crashes now and then while trying to come up with this, but the code above was the only way I got it to work again and again.

By the way. I should note that Apple 'might' not be too happy with trying to even do networked calls while in the background, so your mileage may vary ;)

@H-Max
Copy link

H-Max commented Aug 23, 2011

I'm not planning on doing more than a simple check for new content once or twice a day... Anyhow, they're not very happy with the app I've been working on anyway (been kicked twiced already :/ )

@vgu
Copy link

vgu commented Sep 8, 2011

Hello,

I used those code snippet and noticed that service stops to work in a 10 minutes.
Here is my original post: http://developer.appcelerator.com/question/125271/background-service-stops-after-five-minutes
Is that service long-running in your case? Have you ever make background service to sent http requests while hour or more?
SDK 1.7.0

@rexdahk
Copy link

rexdahk commented Nov 17, 2011

Hi Kosso,

I'm able to run your code in iOS5, starts the app, make it background, it will start the background service
However, after resume to the app, when I press home key to pause the app, it didn't register the background service until I resume to the app again. do you know why?
e.g
1 goto app, bg serv start
2 resume app, bg serv not start
3 resume app, bg serv start
4 resume app, bg serv not start
...

@JigarM
Copy link

JigarM commented Mar 20, 2013

Hi Kosso,

I use background service Code and it is working fine.
I want to refresh my data to every 10mins.
Is it possible.??
Because i know we have only maximum 10 mins for background service but i need to refresh my data to every 10 mins in titanium.

is it possible.??

@mervint
Copy link

mervint commented Sep 29, 2015

Background service runs, when app goes to the background. In foreground, you could write the code in a function and call this function with setTimeout as in this link Check the comment by Mark.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment