Service creates a Service object that runs in the background and can be used to monitor online
databases, local communication ports or changes in data on the file system. They can also trigger
notifications to the user and launch apps when changes or timeouts occur.
Note: Your service script must be called 'Service.js'
Example - Foreground app
function OnStart()
{
//Create a layout.
lay = app.CreateLayout( "linear", "VCenter,FillXY" );
//Create text control to display data from the service.
txt = app.CreateText( "", 0.4 );
txt.SetMargins( 0, 0.05, 0, 0 );
txt.SetTextSize( 22 );
lay.AddChild( txt );
//Create an 'Send Message' button.
btn = app.CreateButton( "Send Message to Service", 0.6, 0.1 );
lay.AddChild( btn );
btn.SetOnTouch( function(){svc.SendMessage("change")} );
//Create a 'Stop Service' button.
btn = app.CreateButton( "Stop Service", 0.6, 0.1 );
lay.AddChild( btn );
btn.SetOnTouch( function(){svc.Stop()} );
//Add layout to app.
app.AddLayout( lay );
//Start/connect to our service.
svc = app.CreateService( "this","this", OnServiceReady );
svc.SetOnMessage( OnServiceMessage );
//This will cause your service to start at boot.
//(Set it to "none" if you need to stop it starting)
//app.SetAutoBoot( "Service" );
}
//Called after our service has started.
function OnServiceReady()
{
console.log( "Service Ready" );
}
//Called when messages comes from our service.
function OnServiceMessage( msg )
{
txt.SetText( "Count: " + msg );
}
Example - Background Service (Service.js)
//Init variables.
var count = 0;
var diff = 1;
//Called when service is started.
function OnStart()
{
app.ShowPopup( "Hello from Service!" );
//Start a timer to do some regular work.
setInterval( DoWork, 1000 );
}
//Called when we get a message from main app.
function OnMessage( msg )
{
console.log( msg );
//Handle commands from main App.
if( msg=="change" ) diff = (diff > 0 ? -1 : 1);
}
//Do some work.
function DoWork()
{
//This is where we do some regular background task
//(here we just modify a counter).
count += diff;
//Send data to the App (if it is running).
app.SendMessage( count );
}
The following methods are avaiable on the Service object: