Set default settings through setDefaults

This commit is contained in:
Sebastián Katzer 2014-12-14 13:38:36 +01:00
parent 0994147d13
commit cbed556154
5 changed files with 143 additions and 48 deletions

View File

@ -1,6 +1,13 @@
## ChangeLog ## ChangeLog
#### Version 0.6.1 (not yet released)
- [enhancement:] Set default settings through `setDefaults`.
- [bugfix:] Events caused thread collision.
#### Version 0.6.0 (14.12.2014) #### Version 0.6.0 (14.12.2014)
- [feature:] Android support - [feature:] Android support
- [feature:] Get default settings through `getDefaults`.
- [feature:] Change Android notification through `configure`.
- [feature:] `onactivate`, `ondeactivate` and `onfailure` callbacks. - [feature:] `onactivate`, `ondeactivate` and `onfailure` callbacks.
- [___change___:] Disabled by default - [___change___:] Disabled by default
- [enhancement:] iOS does not require user permissions, internet connection and geo location anymore. - [enhancement:] iOS does not require user permissions, internet connection and geo location anymore.

View File

@ -68,11 +68,9 @@ More informations can be found [here][PGB_plugin].
## ChangeLog ## ChangeLog
#### Version 0.6.0 (14.12.2014) #### Version 0.6.1 (not yet released)
- [feature:] Android support - [feature:] Get default settings through `getDefaults`.
- [feature:] `onactivate`, `ondeactivate` and `onfailure` callbacks. - [feature:] Set default settings through `setDefaults`.
- [___change___:] Disabled by default
- [enhancement:] iOS does not require user permissions, internet connection and geo location anymore.
#### Further informations #### Further informations
- The former `plugin.backgroundMode` namespace has been deprecated and will be removed with the next major release. - The former `plugin.backgroundMode` namespace has been deprecated and will be removed with the next major release.
@ -87,7 +85,9 @@ The plugin creates the object ```cordova.plugins.backgroundMode``` with the fol
1. [backgroundMode.enable][enable] 1. [backgroundMode.enable][enable]
2. [backgroundMode.disable][disable] 2. [backgroundMode.disable][disable]
2. [backgroundMode.configure][configure] 3. [backgroundMode.getDefaults][android_specifics]
4. [backgroundMode.setDefaults][android_specifics]
2. [backgroundMode.configure][android_specifics]
3. [backgroundMode.onactivate][onactivate] 3. [backgroundMode.onactivate][onactivate]
4. [backgroundMode.ondeactivate][ondeactivate] 4. [backgroundMode.ondeactivate][ondeactivate]
5. [backgroundMode.onfailure][onfailure] 5. [backgroundMode.onfailure][onfailure]
@ -156,14 +156,18 @@ The following example demonstrates how to enable the background mode after devic
```javascript ```javascript
document.addEventListener('deviceready', function () { document.addEventListener('deviceready', function () {
// Android customization // Android customization
cordova.plugins.backgroundMode.configure({ text:'Doing heavy tasks.'}); cordova.plugins.backgroundMode.setDefaults({ text:'Doing heavy tasks.'});
// Enable background mode // Enable background mode
cordova.plugins.backgroundMode.enable(); cordova.plugins.backgroundMode.enable();
// Called when background mode has been activated // Called when background mode has been activated
cordova.plugins.backgroundMode.onactivate = function () { cordova.plugins.backgroundMode.onactivate = function () {
setInterval(function () { setTimeout(function () {
console.log('App is running in background'); // Modify the currently displayed notification
}); cordova.plugins.backgroundMode.configure({
text:'Running in background for more than 5s now.'
});
}, 5000);
} }
}, false); }, false);
``` ```
@ -171,14 +175,14 @@ document.addEventListener('deviceready', function () {
## Platform specifics ## Platform specifics
### Android Customization ### Android customization
To indicate, that the app is executing tasks in background and being paused would disrupt the user, the plug-in has to create a notification while in background - like a download progress bar.
To indicate, that the app is executing tasks in background and being paused would disrupt the user, the plug-in has to create a notification while in background like a download progress bar. #### Override defaults
The title, ticker and text for that notification can be customized as follows:
The title, ticker and text for that notification can be customized in the following way at any time:
```javascript ```javascript
cordova.plugins.backgroundMode.configure({ cordova.plugins.backgroundMode.setDefaults({
title: String, title: String,
ticker: String, ticker: String,
text: String text: String
@ -188,11 +192,21 @@ cordova.plugins.backgroundMode.configure({
By default the app will come to foreground when taping on the notification. That can be changed also. By default the app will come to foreground when taping on the notification. That can be changed also.
```javascript ```javascript
cordova.plugins.backgroundMode.configure({ cordova.plugins.backgroundMode.setDefaults({
resume: false resume: false
}) })
``` ```
#### Modify the currently displayed notification
It's also possible to modify the currently displayed notification while in background.
```javascript
cordova.plugins.backgroundMode.configure({
title: String,
...
})
```
## Contributing ## Contributing
@ -217,7 +231,7 @@ This software is released under the [Apache 2.0 License][apache2_license].
[changelog]: CHANGELOG.md [changelog]: CHANGELOG.md
[enable]: #prevent_the_app_from_going_to_sleep_in_background [enable]: #prevent_the_app_from_going_to_sleep_in_background
[disable]: #pause_the_app_while_in_background [disable]: #pause_the_app_while_in_background
[configure]: #android_customization [android_specifics]: #android_customization
[onactivate]: #get_informed_when_the_background_mode_has_been_activated [onactivate]: #get_informed_when_the_background_mode_has_been_activated
[ondeactivate]: #get_informed_when_the_background_mode_has_been_deactivated [ondeactivate]: #get_informed_when_the_background_mode_has_been_deactivated
[onfailure]: #get_informed_when_the_background_mode_could_not_been_activated [onfailure]: #get_informed_when_the_background_mode_could_not_been_activated

View File

@ -33,7 +33,6 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.ServiceConnection; import android.content.ServiceConnection;
import android.os.IBinder; import android.os.IBinder;
import android.util.Log;
public class BackgroundMode extends CordovaPlugin { public class BackgroundMode extends CordovaPlugin {
@ -54,8 +53,11 @@ public class BackgroundMode extends CordovaPlugin {
// Flag indicates if the service is bind // Flag indicates if the service is bind
private boolean isBind = false; private boolean isBind = false;
// Settings for the notification // Default settings for the notification
protected static JSONObject settings = new JSONObject(); private static JSONObject defaultSettings = new JSONObject();
// Tmp config settings for the notification
private static JSONObject updateSettings;
// Used to (un)bind the service to with the activity // Used to (un)bind the service to with the activity
private final ServiceConnection connection = new ServiceConnection() { private final ServiceConnection connection = new ServiceConnection() {
@ -89,8 +91,16 @@ public class BackgroundMode extends CordovaPlugin {
CallbackContext callback) throws JSONException { CallbackContext callback) throws JSONException {
if (action.equalsIgnoreCase("configure")) { if (action.equalsIgnoreCase("configure")) {
setSettings(args.getJSONObject(0)); JSONObject settings = args.getJSONObject(0);
updateNotifcation(); boolean update = args.getBoolean(1);
if (update) {
setUpdateSettings(settings);
updateNotifcation();
} else {
setDefaultSettings(settings);
}
return true; return true;
} }
@ -162,13 +172,43 @@ public class BackgroundMode extends CordovaPlugin {
} }
/** /**
* Update the settings for the notification. * Update the default settings for the notification.
* *
* @param newSettings * @param settings
* The new settings * The new default settings
*/ */
private void setSettings(JSONObject newSettings) { private void setDefaultSettings(JSONObject settings) {
settings = newSettings; defaultSettings = settings;
}
/**
* Update the config settings for the notification.
*
* @param settings
* The tmp config settings
*/
private void setUpdateSettings(JSONObject settings) {
updateSettings = settings;
}
/**
* The settings for the new/updated notification.
*
* @return
* updateSettings if set or default settings
*/
protected static JSONObject getSettings() {
if (updateSettings != null)
return updateSettings;
return defaultSettings;
}
/**
* Called by ForegroundService to delete the update settings.
*/
protected static void deleteUpdateSettings() {
updateSettings = null;
} }
/** /**
@ -191,17 +231,16 @@ public class BackgroundMode extends CordovaPlugin {
Intent intent = new Intent( Intent intent = new Intent(
context, ForegroundService.class); context, ForegroundService.class);
if (isDisabled || isBind) { if (isDisabled || isBind)
return; return;
}
try { try {
context.bindService( context.bindService(
intent, connection, Context.BIND_AUTO_CREATE); intent, connection, Context.BIND_AUTO_CREATE);
context.startService(intent);
fireEvent(Event.ACTIVATE, null); fireEvent(Event.ACTIVATE, null);
context.startService(intent);
} catch (Exception e) { } catch (Exception e) {
fireEvent(Event.FAILURE, e.getMessage()); fireEvent(Event.FAILURE, e.getMessage());
} }
@ -219,11 +258,12 @@ public class BackgroundMode extends CordovaPlugin {
Intent intent = new Intent( Intent intent = new Intent(
context, ForegroundService.class); context, ForegroundService.class);
if (isBind) { if (!isBind)
fireEvent(Event.DEACTIVATE, null); return;
context.unbindService(connection);
}
fireEvent(Event.DEACTIVATE, null);
context.unbindService(connection);
context.stopService(intent); context.stopService(intent);
isBind = false; isBind = false;
@ -240,6 +280,9 @@ public class BackgroundMode extends CordovaPlugin {
private void fireEvent (Event event, String params) { private void fireEvent (Event event, String params) {
String eventName; String eventName;
if (updateSettings != null && event != Event.FAILURE)
return;
switch (event) { switch (event) {
case ACTIVATE: case ACTIVATE:
eventName = "activate"; break; eventName = "activate"; break;

View File

@ -86,6 +86,8 @@ public class ForegroundService extends Service {
startForeground(NOTIFICATION_ID, makeNotification()); startForeground(NOTIFICATION_ID, makeNotification());
BackgroundMode.deleteUpdateSettings();
keepAliveTask = new TimerTask() { keepAliveTask = new TimerTask() {
@Override @Override
public void run() { public void run() {
@ -121,7 +123,7 @@ public class ForegroundService extends Service {
@SuppressLint("NewApi") @SuppressLint("NewApi")
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private Notification makeNotification() { private Notification makeNotification() {
JSONObject settings = BackgroundMode.settings; JSONObject settings = BackgroundMode.getSettings();
Context context = getApplicationContext(); Context context = getApplicationContext();
String pkgName = context.getPackageName(); String pkgName = context.getPackageName();
Intent intent = context.getPackageManager() Intent intent = context.getPackageManager()
@ -142,6 +144,7 @@ public class ForegroundService extends Service {
notification.setContentIntent(contentIntent); notification.setContentIntent(contentIntent);
} }
if (Build.VERSION.SDK_INT < 16) { if (Build.VERSION.SDK_INT < 16) {
// Build notification for HoneyComb to ICS // Build notification for HoneyComb to ICS
return notification.getNotification(); return notification.getNotification();

View File

@ -31,7 +31,7 @@ channel.onCordovaReady.subscribe(function () {
// Device plugin is ready now // Device plugin is ready now
channel.onCordovaInfoReady.subscribe( function () { channel.onCordovaInfoReady.subscribe( function () {
// Set the defaults // Set the defaults
exports.configure(); exports.setDefaults({});
}); });
// Only enable WP8 by default // Only enable WP8 by default
@ -42,19 +42,18 @@ channel.onCordovaReady.subscribe(function () {
/** /**
* List of all available options with their default value. * @private
* *
* @return {Object} * Default values of all available options.
*/ */
exports.getDefaults = function () { exports._defaults = {
return { title: 'App is running in background',
title: 'App is running in background', text: 'Doing heavy tasks.',
text: 'Doing heavy tasks.', ticker: 'App is running in background',
ticker: 'App is running in background', resume: true
resume: true
};
}; };
/** /**
* Activates the background mode. When activated the application * Activates the background mode. When activated the application
* will be prevented from going to sleep while in background * will be prevented from going to sleep while in background
@ -72,6 +71,35 @@ exports.disable = function () {
cordova.exec(null, null, 'BackgroundMode', 'disable', []); cordova.exec(null, null, 'BackgroundMode', 'disable', []);
}; };
/**
* List of all available options with their default value.
*
* @return {Object}
*/
exports.getDefaults = function () {
return this._defaults;
};
/**
* Overwrite default settings
*
* @param {Object} overrides
* Dict of options which shall be overridden
*/
exports.setDefaults = function (overrides) {
var defaults = this.getDefaults();
for (var key in defaults) {
if (overrides.hasOwnProperty(key)) {
defaults[key] = overrides[key];
}
}
if (device.platform == 'Android') {
cordova.exec(null, null, 'BackgroundMode', 'configure', [defaults, false]);
}
};
/** /**
* Configures the notification settings for Android. * Configures the notification settings for Android.
* Will be merged with the defaults. * Will be merged with the defaults.
@ -80,10 +108,10 @@ exports.disable = function () {
* Dict with key/value pairs * Dict with key/value pairs
*/ */
exports.configure = function (options) { exports.configure = function (options) {
var settings = this.mergeWithDefaults(options || {}); var settings = this.mergeWithDefaults(options);
if (device.platform == 'Android') { if (device.platform == 'Android') {
cordova.exec(null, null, 'BackgroundMode', 'configure', [settings]); cordova.exec(null, null, 'BackgroundMode', 'configure', [settings, true]);
} }
}; };