===== Web file service ===== Sample service to keep checking whether a file on a webserver has changed ==== The code ==== === User interface === Create a new DroidScript JavaScript project with the following code in the main .js file var svc; //Called when application is started. function OnStart() { //Create a layout. var lay = app.CreateLayout( "linear", "VCenter,FillXY" ); //Create a 'Stop Service' button. var btn = app.CreateButton( "Stop Service", 0.6, -1 ); lay.AddChild( btn ); btn.SetOnTouch( btn_OnTouchStop ); //Add layout to app. app.AddLayout( lay ); //Start/connect to our service. svc = app.CreateService( "this","this", OnServiceReady ); //uncomment next line to cause your service to start at boot. //app.SetAutoBoot( "Service" ); } //Called after our service has started. function OnServiceReady() { console.log( "Service Ready" ); var running=false; var me=app.GetPackageName()+":droidscript_service"; var lst = app.GetRunningServices(); for (var key in lst) { if(lst[key].name === me) { console.log(me + " running"); break; } } } function btn_OnTouchStop() { //Tell service we are quitting. svc.SendMessage( "quit" ); //give the service time to clean up setTimeout(delayedStop,1000); } function delayedStop() { //Stop the service. svc.Stop(); // exit main app app.Exit(); } function OnData( isStartUp ) { var id=app.GetNotifyId(); if(id === "servFilx" ) { app.Alert("Notification touched") ; } } === Service.js === Add a second file called Service.js with the following code var g_ = {lastResponse:""}; function OnStart() { app.ShowPopup("Service started"); g_.notify=app.CreateNotification(); //Check file SendRequest(); //Check again every 30 seconds g_.interval = setInterval(SendRequest,30000); } //Send an http get request. function SendRequest() { app.HttpRequest( "GET", "http://sgarman.net", "/downloadable.txt", "", HandleReply, "" ); } //Handle the server's reply function HandleReply( error, response ) { if( !error ) { if(g_.lastResponse !== response) { g_.lastResponse = response; g_.notify.SetMessage( response, "File contents", response ); g_.notify.Notify("servFilx"); } else console.log("same"); } else { app.ShowPopup( "Error: " + response ); } } //Called when we get a service message. function OnMessage( msg ) { //Show debug in WiFi IDE. console.log( msg ); //Handle messages from main App. if( msg=="quit" ) { clearInterval(g_.interval); console.log("loop stopped"); g_.notify.Cancel("servFilx"); } }