Detect screen status

This commit is contained in:
Sebastián Katzer 2017-02-06 15:59:57 +01:00
parent 8064b8853f
commit 131df973fb
5 changed files with 133 additions and 55 deletions

View File

@ -1,4 +1,7 @@
## ChangeLog ## ChangeLog
#### Version 0.7.3 (not yet released)
- Check if screen is off on Android
#### Version 0.7.2 (02.02.2017) #### Version 0.7.2 (02.02.2017)
- Fixed app freeze on iOS using wkwebview-engine - Fixed app freeze on iOS using wkwebview-engine
- Websocket sample in SampleApp - Websocket sample in SampleApp

View File

@ -47,7 +47,7 @@ Or install from local source:
## Usage ## Usage
The plugin creates the object `cordova.plugins.backgroundMode` and is accessible after the *deviceready* event has been fired. The plugin creates the object `cordova.plugins.backgroundMode` and is accessible after the *deviceready* event has been fired.
```javascript ```js
document.addEventListener('deviceready', function () { document.addEventListener('deviceready', function () {
// cordova.plugins.backgroundMode is now available // cordova.plugins.backgroundMode is now available
}, false); }, false);
@ -56,14 +56,14 @@ document.addEventListener('deviceready', function () {
### Enable the background mode ### Enable the background mode
The plugin is not enabled by default. Once it has been enabled the mode becomes active if the app moves to background. The plugin is not enabled by default. Once it has been enabled the mode becomes active if the app moves to background.
```javascript ```js
cordova.plugins.backgroundMode.enable(); cordova.plugins.backgroundMode.enable();
// or // or
cordova.plugins.backgroundMode.setEnabled(true); cordova.plugins.backgroundMode.setEnabled(true);
``` ```
To disable the background mode: To disable the background mode:
```javascript ```js
cordova.plugins.backgroundMode.disable(); cordova.plugins.backgroundMode.disable();
// or // or
cordova.plugins.backgroundMode.setEnabled(false); cordova.plugins.backgroundMode.setEnabled(false);
@ -72,7 +72,7 @@ cordova.plugins.backgroundMode.setEnabled(false);
### Check if running in background ### Check if running in background
Once the plugin has been enabled and the app has entered the background, the background mode becomes active. Once the plugin has been enabled and the app has entered the background, the background mode becomes active.
```javascript ```js
cordova.plugins.backgroundMode.isActive(); // => boolean cordova.plugins.backgroundMode.isActive(); // => boolean
``` ```
@ -81,12 +81,12 @@ A non-active mode means that the app is in foreground.
### Listen for events ### Listen for events
The plugin fires an event each time its status has been changed. These events are `enable`, `disable`, `activate`, `deactivate` and `failure`. The plugin fires an event each time its status has been changed. These events are `enable`, `disable`, `activate`, `deactivate` and `failure`.
```javascript ```js
cordova.plugins.backgroundMode.on('EVENT', function); cordova.plugins.backgroundMode.on('EVENT', function);
``` ```
To remove an event listeners: To remove an event listeners:
```javascript ```js
cordova.plugins.backgroundMode.un('EVENT', function); cordova.plugins.backgroundMode.un('EVENT', function);
``` ```
@ -96,7 +96,7 @@ cordova.plugins.backgroundMode.un('EVENT', function);
### Transit between application states ### Transit between application states
Android allows to programmatically move from foreground to background or vice versa. Android allows to programmatically move from foreground to background or vice versa.
```javascript ```js
cordova.plugins.backgroundMode.moveToBackground(); cordova.plugins.backgroundMode.moveToBackground();
// or // or
cordova.plugins.backgroundMode.moveToForeground(); cordova.plugins.backgroundMode.moveToForeground();
@ -105,24 +105,33 @@ cordova.plugins.backgroundMode.moveToForeground();
### Back button ### Back button
Override the back button on Android to go to background instead of closing the app. Override the back button on Android to go to background instead of closing the app.
```javascript ```js
cordova.plugins.backgroundMode.overrideBackButton(); cordova.plugins.backgroundMode.overrideBackButton();
``` ```
### Recent task list ### Recent task list
Exclude the app from the recent task list works on Android 5.0+. Exclude the app from the recent task list works on Android 5.0+.
```javascript ```js
cordova.plugins.backgroundMode.excludeFromTaskList(); cordova.plugins.backgroundMode.excludeFromTaskList();
``` ```
### Detect screen status
The method works async instead of _isAcive()_ or _isEnabled()_.
```js
cordova.plugins.backgroundMode.isScreenOff(function(bool) {
...
});
```
### Notification ### Notification
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 #### Override defaults
The title, text and icon for that notification can be customized as below. Also, by default the app will come to foreground when tapping on the notification. That can be changed by setting resume to false. On Android 5.0+, the color option will set the background color of the notification circle. Also on Android 5.0+, setting hidden to false will make the notification visible on lockscreen. The title, text and icon for that notification can be customized as below. Also, by default the app will come to foreground when tapping on the notification. That can be changed by setting resume to false. On Android 5.0+, the color option will set the background color of the notification circle. Also on Android 5.0+, setting hidden to false will make the notification visible on lockscreen.
```javascript ```js
cordova.plugins.backgroundMode.setDefaults({ cordova.plugins.backgroundMode.setDefaults({
title: String, title: String,
text: String, text: String,
@ -135,7 +144,7 @@ cordova.plugins.backgroundMode.setDefaults({
``` ```
To modify the currently displayed notification To modify the currently displayed notification
```javascript ```js
cordova.plugins.backgroundMode.configure({ ... }); cordova.plugins.backgroundMode.configure({ ... });
``` ```
@ -144,7 +153,7 @@ __Note:__ All properties are optional - only override the things you need to.
#### Run in background without notification #### Run in background without notification
In silent mode the plugin will not display a notification - which is not the default. Be aware that Android recommends adding a notification otherwise the OS may pause the app. In silent mode the plugin will not display a notification - which is not the default. Be aware that Android recommends adding a notification otherwise the OS may pause the app.
```javascript ```js
cordova.plugins.backgroundMode.configure({ silent: true }); cordova.plugins.backgroundMode.configure({ silent: true });
``` ```
@ -153,7 +162,7 @@ cordova.plugins.backgroundMode.configure({ silent: true });
Various APIs like playing media or tracking GPS position in background might not work while in background even the background mode is active. To fix such issues the plugin provides a method to disable most optimizations done by Android/CrossWalk. Various APIs like playing media or tracking GPS position in background might not work while in background even the background mode is active. To fix such issues the plugin provides a method to disable most optimizations done by Android/CrossWalk.
```javascript ```js
cordova.plugins.backgroundMode.on('activate', function() { cordova.plugins.backgroundMode.on('activate', function() {
cordova.plugins.backgroundMode.disableWebViewOptimizations(); cordova.plugins.backgroundMode.disableWebViewOptimizations();
}); });

View File

@ -25,18 +25,24 @@ import android.annotation.TargetApi;
import android.app.Activity; import android.app.Activity;
import android.app.ActivityManager; import android.app.ActivityManager;
import android.app.ActivityManager.AppTask; import android.app.ActivityManager.AppTask;
import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Build; import android.os.Build;
import android.os.PowerManager;
import android.view.View; import android.view.View;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView; import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.List; import java.util.List;
import static android.content.Context.ACTIVITY_SERVICE;
import static android.content.Context.POWER_SERVICE;
class BackgroundExt { class BackgroundExt {
// Weak reference to the cordova interface passed by the plugin // Weak reference to the cordova interface passed by the plugin
@ -48,40 +54,62 @@ class BackgroundExt {
/** /**
* Initialize the extension to perform non-background related tasks. * Initialize the extension to perform non-background related tasks.
* *
* @param cordova The cordova interface. * @param plugin The cordova plugin.
* @param webView The cordova web view.
*/ */
private BackgroundExt(CordovaInterface cordova, CordovaWebView webView) { private BackgroundExt(CordovaPlugin plugin) {
this.cordova = new WeakReference<CordovaInterface>(cordova); this.cordova = new WeakReference<CordovaInterface>(plugin.cordova);
this.webView = new WeakReference<CordovaWebView>(webView); this.webView = new WeakReference<CordovaWebView>(plugin.webView);
}
/**
* Executes the request asynchronous.
*
* @param plugin The cordova plugin.
* @param action The action to execute.
* @param callback The callback context used when
* calling back into JavaScript.
*/
@SuppressWarnings("UnusedParameters")
static void execute (CordovaPlugin plugin, final String action,
final CallbackContext callback) {
final BackgroundExt ext = new BackgroundExt(plugin);
plugin.cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
ext.execute(action, callback);
}
});
} }
/** /**
* Executes the request. * Executes the request.
* *
* @param action The action to execute. * @param action The action to execute.
* @param cordova The cordova interface. * @param callback The callback context used when
* @param webView The cordova web view. * calling back into JavaScript.
*/ */
static void execute(String action, CordovaInterface cordova, private void execute (String action, CallbackContext callback) {
CordovaWebView webView) {
BackgroundExt ext = new BackgroundExt(cordova, webView);
if (action.equalsIgnoreCase("optimizations")) { if (action.equalsIgnoreCase("optimizations")) {
ext.disableWebViewOptimizations(); disableWebViewOptimizations();
} }
if (action.equalsIgnoreCase("background")) { if (action.equalsIgnoreCase("background")) {
ext.moveToBackground(); moveToBackground();
} }
if (action.equalsIgnoreCase("foreground")) { if (action.equalsIgnoreCase("foreground")) {
ext.moveToForeground(); moveToForeground();
} }
if (action.equalsIgnoreCase("tasklist")) { if (action.equalsIgnoreCase("tasklist")) {
ext.excludeFromTaskList(); excludeFromTaskList();
}
if (action.equalsIgnoreCase("dimmed")) {
isDimmed(callback);
} }
} }
@ -148,8 +176,7 @@ class BackgroundExt {
*/ */
@TargetApi(Build.VERSION_CODES.LOLLIPOP) @TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void excludeFromTaskList() { private void excludeFromTaskList() {
ActivityManager am = (ActivityManager) getActivity() ActivityManager am = (ActivityManager) getService(ACTIVITY_SERVICE);
.getSystemService(Context.ACTIVITY_SERVICE);
if (am == null || Build.VERSION.SDK_INT < 21) if (am == null || Build.VERSION.SDK_INT < 21)
return; return;
@ -162,6 +189,26 @@ class BackgroundExt {
tasks.get(0).setExcludeFromRecents(true); tasks.get(0).setExcludeFromRecents(true);
} }
/**
* Invoke the callback with information if the screen is on.
*
* @param callback The callback to invoke.
*/
@SuppressWarnings("deprecation")
private void isDimmed (CallbackContext callback) {
PowerManager pm = (PowerManager) getService(POWER_SERVICE);
boolean isDimmed;
if (Build.VERSION.SDK_INT < 20) {
isDimmed = !pm.isScreenOn();
} else {
isDimmed = !pm.isInteractive();
}
PluginResult result = new PluginResult(Status.OK, isDimmed);
callback.sendPluginResult(result);
}
/** /**
* The activity referenced by cordova. * The activity referenced by cordova.
* *
@ -171,4 +218,15 @@ class BackgroundExt {
return cordova.get().getActivity(); return cordova.get().getActivity();
} }
/**
* Get the requested system service by name.
*
* @param name The name of the service.
*
* @return The service instance.
*/
private Object getService (String name) {
return getActivity().getSystemService(name);
}
} }

View File

@ -23,7 +23,6 @@ package de.appplant.cordova.plugin.background;
import android.app.Activity; import android.app.Activity;
import android.content.ComponentName; import android.content.ComponentName;
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;
@ -34,6 +33,8 @@ import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import static android.content.Context.BIND_AUTO_CREATE;
public class BackgroundMode extends CordovaPlugin { public class BackgroundMode extends CordovaPlugin {
// Event types for callbacks // Event types for callbacks
@ -93,25 +94,24 @@ public class BackgroundMode extends CordovaPlugin {
CallbackContext callback) throws JSONException { CallbackContext callback) throws JSONException {
if (action.equalsIgnoreCase("configure")) { if (action.equalsIgnoreCase("configure")) {
JSONObject settings = args.getJSONObject(0); configure(args.getJSONObject(0), args.getBoolean(1));
boolean update = args.getBoolean(1); callback.success();
return true;
configure(settings, update);
} }
else
if (action.equalsIgnoreCase("enable")) { if (action.equalsIgnoreCase("enable")) {
enableMode(); enableMode();
callback.success();
return true;
} }
else
if (action.equalsIgnoreCase("disable")) { if (action.equalsIgnoreCase("disable")) {
disableMode(); disableMode();
} callback.success();
else { return true;
BackgroundExt.execute(action, cordova, webView);
} }
callback.success(); BackgroundExt.execute(this, action, callback);
return true; return true;
} }
@ -221,15 +221,11 @@ public class BackgroundMode extends CordovaPlugin {
if (isDisabled || isBind) if (isDisabled || isBind)
return; return;
Intent intent = new Intent( Intent intent = new Intent(context, ForegroundService.class);
context, ForegroundService.class);
try { try {
context.bindService(intent, context.bindService(intent, connection, BIND_AUTO_CREATE);
connection, Context.BIND_AUTO_CREATE);
fireEvent(Event.ACTIVATE, null); fireEvent(Event.ACTIVATE, null);
context.startService(intent); context.startService(intent);
} catch (Exception e) { } catch (Exception e) {
fireEvent(Event.FAILURE, String.format("'%s'", e.getMessage())); fireEvent(Event.FAILURE, String.format("'%s'", e.getMessage()));
@ -244,15 +240,12 @@ public class BackgroundMode extends CordovaPlugin {
*/ */
private void stopService() { private void stopService() {
Activity context = cordova.getActivity(); Activity context = cordova.getActivity();
Intent intent = new Intent(context, ForegroundService.class);
Intent intent = new Intent(
context, ForegroundService.class);
if (!isBind) if (!isBind)
return; return;
fireEvent(Event.DEACTIVATE, null); fireEvent(Event.DEACTIVATE, null);
context.unbindService(connection); context.unbindService(connection);
context.stopService(intent); context.stopService(intent);

View File

@ -181,6 +181,21 @@ exports.overrideBackButton = function () {
}, false); }, false);
}; };
/**
* If the screen is off.
*
* @param [ Function ] fn Callback function to invoke with boolean arg.
*
* @return [ Void ]
*/
exports.isScreenOff = function (fn) {
if (this._isAndroid) {
cordova.exec(fn, null, 'BackgroundMode', 'dimmed', []);
} else {
fn(undefined);
}
};
/** /**
* If the mode is enabled or disabled. * If the mode is enabled or disabled.
* *