Merge pull request #811 from Red-Folder/master

[Android] Background Service - Cordova 2.x.x version
This commit is contained in:
macdonst
2012-09-28 08:26:22 -07:00
6 changed files with 562 additions and 0 deletions

View File

@@ -0,0 +1,78 @@
package com.yournamespace.yourappname;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.red_folder.phonegap.plugin.backgroundservice.BackgroundService;
public class MyService extends BackgroundService {
private final static String TAG = MyService.class.getSimpleName();
private String mHelloTo = "World";
@Override
protected JSONObject doWork() {
JSONObject result = new JSONObject();
try {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String now = df.format(new Date(System.currentTimeMillis()));
String msg = "Hello " + this.mHelloTo + " - its currently " + now;
result.put("Message", msg);
Log.d(TAG, msg);
} catch (JSONException e) {
}
return result;
}
@Override
protected JSONObject getConfig() {
JSONObject result = new JSONObject();
try {
result.put("HelloTo", this.mHelloTo);
} catch (JSONException e) {
}
return result;
}
@Override
protected void setConfig(JSONObject config) {
try {
if (config.has("HelloTo"))
this.mHelloTo = config.getString("HelloTo");
} catch (JSONException e) {
}
}
@Override
protected JSONObject initialiseLatestResult() {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onTimerEnabled() {
// TODO Auto-generated method stub
}
@Override
protected void onTimerDisabled() {
// TODO Auto-generated method stub
}
}

View File

@@ -0,0 +1,69 @@
# Background Service Plugin for Phonegap #
A plugin (and framework code) that allows the development and operation of an Android Background Service.
The example MyService Background Service will write a Hello message to the LogCat every minute. The MyService is designed as sample code.
## Adding the plugin to your project ##
Copy the files to the following locations:
* libs\backgroundserviceplugin-2.0.0.jar
* src\com\yournamespace\yourappname\MyService.java
* assets\www\backgroundService-2.0.0.js
* assets\www\myService-2.0.0.js
* assets\www\index-2.0.0.html
Add the following to res\xml\config.xml
```
<plugin name="BackgroundServicePlugin" value="com.red_folder.phonegap.plugin.backgroundservice.BackgroundServicePlugin"/>
```
Add the following to AndroidManifest.xml
```
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<!-- To be added within Application nde -->
<service android:name="com.yournamespace.yourappname.MyService">
<intent-filter>
<action android:name="com.yournamespace.yourappname.MyService"/>
</intent-filter>
</service>
<receiver android:name="com.red_folder.phonegap.plugin.backgroundservice.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
```
## Further Information ##
Further information on the plugin can be found at:
* http://red-folder.blogspot.co.uk/2012/09/phonegap-android-background-service.html
* http://red-folder.blogspot.com/2012/09/phonegap-android-background-service_11.html
The below is a tutorial to create your own Twitter service:
* http://red-folder.blogspot.com/2012/09/phonegap-service-tutorial-part-1.html
* http://red-folder.blogspot.com/2012/09/phonegap-service-tutorial-part-2.html
* http://red-folder.blogspot.com/2012/09/phonegap-service-tutorial-part-3.html
Please let me know your thoughts and comments.
## Licence ##
The MIT License
Copyright (c) 2012 Red Folder Consultancy Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,181 @@
/*
* Copyright 2012 Red Folder Consultancy Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Constructor
*/
function CreateBackgroundService(serviceName, require, exports, module) {
var exec = require("cordova/exec");
var BackgroundService = function (serviceName) {
var ServiceName = serviceName
this.getServiceName = function() {
return ServiceName;
};
};
var BackgroundServiceError = function (code, message) {
this.code = code || null;
this.message = message || null;
};
/**
* All methods attempt to return the following data in both the success and failure callbacks
* Front end development should take into account any all or all of these values may be null
*
* Following returned in the JSONObject:
* Boolean Success - was the call a success
* int ErrorCode - Error code if an error occurred, else will be zero
* String ErrorMessage - Text representation of the error code
* Boolean ServiceRunning - True if the Service is running
* Boolean TimerEnabled - True if the Timer is enabled
* Boolean RegisteredForBootStart - True if the Service is registered for boot start
* JSONObject Configuration - A JSONObject of the configuration of the service (contents dependant on the service)
* JSONObject LastestResult - A JSONObject of the last result of the service (contents dependant on the service)
*/
/**
* Starts the Service
*
* @param successCallback The callback which will be called if the method is successful
* @param failureCallback The callback which will be called if the method encounters an error
*/
BackgroundService.prototype.startService = function(successCallback, failureCallback) {
return exec( successCallback,
failureCallback,
'BackgroundServicePlugin',
'startService',
[this.getServiceName()]);
};
/**
* Stops the Service
*
* @param successCallback The callback which will be called if the method is successful
* @param failureCallback The callback which will be called if the method encounters an error
*/
BackgroundService.prototype.stopService = function(successCallback, failureCallback) {
return exec( successCallback,
failureCallback,
'BackgroundServicePlugin',
'stopService',
[this.getServiceName()]);
};
/**
* Enables the Service Timer
*
* @param milliseconds The milliseconds used for the timer
* @param successCallback The callback which will be called if the method is successful
* @param failureCallback The callback which will be called if the method encounters an error
*/
BackgroundService.prototype.enableTimer = function(milliseconds, successCallback, failureCallback) {
return exec( successCallback,
failureCallback,
'BackgroundServicePlugin',
'enableTimer',
[this.getServiceName(), milliseconds]);
};
/**
* Disabled the Service Timer
*
* @param successCallback The callback which will be called if the method is successful
* @param failureCallback The callback which will be called if the method encounters an error
*/
BackgroundService.prototype.disableTimer = function(successCallback, failureCallback) {
return exec( successCallback,
failureCallback,
'BackgroundServicePlugin',
'disableTimer',
[this.getServiceName()]);
};
/**
* Sets the configuration for the service
*
* @oaran configuration JSONObject to be sent to the service
* @param successCallback The callback which will be called if the method is successful
* @param failureCallback The callback which will be called if the method encounters an error
*/
BackgroundService.prototype.setConfiguration = function(configuration, successCallback, failureCallback) {
return exec( successCallback,
failureCallback,
'BackgroundServicePlugin',
'setConfiguration',
[this.getServiceName(), configuration]);
};
/**
* Registers the service for Boot Start
*
* @param successCallback The callback which will be called if the method is successful
* @param failureCallback The callback which will be called if the method encounters an error
*/
BackgroundService.prototype.registerForBootStart = function(successCallback, failureCallback) {
return exec( successCallback,
failureCallback,
'BackgroundServicePlugin',
'registerForBootStart',
[this.getServiceName()]);
};
/**
* Deregisters the service for Boot Start
*
* @param successCallback The callback which will be called if the method is successful
* @param failureCallback The callback which will be called if the method encounters an error
*/
BackgroundService.prototype.deregisterForBootStart = function(successCallback, failureCallback) {
return exec( successCallback,
failureCallback,
'BackgroundServicePlugin',
'deregisterForBootStart',
[this.getServiceName()]);
};
/**
* Get the current status of the service.
*
* @param successCallback The callback which will be called if the method is successful
* @param failureCallback The callback which will be called if the method encounters an error
*/
BackgroundService.prototype.isRegisteredForBootStart = function(successCallback, failureCallback) {
return exec( successCallback,
failureCallback,
'BackgroundServicePlugin',
'isRegisteredForBootStart',
[this.getServiceName()]);
};
/**
* Returns the status of the service
*
* @param successCallback The callback which will be called if the method is successful
* @param failureCallback The callback which will be called if the method encounters an error
*/
BackgroundService.prototype.getStatus = function(successCallback, failureCallback) {
return exec( successCallback,
failureCallback,
'BackgroundServicePlugin',
'getStatus',
[this.getServiceName()]);
};
var backgroundService = new BackgroundService(serviceName);
module.exports = backgroundService;
};

View File

@@ -0,0 +1,215 @@
<!DOCTYPE HTML>
<!--
/*
* Copyright 2012 Red Folder Consultancy Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-->
<html>
<head>
<title>MyService</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" src="backgroundService-2.0.0.js"></script>
<script type="text/javascript" src="myService-2.0.0.js"></script>
<script type="text/javascript" >
var myService = cordova.require('cordova/plugin/myService');
document.addEventListener('deviceready', function() {
getStatus();
}, true);
function handleSuccess(data) {
updateView(data);
}
function handleError(data) {
alert("Error: " + data.ErrorMessage);
alert(JSON.stringify(data));
updateView(data);
}
/*
* Button Handlers
*/
function getStatus() {
myService.getStatus( function(r){handleSuccess(r)},
function(e){handleError(e)});
};
function startService() {
myService.startService( function(r){handleSuccess(r)},
function(e){handleError(e)});
}
function stopService() {
myService.stopService( function(r){handleSuccess(r)},
function(e){handleError(e)});
}
function enableTimer() {
myService.enableTimer( 60000,
function(r){handleSuccess(r)},
function(e){handleError(e)});
}
function disableTimer() {
myService.disableTimer( function(r){handleSuccess(r)},
function(e){handleError(e)});
};
function registerForBootStart() {
myService.registerForBootStart( function(r){handleSuccess(r)},
function(e){handleError(e)});
}
function deregisterForBootStart() {
myService.deregisterForBootStart( function(r){handleSuccess(r)},
function(e){handleError(e)});
}
function setConfig() {
var helloToTxt = document.getElementById("helloToTxt");
var helloToString = helloToTxt.value;
var config = {
"HelloTo" : helloToString
};
myService.setConfiguration( config,
function(r){handleSuccess(r)},
function(e){handleError(e)});
}
/*
* View logic
*/
function updateView(data) {
var serviceBtn = document.getElementById("toggleService");
var timerBtn = document.getElementById("toggleTimer");
var bootBtn = document.getElementById("toggleBoot");
var updateBtn = document.getElementById("updateBtn");
var refreshBtn = document.getElementById("refreshBtn");
var serviceStatus = document.getElementById("serviceStatus");
var timerStatus = document.getElementById("timerStatus");
var bootStatus = document.getElementById("bootStatus");
serviceBtn.disabled = false;
if (data.ServiceRunning) {
serviceStatus.innerHTML = "Running";
serviceBtn.onclick = stopService;
timerBtn.disabled = false;
if (data.TimerEnabled) {
timerStatus.innerHTML = "Enabled";
timerBtn.onclick = disableTimer;
} else {
timerStatus.innerHTML = "Disabled";
timerBtn.onclick = enableTimer;
}
updateBtn.disabled = false;
updateBtn.onclick = setConfig;
refreshBtn.disabled = false;
refreshBtn.onclick = getStatus;
} else {
serviceStatus.innerHTML = "Not running";
serviceBtn.onclick = startService;
timerBtn.disabled = true;
timerEnabled = false;
updateBtn.disabled = true;
refreshBtn.disabled = true;
}
bootBtn.disabled = false;
if (data.RegisteredForBootStart) {
bootStatus.innerHTML = "Registered";
bootBtn.onclick = deregisterForBootStart;
} else {
bootStatus.innerHTML = "Not registered";
bootBtn.onclick = registerForBootStart;
}
if (data.Configuration != null)
{
try {
var helloToTxt = document.getElementById("helloToTxt");
helloToTxt.value = data.Configuration.HelloTo;
} catch (err) {
}
}
if (data.LatestResult != null)
{
try {
var resultMessage = document.getElementById("resultMessage");
resultMessage.innerHTML = data.LatestResult.Message;
} catch (err) {
}
}
}
</script>
</head>
<body>
<h1>MyService</h1>
<table>
<tr>
<th>Service</th>
<td><div id="serviceStatus"></div></td>
<td><input disabled id="toggleService" type="button" value="toggle"/></td>
</tr>
<tr>
<th>Timer</th>
<td><div id="timerStatus"></div></td>
<td><input disabled id="toggleTimer" type="button" value="toggle"/></td>
</tr>
<tr>
<th>Boot</th>
<td><div id="bootStatus"></div></td>
<td><input disabled id="toggleBoot" type="button" value="toggle"/></td>
</tr>
<tr>
<th colspan=3 align="center">Configuration</th>
</tr>
<tr>
<th align="left">Hello To</th>
<td colspan=2 align="center"><input id="helloToTxt" type="Text"/></td>
</tr>
<tr>
<td colspan=3 align="center"><input disabled id="updateBtn" type="button" value="Update Config"/></td>
</tr>
<tr>
<th colspan=3 align="center">Latest Result</th>
</tr>
<tr>
<td colspan=3 align="center"><div id="resultMessage"></div></td>
</tr>
<tr>
<td colspan=3 align="center"><input disabled id="refreshBtn" type="button" value="Refresh"/></td>
</tr>
</table>
</body>
</html>

View File

@@ -0,0 +1,19 @@
/*
* Copyright 2012 Red Folder Consultancy Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
cordova.define( 'cordova/plugin/myService', function(require, exports, module) {
CreateBackgroundService('com.yournamespace.yourappname.MyService', require, exports, module);
});