TagSpaces is an offline, open source, document manager with tagging support
Fixing audio playback issues on Android - upgrading cordova plugins - removing cordova media plugin - adding and enabling cordova background-mode plugin
Ilian Sapundshievcb10c165cc09
diff --git a/app/services/cordova-io.js b/app/services/cordova-io.jsindex e655ecfaa..ffb84ee35 100644--- a/app/services/cordova-io.js+++ b/app/services/cordova-io.js@@ -49,6 +49,11 @@ export default class CordovaIO {// attachFastClick(document.body);this.getFileSystem();+ // enabling the cordova-plugin-background-mode+ if (window.plugins.backgroundMode) {+ window.plugins.backgroundMode.enable();+ }+// iOS specific initializationif (AppConfig.isCordovaiOS) {window.plugins = window.plugins || {};diff --git a/cordova/config.xml b/cordova/config.xmlindex b92010613..2aceddd4d 100644--- a/cordova/config.xml+++ b/cordova/config.xml@@ -22,13 +22,15 @@<allow-intent href="itms:*" /><allow-intent href="itms-apps:*" /></platform>- <plugin name="cordova-plugin-file" spec="^6.0.1" /><preference name="AndroidPersistentFileLocation" value="Compatibility" /><preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" /><preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" /><plugin name="cordova-plugin-device" spec="^2.0.2" /><plugin name="cordova-plugin-whitelist" spec="^1.3.3" />- <plugin name="cordova-plugin-camera" spec="~4.0.3" />- <plugin name="cordova-plugin-media" spec="^5.0.2" />+ <plugin name="cordova-plugin-background-mode" spec="^0.7.3" />+ <plugin name="cordova-plugin-camera" spec="4.1.0">+ <variable name="ANDROID_SUPPORT_V4_VERSION" value="27.+" />+ </plugin>+ <plugin name="cordova-plugin-file" spec="6.0.2" /><engine name="android" spec="^7.1.4" /></widget>diff --git a/cordova/package.json b/cordova/package.jsonindex 52e27a1f8..9f8d5b2e4 100644--- a/cordova/package.json+++ b/cordova/package.json@@ -11,19 +11,21 @@"license": "Apache-2.0","dependencies": {"cordova-android": "^7.1.4",- "cordova-plugin-camera": "^4.0.3",- "cordova-plugin-device": "^2.0.2",- "cordova-plugin-file": "^6.0.1",- "cordova-plugin-media": "^5.0.2",- "cordova-plugin-whitelist": "^1.3.3"+ "cordova-plugin-background-mode": "^0.7.3",+ "cordova-plugin-camera": "4.1.0",+ "cordova-plugin-device": "^2.0.3",+ "cordova-plugin-file": "6.0.2",+ "cordova-plugin-whitelist": "^1.3.4"},"cordova": {"plugins": {"cordova-plugin-whitelist": {},- "cordova-plugin-file": {},"cordova-plugin-device": {},- "cordova-plugin-media": {},- "cordova-plugin-camera": {}+ "cordova-plugin-background-mode": {},+ "cordova-plugin-camera": {+ "ANDROID_SUPPORT_V4_VERSION": "27.+"+ },+ "cordova-plugin-file": {}},"platforms": ["android"diff --git a/cordova/platforms/android/android.json b/cordova/platforms/android/android.jsonindex af50ce707..368e5cd78 100644--- a/cordova/platforms/android/android.json+++ b/cordova/platforms/android/android.json@@ -9,23 +9,31 @@"parents": {"/*": [{- "xml": "<feature name=\"Camera\"><param name=\"android-package\" value=\"org.apache.cordova.camera.CameraLauncher\" /></feature>",+ "xml": "<feature name=\"Device\"><param name=\"android-package\" value=\"org.apache.cordova.device.Device\" /></feature>","count": 1},{- "xml": "<feature name=\"Device\"><param name=\"android-package\" value=\"org.apache.cordova.device.Device\" /></feature>",+ "xml": "<feature name=\"BackgroundMode\"><param name=\"android-package\" value=\"de.appplant.cordova.plugin.background.BackgroundMode\" /></feature>","count": 1},{- "xml": "<feature name=\"File\"><param name=\"android-package\" value=\"org.apache.cordova.file.FileUtils\" /><param name=\"onload\" value=\"true\" /></feature>",+ "xml": "<feature name=\"BackgroundModeExt\"><param name=\"android-package\" value=\"de.appplant.cordova.plugin.background.BackgroundModeExt\" /></feature>","count": 1},{- "xml": "<allow-navigation href=\"cdvfile:*\" />",+ "xml": "<preference name=\"KeepRunning\" value=\"true\" />",+ "count": 1+ },+ {+ "xml": "<feature name=\"Camera\"><param name=\"android-package\" value=\"org.apache.cordova.camera.CameraLauncher\" /></feature>",+ "count": 1+ },+ {+ "xml": "<feature name=\"File\"><param name=\"android-package\" value=\"org.apache.cordova.file.FileUtils\" /><param name=\"onload\" value=\"true\" /></feature>","count": 1},{- "xml": "<feature name=\"Media\"><param name=\"android-package\" value=\"org.apache.cordova.media.AudioHandler\" /></feature>",+ "xml": "<allow-navigation href=\"cdvfile:*\" />","count": 1},{@@ -37,22 +45,22 @@},"AndroidManifest.xml": {"parents": {- "/*": [+ "/manifest/application": [{- "xml": "<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />",- "count": 3- },- {- "xml": "<uses-permission android:name=\"android.permission.RECORD_AUDIO\" />",+ "xml": "<service android:name=\"de.appplant.cordova.plugin.background.ForegroundService\" />","count": 1- },+ }+ ],+ "/manifest": [{- "xml": "<uses-permission android:name=\"android.permission.MODIFY_AUDIO_SETTINGS\" />",+ "xml": "<uses-permission android:name=\"android.permission.WAKE_LOCK\" />","count": 1- },+ }+ ],+ "/*": [{- "xml": "<uses-permission android:name=\"android.permission.READ_PHONE_STATE\" />",- "count": 1+ "xml": "<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />",+ "count": 2}],"application": [@@ -66,16 +74,17 @@}},"installed_plugins": {- "cordova-plugin-camera": {+ "cordova-plugin-device": {"PACKAGE_NAME": "org.tagspaces.mobile"},- "cordova-plugin-device": {+ "cordova-plugin-background-mode": {"PACKAGE_NAME": "org.tagspaces.mobile"},- "cordova-plugin-file": {+ "cordova-plugin-camera": {+ "ANDROID_SUPPORT_V4_VERSION": "27.+","PACKAGE_NAME": "org.tagspaces.mobile"},- "cordova-plugin-media": {+ "cordova-plugin-file": {"PACKAGE_NAME": "org.tagspaces.mobile"},"cordova-plugin-whitelist": {@@ -84,6 +93,23 @@},"dependent_plugins": {},"modules": [+ {+ "id": "cordova-plugin-device.device",+ "file": "plugins/cordova-plugin-device/www/device.js",+ "pluginId": "cordova-plugin-device",+ "clobbers": [+ "device"+ ]+ },+ {+ "id": "cordova-plugin-background-mode.BackgroundMode",+ "file": "plugins/cordova-plugin-background-mode/www/background-mode.js",+ "pluginId": "cordova-plugin-background-mode",+ "clobbers": [+ "cordova.plugins.backgroundMode",+ "plugin.backgroundMode"+ ]+ },{"id": "cordova-plugin-camera.Camera","file": "plugins/cordova-plugin-camera/www/CameraConstants.js",@@ -116,14 +142,6 @@"CameraPopoverHandle"]},- {- "id": "cordova-plugin-device.device",- "file": "plugins/cordova-plugin-device/www/device.js",- "pluginId": "cordova-plugin-device",- "clobbers": [- "device"- ]- },{"id": "cordova-plugin-file.DirectoryEntry","file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",@@ -296,29 +314,13 @@"cordova"],"runs": true- },- {- "id": "cordova-plugin-media.MediaError",- "file": "plugins/cordova-plugin-media/www/MediaError.js",- "pluginId": "cordova-plugin-media",- "clobbers": [- "window.MediaError"- ]- },- {- "id": "cordova-plugin-media.Media",- "file": "plugins/cordova-plugin-media/www/Media.js",- "pluginId": "cordova-plugin-media",- "clobbers": [- "window.Media"- ]}],"plugin_metadata": {- "cordova-plugin-camera": "4.0.3","cordova-plugin-device": "2.0.2",- "cordova-plugin-file": "6.0.1",- "cordova-plugin-media": "5.0.2",+ "cordova-plugin-background-mode": "0.7.3",+ "cordova-plugin-camera": "4.1.0",+ "cordova-plugin-file": "6.0.2","cordova-plugin-whitelist": "1.3.3"}}\ No newline at end of filediff --git a/cordova/platforms/android/app/build.gradle b/cordova/platforms/android/app/build.gradleindex a7cc3f4e1..e316cfc9c 100644--- a/cordova/platforms/android/app/build.gradle+++ b/cordova/platforms/android/app/build.gradle@@ -265,7 +265,7 @@ dependencies {implementation fileTree(dir: 'libs', include: '*.jar')// SUB-PROJECT DEPENDENCIES STARTimplementation(project(path: ":CordovaLib"))- compile "com.android.support:support-v4:24.1.1+"+ compile "com.android.support:support-v4:27.+"// SUB-PROJECT DEPENDENCIES END}diff --git a/cordova/platforms/android/app/src/main/AndroidManifest.xml b/cordova/platforms/android/app/src/main/AndroidManifest.xmlindex a8c9c5f81..7fdf93311 100644--- a/cordova/platforms/android/app/src/main/AndroidManifest.xml+++ b/cordova/platforms/android/app/src/main/AndroidManifest.xml@@ -9,13 +9,12 @@<category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity>+ <service android:name="de.appplant.cordova.plugin.background.ForegroundService" /><provider android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true" android:name="org.apache.cordova.camera.FileProvider"><meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/camera_provider_paths" /></provider></application><uses-sdk android:minSdkVersion="19" android:targetSdkVersion="27" />+ <uses-permission android:name="android.permission.WAKE_LOCK" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />- <uses-permission android:name="android.permission.RECORD_AUDIO" />- <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />- <uses-permission android:name="android.permission.READ_PHONE_STATE" /></manifest>diff --git a/cordova/platforms/android/app/src/main/java/de/appplant/cordova/plugin/background/BackgroundMode.java b/cordova/platforms/android/app/src/main/java/de/appplant/cordova/plugin/background/BackgroundMode.javanew file mode 100644index 000000000..3ccb5cd14--- /dev/null+++ b/cordova/platforms/android/app/src/main/java/de/appplant/cordova/plugin/background/BackgroundMode.java@@ -0,0 +1,297 @@+/*+ Copyright 2013 Sebastián Katzer++ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you 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.+ */++package de.appplant.cordova.plugin.background;++import android.app.Activity;+import android.content.ComponentName;+import android.content.Intent;+import android.content.ServiceConnection;+import android.os.IBinder;++import org.apache.cordova.CallbackContext;+import org.apache.cordova.CordovaPlugin;+import org.json.JSONArray;+import org.json.JSONObject;++import de.appplant.cordova.plugin.background.ForegroundService.ForegroundBinder;++import static android.content.Context.BIND_AUTO_CREATE;+import static de.appplant.cordova.plugin.background.BackgroundModeExt.clearKeyguardFlags;++public class BackgroundMode extends CordovaPlugin {++ // Event types for callbacks+ private enum Event { ACTIVATE, DEACTIVATE, FAILURE }++ // Plugin namespace+ private static final String JS_NAMESPACE = "cordova.plugins.backgroundMode";++ // Flag indicates if the app is in background or foreground+ private boolean inBackground = false;++ // Flag indicates if the plugin is enabled or disabled+ private boolean isDisabled = true;++ // Flag indicates if the service is bind+ private boolean isBind = false;++ // Default settings for the notification+ private static JSONObject defaultSettings = new JSONObject();++ // Service that keeps the app awake+ private ForegroundService service;++ // Used to (un)bind the service to with the activity+ private final ServiceConnection connection = new ServiceConnection()+ {+ @Override+ public void onServiceConnected (ComponentName name, IBinder service)+ {+ ForegroundBinder binder = (ForegroundBinder) service;+ BackgroundMode.this.service = binder.getService();+ }++ @Override+ public void onServiceDisconnected (ComponentName name)+ {+ fireEvent(Event.FAILURE, "'service disconnected'");+ }+ };++ /**+ * Executes the request.+ *+ * @param action The action to execute.+ * @param args The exec() arguments.+ * @param callback The callback context used when+ * calling back into JavaScript.+ *+ * @return Returning false results in a "MethodNotFound" error.+ */+ @Override+ public boolean execute (String action, JSONArray args,+ CallbackContext callback)+ {+ boolean validAction = true;++ switch (action)+ {+ case "configure":+ configure(args.optJSONObject(0), args.optBoolean(1));+ break;+ case "enable":+ enableMode();+ break;+ case "disable":+ disableMode();+ break;+ default:+ validAction = false;+ }++ if (validAction) {+ callback.success();+ } else {+ callback.error("Invalid action: " + action);+ }++ return validAction;+ }++ /**+ * Called when the system is about to start resuming a previous activity.+ *+ * @param multitasking Flag indicating if multitasking is turned on for app.+ */+ @Override+ public void onPause(boolean multitasking)+ {+ try {+ inBackground = true;+ startService();+ } finally {+ clearKeyguardFlags(cordova.getActivity());+ }+ }++ /**+ * Called when the activity is no longer visible to the user.+ */+ @Override+ public void onStop () {+ clearKeyguardFlags(cordova.getActivity());+ }++ /**+ * Called when the activity will start interacting with the user.+ *+ * @param multitasking Flag indicating if multitasking is turned on for app.+ */+ @Override+ public void onResume (boolean multitasking)+ {+ inBackground = false;+ stopService();+ }++ /**+ * Called when the activity will be destroyed.+ */+ @Override+ public void onDestroy()+ {+ stopService();+ android.os.Process.killProcess(android.os.Process.myPid());+ }++ /**+ * Enable the background mode.+ */+ private void enableMode()+ {+ isDisabled = false;++ if (inBackground) {+ startService();+ }+ }++ /**+ * Disable the background mode.+ */+ private void disableMode()+ {+ stopService();+ isDisabled = true;+ }++ /**+ * Update the default settings and configure the notification.+ *+ * @param settings The settings+ * @param update A truthy value means to update the running service.+ */+ private void configure(JSONObject settings, boolean update)+ {+ if (update) {+ updateNotification(settings);+ } else {+ setDefaultSettings(settings);+ }+ }++ /**+ * Update the default settings for the notification.+ *+ * @param settings The new default settings+ */+ private void setDefaultSettings(JSONObject settings)+ {+ defaultSettings = settings;+ }++ /**+ * Returns the settings for the new/updated notification.+ */+ static JSONObject getSettings () {+ return defaultSettings;+ }++ /**+ * Update the notification.+ *+ * @param settings The config settings+ */+ private void updateNotification(JSONObject settings)+ {+ if (isBind) {+ service.updateNotification(settings);+ }+ }++ /**+ * Bind the activity to a background service and put them into foreground+ * state.+ */+ private void startService()+ {+ Activity context = cordova.getActivity();++ if (isDisabled || isBind)+ return;++ Intent intent = new Intent(context, ForegroundService.class);++ try {+ context.bindService(intent, connection, BIND_AUTO_CREATE);+ fireEvent(Event.ACTIVATE, null);+ context.startService(intent);+ } catch (Exception e) {+ fireEvent(Event.FAILURE, String.format("'%s'", e.getMessage()));+ }++ isBind = true;+ }++ /**+ * Bind the activity to a background service and put them into foreground+ * state.+ */+ private void stopService()+ {+ Activity context = cordova.getActivity();+ Intent intent = new Intent(context, ForegroundService.class);++ if (!isBind) return;++ fireEvent(Event.DEACTIVATE, null);+ context.unbindService(connection);+ context.stopService(intent);++ isBind = false;+ }++ /**+ * Fire vent with some parameters inside the web view.+ *+ * @param event The name of the event+ * @param params Optional arguments for the event+ */+ private void fireEvent (Event event, String params)+ {+ String eventName = event.name().toLowerCase();+ Boolean active = event == Event.ACTIVATE;++ String str = String.format("%s._setActive(%b)",+ JS_NAMESPACE, active);++ str = String.format("%s;%s.on('%s', %s)",+ str, JS_NAMESPACE, eventName, params);++ str = String.format("%s;%s.fireEvent('%s',%s);",+ str, JS_NAMESPACE, eventName, params);++ final String js = str;++ cordova.getActivity().runOnUiThread(() -> webView.loadUrl("javascript:" + js));+ }+}diff --git a/cordova/platforms/android/app/src/main/java/de/appplant/cordova/plugin/background/BackgroundModeExt.java b/cordova/platforms/android/app/src/main/java/de/appplant/cordova/plugin/background/BackgroundModeExt.javanew file mode 100644index 000000000..ed7659849--- /dev/null+++ b/cordova/platforms/android/app/src/main/java/de/appplant/cordova/plugin/background/BackgroundModeExt.java@@ -0,0 +1,445 @@+/*+ Copyright 2013 Sebastián Katzer++ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you 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.+ */++package de.appplant.cordova.plugin.background;++import android.annotation.SuppressLint;+import android.annotation.TargetApi;+import android.app.Activity;+import android.app.ActivityManager;+import android.app.ActivityManager.AppTask;+import android.app.AlertDialog;+import android.content.ComponentName;+import android.content.Context;+import android.content.Intent;+import android.content.pm.PackageManager;+import android.net.Uri;+import android.os.Build;+import android.os.PowerManager;+import android.view.View;++import org.apache.cordova.CallbackContext;+import org.apache.cordova.CordovaPlugin;+import org.apache.cordova.PluginResult;+import org.apache.cordova.PluginResult.Status;+import org.json.JSONArray;+import org.json.JSONObject;++import java.util.Arrays;+import java.util.List;++import static android.R.string.cancel;+import static android.R.string.ok;+import static android.R.style.Theme_DeviceDefault_Light_Dialog;+import static android.content.Context.ACTIVITY_SERVICE;+import static android.content.Context.POWER_SERVICE;+import static android.content.pm.PackageManager.MATCH_DEFAULT_ONLY;+import static android.os.Build.VERSION.SDK_INT;+import static android.os.Build.VERSION_CODES.M;+import static android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS;+import static android.view.WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON;+import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;+import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;+import static android.view.WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;++/**+ * Implements extended functions around the main purpose+ * of infinite execution in the background.+ */+public class BackgroundModeExt extends CordovaPlugin {++ // To keep the device awake+ private PowerManager.WakeLock wakeLock;++ /**+ * Executes the request.+ *+ * @param action The action to execute.+ * @param args The exec() arguments.+ * @param callback The callback context used when+ * calling back into JavaScript.+ *+ * @return Returning false results in a "MethodNotFound" error.+ */+ @Override+ public boolean execute (String action, JSONArray args,+ CallbackContext callback)+ {+ boolean validAction = true;++ switch (action)+ {+ case "battery":+ disableBatteryOptimizations();+ break;+ case "webview":+ disableWebViewOptimizations();+ break;+ case "appstart":+ openAppStart(args.opt(0));+ break;+ case "background":+ moveToBackground();+ break;+ case "foreground":+ moveToForeground();+ break;+ case "tasklist":+ excludeFromTaskList();+ break;+ case "dimmed":+ isDimmed(callback);+ break;+ case "wakeup":+ wakeup();+ break;+ case "unlock":+ wakeup();+ unlock();+ break;+ default:+ validAction = false;+ }++ if (validAction) {+ callback.success();+ } else {+ callback.error("Invalid action: " + action);+ }++ return validAction;+ }++ /**+ * Moves the app to the background.+ */+ private void moveToBackground()+ {+ Intent intent = new Intent(Intent.ACTION_MAIN);++ intent.addCategory(Intent.CATEGORY_HOME);++ getApp().startActivity(intent);+ }++ /**+ * Moves the app to the foreground.+ */+ private void moveToForeground()+ {+ Activity app = getApp();+ Intent intent = getLaunchIntent();++ intent.addFlags(+ Intent.FLAG_ACTIVITY_REORDER_TO_FRONT |+ Intent.FLAG_ACTIVITY_SINGLE_TOP |+ Intent.FLAG_ACTIVITY_CLEAR_TOP);++ clearScreenAndKeyguardFlags();+ app.startActivity(intent);+ }++ /**+ * Enable GPS position tracking while in background.+ */+ private void disableWebViewOptimizations() {+ Thread thread = new Thread(){+ public void run() {+ try {+ Thread.sleep(1000);+ getApp().runOnUiThread(() -> {+ View view = webView.getEngine().getView();++ try {+ Class.forName("org.crosswalk.engine.XWalkCordovaView")+ .getMethod("onShow")+ .invoke(view);+ } catch (Exception e){+ view.dispatchWindowVisibilityChanged(View.VISIBLE);+ }+ });+ } catch (InterruptedException e) {+ // do nothing+ }+ }+ };++ thread.start();+ }++ /**+ * Disables battery optimizations for the app.+ * Requires permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS to function.+ */+ @SuppressLint("BatteryLife")+ private void disableBatteryOptimizations()+ {+ Activity activity = cordova.getActivity();+ Intent intent = new Intent();+ String pkgName = activity.getPackageName();+ PowerManager pm = (PowerManager)getService(POWER_SERVICE);++ if (SDK_INT < M)+ return;++ if (pm.isIgnoringBatteryOptimizations(pkgName))+ return;++ intent.setAction(ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);+ intent.setData(Uri.parse("package:" + pkgName));++ cordova.getActivity().startActivity(intent);+ }++ /**+ * Opens the system settings dialog where the user can tweak or turn off any+ * custom app start settings added by the manufacturer if available.+ *+ * @param arg Text and title for the dialog or false to skip the dialog.+ */+ private void openAppStart (Object arg)+ {+ Activity activity = cordova.getActivity();+ PackageManager pm = activity.getPackageManager();++ for (Intent intent : getAppStartIntents())+ {+ if (pm.resolveActivity(intent, MATCH_DEFAULT_ONLY) != null)+ {+ JSONObject spec = (arg instanceof JSONObject) ? (JSONObject) arg : null;++ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);++ if (arg instanceof Boolean && !((Boolean) arg))+ {+ activity.startActivity(intent);+ break;+ }++ AlertDialog.Builder dialog = new AlertDialog.Builder(activity, Theme_DeviceDefault_Light_Dialog);++ dialog.setPositiveButton(ok, (o, d) -> activity.startActivity(intent));+ dialog.setNegativeButton(cancel, (o, d) -> {});+ dialog.setCancelable(true);++ if (spec != null && spec.has("title"))+ {+ dialog.setTitle(spec.optString("title"));+ }++ if (spec != null && spec.has("text"))+ {+ dialog.setMessage(spec.optString("text"));+ }+ else+ {+ dialog.setMessage("missing text");+ }++ activity.runOnUiThread(dialog::show);++ break;+ }+ }+ }++ /**+ * Excludes the app from the recent tasks list.+ */+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)+ private void excludeFromTaskList()+ {+ ActivityManager am = (ActivityManager) getService(ACTIVITY_SERVICE);++ if (am == null || SDK_INT < 21)+ return;++ List<AppTask> tasks = am.getAppTasks();++ if (tasks == null || tasks.isEmpty())+ return;++ tasks.get(0).setExcludeFromRecents(true);+ }++ /**+ * Invokes the callback with information if the screen is on.+ *+ * @param callback The callback to invoke.+ */+ @SuppressWarnings("deprecation")+ private void isDimmed (CallbackContext callback)+ {+ boolean status = isDimmed();+ PluginResult res = new PluginResult(Status.OK, status);++ callback.sendPluginResult(res);+ }++ /**+ * Returns if the screen is active.+ */+ @SuppressWarnings("deprecation")+ private boolean isDimmed()+ {+ PowerManager pm = (PowerManager) getService(POWER_SERVICE);++ if (SDK_INT < 20)+ {+ return !pm.isScreenOn();+ }++ return !pm.isInteractive();+ }++ /**+ * Wakes up the device if the screen isn't still on.+ */+ private void wakeup()+ {+ try {+ acquireWakeLock();+ } catch (Exception e) {+ releaseWakeLock();+ }+ }++ /**+ * Unlocks the device even with password protection.+ */+ private void unlock()+ {+ addSreenAndKeyguardFlags();+ getApp().startActivity(getLaunchIntent());+ }++ /**+ * Acquires a wake lock to wake up the device.+ */+ @SuppressWarnings("deprecation")+ private void acquireWakeLock()+ {+ PowerManager pm = (PowerManager) getService(POWER_SERVICE);++ releaseWakeLock();++ if (!isDimmed())+ return;++ int level = PowerManager.SCREEN_DIM_WAKE_LOCK |+ PowerManager.ACQUIRE_CAUSES_WAKEUP;++ wakeLock = pm.newWakeLock(level, "backgroundmode:wakelock");+ wakeLock.setReferenceCounted(false);+ wakeLock.acquire(1000);+ }++ /**+ * Releases the previously acquire wake lock.+ */+ private void releaseWakeLock()+ {+ if (wakeLock != null && wakeLock.isHeld()) {+ wakeLock.release();+ wakeLock = null;+ }+ }++ /**+ * Adds required flags to the window to unlock/wakeup the device.+ */+ private void addSreenAndKeyguardFlags()+ {+ getApp().runOnUiThread(() -> getApp().getWindow().addFlags(FLAG_ALLOW_LOCK_WHILE_SCREEN_ON | FLAG_SHOW_WHEN_LOCKED | FLAG_TURN_SCREEN_ON | FLAG_DISMISS_KEYGUARD));+ }++ /**+ * Clears required flags to the window to unlock/wakeup the device.+ */+ private void clearScreenAndKeyguardFlags()+ {+ getApp().runOnUiThread(() -> getApp().getWindow().clearFlags(FLAG_ALLOW_LOCK_WHILE_SCREEN_ON | FLAG_SHOW_WHEN_LOCKED | FLAG_TURN_SCREEN_ON | FLAG_DISMISS_KEYGUARD));+ }++ /**+ * Removes required flags to the window to unlock/wakeup the device.+ */+ static void clearKeyguardFlags (Activity app)+ {+ app.runOnUiThread(() -> app.getWindow().clearFlags(FLAG_DISMISS_KEYGUARD));+ }++ /**+ * Returns the activity referenced by cordova.+ */+ Activity getApp() {+ return cordova.getActivity();+ }++ /**+ * Gets the launch intent for the main activity.+ */+ private Intent getLaunchIntent()+ {+ Context app = getApp().getApplicationContext();+ String pkgName = app.getPackageName();++ return app.getPackageManager().getLaunchIntentForPackage(pkgName);+ }++ /**+ * Get the requested system service by name.+ *+ * @param name The name of the service.+ */+ private Object getService(String name)+ {+ return getApp().getSystemService(name);+ }++ /**+ * Returns list of all possible intents to present the app start settings.+ */+ private List<Intent> getAppStartIntents()+ {+ return Arrays.asList(+ new Intent().setComponent(new ComponentName("com.miui.securitycenter","com.miui.permcenter.autostart.AutoStartManagementActivity")),+ new Intent().setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity")),+ new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity")),+ new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity")),+ new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity")),+ new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity")),+ new Intent().setComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity")),+ new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity")),+ new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager")),+ new Intent().setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity")),+ new Intent().setComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.autostart.AutoStartActivity")),+ new Intent().setComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.entry.FunctionActivity")).setData(android.net.Uri.parse("mobilemanager://function/entry/AutoStart")),+ new Intent().setAction("com.letv.android.permissionautoboot"),+ new Intent().setComponent(new ComponentName("com.samsung.android.sm_cn", "com.samsung.android.sm.ui.ram.AutoRunActivity")),+ new Intent().setComponent(ComponentName.unflattenFromString("com.iqoo.secure/.MainActivity")),+ new Intent().setComponent(ComponentName.unflattenFromString("com.meizu.safe/.permission.SmartBGActivity")),+ new Intent().setComponent(new ComponentName("com.yulong.android.coolsafe", ".ui.activity.autorun.AutoRunListActivity")),+ new Intent().setComponent(new ComponentName("cn.nubia.security2", "cn.nubia.security.appmanage.selfstart.ui.SelfStartActivity")),+ new Intent().setComponent(new ComponentName("com.zui.safecenter", "com.lenovo.safecenter.MainTab.LeSafeMainActivity"))+ );+ }+}diff --git a/cordova/platforms/android/app/src/main/java/de/appplant/cordova/plugin/background/ForegroundService.java b/cordova/platforms/android/app/src/main/java/de/appplant/cordova/plugin/background/ForegroundService.javanew file mode 100644index 000000000..806c9568b--- /dev/null+++ b/cordova/platforms/android/app/src/main/java/de/appplant/cordova/plugin/background/ForegroundService.java@@ -0,0 +1,323 @@+/*+ Copyright 2013 Sebastián Katzer++ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you 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.+ */++package de.appplant.cordova.plugin.background;++import android.annotation.SuppressLint;+import android.annotation.TargetApi;+import android.app.Notification;+import android.app.NotificationManager;+import android.app.PendingIntent;+import android.app.Service;+import android.content.Context;+import android.content.Intent;+import android.content.res.Resources;+import android.os.Binder;+import android.os.Build;+import android.os.IBinder;+import android.os.PowerManager;+import android.app.NotificationChannel;++import org.json.JSONObject;++import static android.os.PowerManager.PARTIAL_WAKE_LOCK;++/**+ * Puts the service in a foreground state, where the system considers it to be+ * something the user is actively aware of and thus not a candidate for killing+ * when low on memory.+ */+public class ForegroundService extends Service {++ // Fixed ID for the 'foreground' notification+ public static final int NOTIFICATION_ID = -574543954;++ // Default title of the background notification+ private static final String NOTIFICATION_TITLE =+ "App is running in background";++ // Default text of the background notification+ private static final String NOTIFICATION_TEXT =+ "Doing heavy tasks.";++ // Default icon of the background notification+ private static final String NOTIFICATION_ICON = "icon";++ // Binder given to clients+ private final IBinder binder = new ForegroundBinder();++ // Partial wake lock to prevent the app from going to sleep when locked+ private PowerManager.WakeLock wakeLock;++ /**+ * Allow clients to call on to the service.+ */+ @Override+ public IBinder onBind (Intent intent) {+ return binder;+ }++ /**+ * Class used for the client Binder. Because we know this service always+ * runs in the same process as its clients, we don't need to deal with IPC.+ */+ class ForegroundBinder extends Binder+ {+ ForegroundService getService()+ {+ // Return this instance of ForegroundService+ // so clients can call public methods+ return ForegroundService.this;+ }+ }++ /**+ * Put the service in a foreground state to prevent app from being killed+ * by the OS.+ */+ @Override+ public void onCreate()+ {+ super.onCreate();+ keepAwake();+ }++ /**+ * No need to run headless on destroy.+ */+ @Override+ public void onDestroy()+ {+ super.onDestroy();+ sleepWell();+ }++ /**+ * Prevent Android from stopping the background service automatically.+ */+ @Override+ public int onStartCommand (Intent intent, int flags, int startId) {+ return START_STICKY;+ }++ /**+ * Put the service in a foreground state to prevent app from being killed+ * by the OS.+ */+ @SuppressLint("WakelockTimeout")+ private void keepAwake()+ {+ JSONObject settings = BackgroundMode.getSettings();+ boolean isSilent = settings.optBoolean("silent", false);++ if (!isSilent) {+ startForeground(NOTIFICATION_ID, makeNotification());+ }++ PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);++ wakeLock = pm.newWakeLock(+ PARTIAL_WAKE_LOCK, "backgroundmode:wakelock");++ wakeLock.acquire();+ }++ /**+ * Stop background mode.+ */+ private void sleepWell()+ {+ stopForeground(true);+ getNotificationManager().cancel(NOTIFICATION_ID);++ if (wakeLock != null) {+ wakeLock.release();+ wakeLock = null;+ }+ }++ /**+ * Create a notification as the visible part to be able to put the service+ * in a foreground state by using the default settings.+ */+ private Notification makeNotification()+ {+ return makeNotification(BackgroundMode.getSettings());+ }++ /**+ * Create a notification as the visible part to be able to put the service+ * in a foreground state.+ *+ * @param settings The config settings+ */+ private Notification makeNotification (JSONObject settings)+ {+ // use channelid for Oreo and higher+ String CHANNEL_ID = "cordova-plugin-background-mode-id";+ if(Build.VERSION.SDK_INT >= 26){+ // The user-visible name of the channel.+ CharSequence name = "cordova-plugin-background-mode";+ // The user-visible description of the channel.+ String description = "cordova-plugin-background-moden notification";++ int importance = NotificationManager.IMPORTANCE_LOW;++ NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name,importance);++ // Configure the notification channel.+ mChannel.setDescription(description);++ getNotificationManager().createNotificationChannel(mChannel);+ }+ String title = settings.optString("title", NOTIFICATION_TITLE);+ String text = settings.optString("text", NOTIFICATION_TEXT);+ boolean bigText = settings.optBoolean("bigText", false);++ Context context = getApplicationContext();+ String pkgName = context.getPackageName();+ Intent intent = context.getPackageManager()+ .getLaunchIntentForPackage(pkgName);++ Notification.Builder notification = new Notification.Builder(context)+ .setContentTitle(title)+ .setContentText(text)+ .setOngoing(true)+ .setSmallIcon(getIconResId(settings));++ if(Build.VERSION.SDK_INT >= 26){+ notification.setChannelId(CHANNEL_ID);+ }++ if (settings.optBoolean("hidden", true)) {+ notification.setPriority(Notification.PRIORITY_MIN);+ }++ if (bigText || text.contains("\n")) {+ notification.setStyle(+ new Notification.BigTextStyle().bigText(text));+ }++ setColor(notification, settings);++ if (intent != null && settings.optBoolean("resume")) {+ intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);+ PendingIntent contentIntent = PendingIntent.getActivity(+ context, NOTIFICATION_ID, intent,+ PendingIntent.FLAG_UPDATE_CURRENT);+++ notification.setContentIntent(contentIntent);+ }++ return notification.build();+ }++ /**+ * Update the notification.+ *+ * @param settings The config settings+ */+ protected void updateNotification (JSONObject settings)+ {+ boolean isSilent = settings.optBoolean("silent", false);++ if (isSilent) {+ stopForeground(true);+ return;+ }++ Notification notification = makeNotification(settings);+ getNotificationManager().notify(NOTIFICATION_ID, notification);++ }++ /**+ * Retrieves the resource ID of the app icon.+ *+ * @param settings A JSON dict containing the icon name.+ */+ private int getIconResId (JSONObject settings)+ {+ String icon = settings.optString("icon", NOTIFICATION_ICON);++ int resId = getIconResId(icon, "mipmap");++ if (resId == 0) {+ resId = getIconResId(icon, "drawable");+ }++ return resId;+ }++ /**+ * Retrieve resource id of the specified icon.+ *+ * @param icon The name of the icon.+ * @param type The resource type where to look for.+ *+ * @return The resource id or 0 if not found.+ */+ private int getIconResId (String icon, String type)+ {+ Resources res = getResources();+ String pkgName = getPackageName();++ int resId = res.getIdentifier(icon, type, pkgName);++ if (resId == 0) {+ resId = res.getIdentifier("icon", type, pkgName);+ }++ return resId;+ }++ /**+ * Set notification color if its supported by the SDK.+ *+ * @param notification A Notification.Builder instance+ * @param settings A JSON dict containing the color definition (red: FF0000)+ */+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)+ private void setColor (Notification.Builder notification, JSONObject settings)+ {++ String hex = settings.optString("color", null);++ if (Build.VERSION.SDK_INT < 21 || hex == null)+ return;++ try {+ int aRGB = Integer.parseInt(hex, 16) + 0xFF000000;+ notification.setColor(aRGB);+ } catch (Exception e) {+ e.printStackTrace();+ }+ }++ /**+ * Returns the shared notification service manager.+ */+ private NotificationManager getNotificationManager()+ {+ return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);+ }+}diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/camera/CameraLauncher.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/camera/CameraLauncher.javaindex fbe8470e4..2eef0fa57 100644--- a/cordova/platforms/android/app/src/main/java/org/apache/cordova/camera/CameraLauncher.java+++ b/cordova/platforms/android/app/src/main/java/org/apache/cordova/camera/CameraLauncher.java@@ -18,34 +18,13 @@*/package org.apache.cordova.camera;-import java.io.ByteArrayOutputStream;-import java.io.File;-import java.io.FileInputStream;-import java.io.FileNotFoundException;-import java.io.FileOutputStream;-import java.io.IOException;-import java.io.InputStream;-import java.io.OutputStream;-import java.text.SimpleDateFormat;-import java.util.Date;--import org.apache.cordova.BuildHelper;-import org.apache.cordova.CallbackContext;-import org.apache.cordova.CordovaPlugin;-import org.apache.cordova.CordovaResourceApi;-import org.apache.cordova.LOG;-import org.apache.cordova.PermissionHelper;-import org.apache.cordova.PluginResult;-import org.json.JSONArray;-import org.json.JSONException;-import android.Manifest;-import android.annotation.TargetApi;import android.app.Activity;import android.content.ActivityNotFoundException;import android.content.ContentValues;-import android.content.Context;import android.content.Intent;+import android.content.pm.PackageManager;+import android.content.pm.PackageManager.NameNotFoundException;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.Bitmap.CompressFormat;@@ -55,16 +34,31 @@ import android.media.ExifInterface;import android.media.MediaScannerConnection;import android.media.MediaScannerConnection.MediaScannerConnectionClient;import android.net.Uri;-import android.os.Build;import android.os.Bundle;import android.os.Environment;-import android.provider.DocumentsContract;import android.provider.MediaStore;-import android.provider.OpenableColumns;import android.support.v4.content.FileProvider;import android.util.Base64;-import android.content.pm.PackageManager;-import android.content.pm.PackageManager.NameNotFoundException;++import org.apache.cordova.BuildHelper;+import org.apache.cordova.CallbackContext;+import org.apache.cordova.CordovaPlugin;+import org.apache.cordova.LOG;+import org.apache.cordova.PermissionHelper;+import org.apache.cordova.PluginResult;+import org.json.JSONArray;+import org.json.JSONException;++import java.io.ByteArrayOutputStream;+import java.io.File;+import java.io.FileInputStream;+import java.io.FileNotFoundException;+import java.io.FileOutputStream;+import java.io.IOException;+import java.io.InputStream;+import java.io.OutputStream;+import java.text.SimpleDateFormat;+import java.util.Date;/*** This class launches the camera view, allows the user to take a picture, closes the camera view,@@ -87,9 +81,19 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnectprivate static final int JPEG = 0; // Take a picture of type JPEGprivate static final int PNG = 1; // Take a picture of type PNG+ private static final String JPEG_TYPE = "jpg";+ private static final String PNG_TYPE = "png";+ private static final String JPEG_EXTENSION = "." + JPEG_TYPE;+ private static final String PNG_EXTENSION = "." + PNG_TYPE;+ private static final String PNG_MIME_TYPE = "image/png";+ private static final String JPEG_MIME_TYPE = "image/jpeg";private static final String GET_PICTURE = "Get Picture";private static final String GET_VIDEO = "Get Video";private static final String GET_All = "Get All";+ private static final String CROPPED_URI_KEY = "croppedUri";+ private static final String IMAGE_URI_KEY = "imageUri";++ private static final String TAKE_PICTURE_ACTION = "takePicture";public static final int PERMISSION_DENIED_ERROR = 20;public static final int TAKE_PIC_SEC = 0;@@ -100,6 +104,8 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect//Where did this come from?private static final int CROP_CAMERA = 100;+ private static final String TIME_FORMAT = "yyyyMMdd_HHmmss";+private int mQuality; // Compression quality hint (0-100: 0=low quality & high compression, 100=compress of max quality)private int targetWidth; // desired width of the imageprivate int targetHeight; // desired height of the image@@ -141,7 +147,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnectthis.applicationId = preferences.getString("applicationId", this.applicationId);- if (action.equals("takePicture")) {+ if (action.equals(TAKE_PICTURE_ACTION)) {this.srcType = CAMERA;this.destType = FILE_URI;this.saveToPhotoAlbum = false;@@ -297,7 +303,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnectthis.imageUri = new CordovaUri(FileProvider.getUriForFile(cordova.getActivity(),applicationId + ".provider",photo));- intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri.getCorrectUri());+ intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri.getCorrectUri());//We can write to this URI, this will hopefully allow us to write files to get to the next stepintent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);@@ -306,7 +312,6 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnectPackageManager mPm = this.cordova.getActivity().getPackageManager();if(intent.resolveActivity(mPm) != null){-this.cordova.startActivityForResult((CordovaPlugin) this, intent, (CAMERA + 1) * 16 + returnType + 1);}else@@ -341,9 +346,9 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect}if (encodingType == JPEG) {- fileName = fileName + ".jpg";+ fileName = fileName + JPEG_EXTENSION;} else if (encodingType == PNG) {- fileName = fileName + ".png";+ fileName = fileName + PNG_EXTENSION;} else {throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType);}@@ -352,7 +357,6 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect}-/*** Get image from photo library.*@@ -383,7 +387,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect}File photo = createCaptureFile(JPEG);croppedUri = Uri.fromFile(photo);- intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, croppedUri);+ intent.putExtra(MediaStore.EXTRA_OUTPUT, croppedUri);} else {intent.setAction(Intent.ACTION_GET_CONTENT);intent.addCategory(Intent.CATEGORY_OPENABLE);@@ -599,8 +603,8 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect}private String getPicturesPath() {- String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());- String imageFileName = "IMG_" + timeStamp + (this.encodingType == JPEG ? ".jpg" : ".png");+ String timeStamp = new SimpleDateFormat(TIME_FORMAT).format(new Date());+ String imageFileName = "IMG_" + timeStamp + (this.encodingType == JPEG ? JPEG_EXTENSION : PNG_EXTENSION);File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);storageDir.mkdirs();@@ -621,8 +625,8 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect* @return String String value of mime type or empty string if mime type is not supported*/private String getMimetypeForFormat(int outputFormat) {- if (outputFormat == PNG) return "image/png";- if (outputFormat == JPEG) return "image/jpeg";+ if (outputFormat == PNG) return PNG_MIME_TYPE;+ if (outputFormat == JPEG) return JPEG_MIME_TYPE;return "";}@@ -634,9 +638,9 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect// Get filename from uriString fileName = realPath != null ?realPath.substring(realPath.lastIndexOf('/') + 1) :- "modified." + (this.encodingType == JPEG ? "jpg" : "png");+ "modified." + (this.encodingType == JPEG ? JPEG_TYPE : PNG_TYPE);- String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());+ String timeStamp = new SimpleDateFormat(TIME_FORMAT).format(new Date());//String fileName = "IMG_" + timeStamp + (this.encodingType == JPEG ? ".jpg" : ".png");String modifiedPath = getTempDirectoryPath() + "/" + fileName;@@ -683,32 +687,26 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnectint rotate = 0;String fileLocation = FileHelper.getRealPath(uri, this.cordova);- LOG.d(LOG_TAG, "File locaton is: " + fileLocation);+ LOG.d(LOG_TAG, "File location is: " + fileLocation);- // If you ask for video or all media type you will automatically get back a file URI- // and there will be no attempt to resize any returned data- if (this.mediaType != PICTURE) {+ String uriString = uri.toString();+ String mimeType = FileHelper.getMimeType(uriString, this.cordova);++ // If you ask for video or the selected file doesn't have JPEG or PNG mime type+ // there will be no attempt to resize any returned data+ if (this.mediaType == VIDEO || !(JPEG_MIME_TYPE.equalsIgnoreCase(mimeType) || PNG_MIME_TYPE.equalsIgnoreCase(mimeType))) {this.callbackContext.success(fileLocation);}else {- String uriString = uri.toString();- // Get the path to the image. Makes loading so much easier.- String mimeType = FileHelper.getMimeType(uriString, this.cordova);// This is a special case to just return the path as no scaling,// rotating, nor compressing needs to be doneif (this.targetHeight == -1 && this.targetWidth == -1 &&(destType == FILE_URI || destType == NATIVE_URI) && !this.correctOrientation &&- mimeType.equalsIgnoreCase(getMimetypeForFormat(encodingType)))+ mimeType != null && mimeType.equalsIgnoreCase(getMimetypeForFormat(encodingType))){this.callbackContext.success(uriString);} else {- // If we don't have a valid image so quit.- if (!("image/jpeg".equalsIgnoreCase(mimeType) || "image/png".equalsIgnoreCase(mimeType))) {- LOG.d(LOG_TAG, "I either have a null image path or bitmap");- this.failPicture("Unable to retrieve path to picture!");- return;- }Bitmap bitmap = null;try {bitmap = getScaledAndRotatedBitmap(uriString);@@ -912,14 +910,14 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect*/private Uri getUriFromMediaStore() {ContentValues values = new ContentValues();- values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");+ values.put(MediaStore.Images.Media.MIME_TYPE, JPEG_MIME_TYPE);Uri uri;try {- uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);+ uri = this.cordova.getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);} catch (RuntimeException e) {LOG.d(LOG_TAG, "Can't write to external media storage.");try {- uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);+ uri = this.cordova.getActivity().getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);} catch (RuntimeException ex) {LOG.d(LOG_TAG, "Can't write to internal media storage.");return null;@@ -975,19 +973,20 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnectInputStream fileStream = FileHelper.getInputStreamFromUriString(imageUrl, cordova);if (fileStream != null) {// Generate a temporary file- String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());- String fileName = "IMG_" + timeStamp + (this.encodingType == JPEG ? ".jpg" : ".png");+ String timeStamp = new SimpleDateFormat(TIME_FORMAT).format(new Date());+ String fileName = "IMG_" + timeStamp + (this.encodingType == JPEG ? JPEG_EXTENSION : PNG_EXTENSION);localFile = new File(getTempDirectoryPath() + fileName);galleryUri = Uri.fromFile(localFile);writeUncompressedImage(fileStream, galleryUri);try {String mimeType = FileHelper.getMimeType(imageUrl.toString(), cordova);- if ("image/jpeg".equalsIgnoreCase(mimeType)) {+ if (JPEG_MIME_TYPE.equalsIgnoreCase(mimeType)) {// ExifInterface doesn't like the file:// prefixString filePath = galleryUri.toString().replace("file://", "");// read exifData of sourceexifData = new ExifHelper();exifData.createInFile(filePath);+ exifData.readExifData();// Use ExifInterface to pull rotation informationif (this.correctOrientation) {ExifInterface exif = new ExifInterface(filePath);@@ -1244,9 +1243,9 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect*/private Uri whichContentStore() {if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {- return android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;+ return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;} else {- return android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;+ return MediaStore.Images.Media.INTERNAL_CONTENT_URI;}}@@ -1298,7 +1297,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnectpublic void onMediaScannerConnected() {try {this.conn.scanFile(this.scanMe.toString(), "image/*");- } catch (java.lang.IllegalStateException e) {+ } catch (IllegalStateException e) {LOG.e(LOG_TAG, "Can't scan file in MediaScanner after taking picture");}@@ -1347,11 +1346,11 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnectstate.putBoolean("saveToPhotoAlbum", this.saveToPhotoAlbum);if (this.croppedUri != null) {- state.putString("croppedUri", this.croppedUri.toString());+ state.putString(CROPPED_URI_KEY, this.croppedUri.toString());}if (this.imageUri != null) {- state.putString("imageUri", this.imageUri.getFileUri().toString());+ state.putString(IMAGE_URI_KEY, this.imageUri.getFileUri().toString());}return state;@@ -1370,38 +1369,34 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnectthis.correctOrientation = state.getBoolean("correctOrientation");this.saveToPhotoAlbum = state.getBoolean("saveToPhotoAlbum");- if (state.containsKey("croppedUri")) {- this.croppedUri = Uri.parse(state.getString("croppedUri"));+ if (state.containsKey(CROPPED_URI_KEY)) {+ this.croppedUri = Uri.parse(state.getString(CROPPED_URI_KEY));}- if (state.containsKey("imageUri")) {+ if (state.containsKey(IMAGE_URI_KEY)) {//I have no idea what type of URI is being passed in- this.imageUri = new CordovaUri(Uri.parse(state.getString("imageUri")));+ this.imageUri = new CordovaUri(Uri.parse(state.getString(IMAGE_URI_KEY)));}this.callbackContext = callbackContext;}- /*- * This is dirty, but it does the job.- *- * Since the FilesProvider doesn't really provide you a way of getting a URL from the file,- * and since we actually need the Camera to create the file for us most of the time, we don't- * actually write the file, just generate the location based on a timestamp, we need to get it- * back from the Intent.- *- * However, the FilesProvider preserves the path, so we can at least write to it from here, since- * we own the context in this case.- */-+ /*+ * This is dirty, but it does the job.+ *+ * Since the FilesProvider doesn't really provide you a way of getting a URL from the file,+ * and since we actually need the Camera to create the file for us most of the time, we don't+ * actually write the file, just generate the location based on a timestamp, we need to get it+ * back from the Intent.+ *+ * However, the FilesProvider preserves the path, so we can at least write to it from here, since+ * we own the context in this case.+ */private String getFileNameFromUri(Uri uri) {String fullUri = uri.toString();String partial_path = fullUri.split("external_files")[1];File external_storage = Environment.getExternalStorageDirectory();String path = external_storage.getAbsolutePath() + partial_path;return path;-}--}diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/camera/FileHelper.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/camera/FileHelper.javaindex ccc5e3e75..edf165787 100644--- a/cordova/platforms/android/app/src/main/java/org/apache/cordova/camera/FileHelper.java+++ b/cordova/platforms/android/app/src/main/java/org/apache/cordova/camera/FileHelper.java@@ -97,10 +97,21 @@ public class FileHelper {else if (isDownloadsDocument(uri)) {final String id = DocumentsContract.getDocumentId(uri);- final Uri contentUri = ContentUris.withAppendedId(- Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));-- return getDataColumn(context, contentUri, null, null);+ if (id != null && id.length() > 0) {+ if (id.startsWith("raw:")) {+ return id.replaceFirst("raw:", "");+ }+ try {+ final Uri contentUri = ContentUris.withAppendedId(+ Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));++ return getDataColumn(context, contentUri, null, null);+ } catch (NumberFormatException e) {+ return null;+ }+ } else {+ return null;+ }}// MediaProviderelse if (isMediaDocument(uri)) {diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioHandler.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioHandler.javadeleted file mode 100644index 9e734c440..000000000--- a/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioHandler.java+++ /dev/null@@ -1,568 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you 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.-*/-package org.apache.cordova.media;--import org.apache.cordova.CallbackContext;-import org.apache.cordova.CordovaPlugin;-import org.apache.cordova.CordovaResourceApi;-import org.apache.cordova.PermissionHelper;--import android.Manifest;-import android.content.Context;-import android.content.pm.PackageManager;-import android.media.AudioManager;-import android.media.AudioManager.OnAudioFocusChangeListener;-import android.net.Uri;-import android.os.Build;--import java.security.Permission;-import java.util.ArrayList;--import org.apache.cordova.LOG;-import org.apache.cordova.PluginResult;-import org.json.JSONArray;-import org.json.JSONException;-import org.json.JSONObject;--import java.util.HashMap;--/**- * This class called by CordovaActivity to play and record audio.- * The file can be local or over a network using http.- *- * Audio formats supported (tested):- * .mp3, .wav- *- * Local audio files must reside in one of two places:- * android_asset: file name must start with /android_asset/sound.mp3- * sdcard: file name is just sound.mp3- */-public class AudioHandler extends CordovaPlugin {-- public static String TAG = "AudioHandler";- HashMap<String, AudioPlayer> players; // Audio player object- ArrayList<AudioPlayer> pausedForPhone; // Audio players that were paused when phone call came in- ArrayList<AudioPlayer> pausedForFocus; // Audio players that were paused when focus was lost- private int origVolumeStream = -1;- private CallbackContext messageChannel;--- public static String [] permissions = { Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE};- public static int RECORD_AUDIO = 0;- public static int WRITE_EXTERNAL_STORAGE = 1;-- public static final int PERMISSION_DENIED_ERROR = 20;-- private String recordId;- private String fileUriStr;-- /**- * Constructor.- */- public AudioHandler() {- this.players = new HashMap<String, AudioPlayer>();- this.pausedForPhone = new ArrayList<AudioPlayer>();- this.pausedForFocus = new ArrayList<AudioPlayer>();- }--- protected void getWritePermission(int requestCode)- {- PermissionHelper.requestPermission(this, requestCode, permissions[WRITE_EXTERNAL_STORAGE]);- }--- protected void getMicPermission(int requestCode)- {- PermissionHelper.requestPermission(this, requestCode, permissions[RECORD_AUDIO]);- }--- /**- * Executes the request and returns PluginResult.- * @param action The action to execute.- * @param args JSONArry of arguments for the plugin.- * @param callbackContext The callback context used when calling back into JavaScript.- * @return A PluginResult object with a status and message.- */- public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {- CordovaResourceApi resourceApi = webView.getResourceApi();- PluginResult.Status status = PluginResult.Status.OK;- String result = "";-- if (action.equals("startRecordingAudio")) {- recordId = args.getString(0);- String target = args.getString(1);- try {- Uri targetUri = resourceApi.remapUri(Uri.parse(target));- fileUriStr = targetUri.toString();- } catch (IllegalArgumentException e) {- fileUriStr = target;- }- promptForRecord();- }- else if (action.equals("stopRecordingAudio")) {- this.stopRecordingAudio(args.getString(0), true);- }- else if (action.equals("pauseRecordingAudio")) {- this.stopRecordingAudio(args.getString(0), false);- }- else if (action.equals("resumeRecordingAudio")) {- this.resumeRecordingAudio(args.getString(0));- }- else if (action.equals("startPlayingAudio")) {- String target = args.getString(1);- String fileUriStr;- try {- Uri targetUri = resourceApi.remapUri(Uri.parse(target));- fileUriStr = targetUri.toString();- } catch (IllegalArgumentException e) {- fileUriStr = target;- }- this.startPlayingAudio(args.getString(0), FileHelper.stripFileProtocol(fileUriStr));- }- else if (action.equals("seekToAudio")) {- this.seekToAudio(args.getString(0), args.getInt(1));- }- else if (action.equals("pausePlayingAudio")) {- this.pausePlayingAudio(args.getString(0));- }- else if (action.equals("stopPlayingAudio")) {- this.stopPlayingAudio(args.getString(0));- } else if (action.equals("setVolume")) {- try {- this.setVolume(args.getString(0), Float.parseFloat(args.getString(1)));- } catch (NumberFormatException nfe) {- //no-op- }- } else if (action.equals("getCurrentPositionAudio")) {- float f = this.getCurrentPositionAudio(args.getString(0));- callbackContext.sendPluginResult(new PluginResult(status, f));- return true;- }- else if (action.equals("getDurationAudio")) {- float f = this.getDurationAudio(args.getString(0), args.getString(1));- callbackContext.sendPluginResult(new PluginResult(status, f));- return true;- }- else if (action.equals("create")) {- String id = args.getString(0);- String src = FileHelper.stripFileProtocol(args.getString(1));- getOrCreatePlayer(id, src);- }- else if (action.equals("release")) {- boolean b = this.release(args.getString(0));- callbackContext.sendPluginResult(new PluginResult(status, b));- return true;- }- else if (action.equals("messageChannel")) {- messageChannel = callbackContext;- return true;- } else if (action.equals("getCurrentAmplitudeAudio")) {- float f = this.getCurrentAmplitudeAudio(args.getString(0));- callbackContext.sendPluginResult(new PluginResult(status, f));- return true;- }- else { // Unrecognized action.- return false;- }-- callbackContext.sendPluginResult(new PluginResult(status, result));-- return true;- }-- /**- * Stop all audio players and recorders.- */- public void onDestroy() {- if (!players.isEmpty()) {- onLastPlayerReleased();- }- for (AudioPlayer audio : this.players.values()) {- audio.destroy();- }- this.players.clear();- }-- /**- * Stop all audio players and recorders on navigate.- */- @Override- public void onReset() {- onDestroy();- }-- /**- * Called when a message is sent to plugin.- *- * @param id The message id- * @param data The message data- * @return Object to stop propagation or null- */- public Object onMessage(String id, Object data) {-- // If phone message- if (id.equals("telephone")) {-- // If phone ringing, then pause playing- if ("ringing".equals(data) || "offhook".equals(data)) {-- // Get all audio players and pause them- for (AudioPlayer audio : this.players.values()) {- if (audio.getState() == AudioPlayer.STATE.MEDIA_RUNNING.ordinal()) {- this.pausedForPhone.add(audio);- audio.pausePlaying();- }- }-- }-- // If phone idle, then resume playing those players we paused- else if ("idle".equals(data)) {- for (AudioPlayer audio : this.pausedForPhone) {- audio.startPlaying(null);- }- this.pausedForPhone.clear();- }- }- return null;- }-- //--------------------------------------------------------------------------- // LOCAL METHODS- //---------------------------------------------------------------------------- private AudioPlayer getOrCreatePlayer(String id, String file) {- AudioPlayer ret = players.get(id);- if (ret == null) {- if (players.isEmpty()) {- onFirstPlayerCreated();- }- ret = new AudioPlayer(this, id, file);- players.put(id, ret);- }- return ret;- }-- /**- * Release the audio player instance to save memory.- * @param id The id of the audio player- */- private boolean release(String id) {- AudioPlayer audio = players.remove(id);- if (audio == null) {- return false;- }- if (players.isEmpty()) {- onLastPlayerReleased();- }- audio.destroy();- return true;- }-- /**- * Start recording and save the specified file.- * @param id The id of the audio player- * @param file The name of the file- */- public void startRecordingAudio(String id, String file) {- AudioPlayer audio = getOrCreatePlayer(id, file);- audio.startRecording(file);- }-- /**- * Stop/Pause recording and save to the file specified when recording started.- * @param id The id of the audio player- * @param stop If true stop recording, if false pause recording- */- public void stopRecordingAudio(String id, boolean stop) {- AudioPlayer audio = this.players.get(id);- if (audio != null) {- audio.stopRecording(stop);- }- }-- /**- * Resume recording- * @param id The id of the audio player- */- public void resumeRecordingAudio(String id) {- AudioPlayer audio = players.get(id);- if (audio != null) {- audio.resumeRecording();- }- }-- /**- * Start or resume playing audio file.- * @param id The id of the audio player- * @param file The name of the audio file.- */- public void startPlayingAudio(String id, String file) {- AudioPlayer audio = getOrCreatePlayer(id, file);- audio.startPlaying(file);- getAudioFocus();- }-- /**- * Seek to a location.- * @param id The id of the audio player- * @param milliseconds int: number of milliseconds to skip 1000 = 1 second- */- public void seekToAudio(String id, int milliseconds) {- AudioPlayer audio = this.players.get(id);- if (audio != null) {- audio.seekToPlaying(milliseconds);- }- }-- /**- * Pause playing.- * @param id The id of the audio player- */- public void pausePlayingAudio(String id) {- AudioPlayer audio = this.players.get(id);- if (audio != null) {- audio.pausePlaying();- }- }-- /**- * Stop playing the audio file.- * @param id The id of the audio player- */- public void stopPlayingAudio(String id) {- AudioPlayer audio = this.players.get(id);- if (audio != null) {- audio.stopPlaying();- }- }-- /**- * Get current position of playback.- * @param id The id of the audio player- * @return position in msec- */- public float getCurrentPositionAudio(String id) {- AudioPlayer audio = this.players.get(id);- if (audio != null) {- return (audio.getCurrentPosition() / 1000.0f);- }- return -1;- }-- /**- * Get the duration of the audio file.- * @param id The id of the audio player- * @param file The name of the audio file.- * @return The duration in msec.- */- public float getDurationAudio(String id, String file) {- AudioPlayer audio = getOrCreatePlayer(id, file);- return audio.getDuration(file);- }-- /**- * Set the audio device to be used for playback.- *- * @param output 1=earpiece, 2=speaker- */- @SuppressWarnings("deprecation")- public void setAudioOutputDevice(int output) {- String TAG1 = "AudioHandler.setAudioOutputDevice(): Error : ";-- AudioManager audiMgr = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);- if (output == 2) {- audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_SPEAKER, AudioManager.ROUTE_ALL);- }- else if (output == 1) {- audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);- }- else {- LOG.e(TAG1," Unknown output device");- }- }-- public void pauseAllLostFocus() {- for (AudioPlayer audio : this.players.values()) {- if (audio.getState() == AudioPlayer.STATE.MEDIA_RUNNING.ordinal()) {- this.pausedForFocus.add(audio);- audio.pausePlaying();- }- }- }-- public void resumeAllGainedFocus() {- for (AudioPlayer audio : this.pausedForFocus) {- audio.resumePlaying();- }- this.pausedForFocus.clear();- }-- /**- * Get the the audio focus- */- private OnAudioFocusChangeListener focusChangeListener = new OnAudioFocusChangeListener() {- public void onAudioFocusChange(int focusChange) {- switch (focusChange) {- case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :- case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :- case (AudioManager.AUDIOFOCUS_LOSS) :- pauseAllLostFocus();- break;- case (AudioManager.AUDIOFOCUS_GAIN):- resumeAllGainedFocus();- break;- default:- break;- }- }- };-- public void getAudioFocus() {- String TAG2 = "AudioHandler.getAudioFocus(): Error : ";-- AudioManager am = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);- int result = am.requestAudioFocus(focusChangeListener,- AudioManager.STREAM_MUSIC,- AudioManager.AUDIOFOCUS_GAIN);-- if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {- LOG.e(TAG2,result + " instead of " + AudioManager.AUDIOFOCUS_REQUEST_GRANTED);- }-- }--- /**- * Get the audio device to be used for playback.- *- * @return 1=earpiece, 2=speaker- */- @SuppressWarnings("deprecation")- public int getAudioOutputDevice() {- AudioManager audiMgr = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);- if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_EARPIECE) {- return 1;- }- else if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_SPEAKER) {- return 2;- }- else {- return -1;- }- }-- /**- * Set the volume for an audio device- *- * @param id The id of the audio player- * @param volume Volume to adjust to 0.0f - 1.0f- */- public void setVolume(String id, float volume) {- String TAG3 = "AudioHandler.setVolume(): Error : ";-- AudioPlayer audio = this.players.get(id);- if (audio != null) {- audio.setVolume(volume);- } else {- LOG.e(TAG3,"Unknown Audio Player " + id);- }- }-- private void onFirstPlayerCreated() {- origVolumeStream = cordova.getActivity().getVolumeControlStream();- cordova.getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);- }-- private void onLastPlayerReleased() {- if (origVolumeStream != -1) {- cordova.getActivity().setVolumeControlStream(origVolumeStream);- origVolumeStream = -1;- }- }-- void sendEventMessage(String action, JSONObject actionData) {- JSONObject message = new JSONObject();- try {- message.put("action", action);- if (actionData != null) {- message.put(action, actionData);- }- } catch (JSONException e) {- LOG.e(TAG, "Failed to create event message", e);- }-- PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, message);- pluginResult.setKeepCallback(true);- if (messageChannel != null) {- messageChannel.sendPluginResult(pluginResult);- }- }-- public void onRequestPermissionResult(int requestCode, String[] permissions,- int[] grantResults) throws JSONException- {- for(int r:grantResults)- {- if(r == PackageManager.PERMISSION_DENIED)- {- this.messageChannel.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, PERMISSION_DENIED_ERROR));- return;- }- }- promptForRecord();- }-- /*- * This little utility method catch-all work great for multi-permission stuff.- *- */-- private void promptForRecord()- {- if(PermissionHelper.hasPermission(this, permissions[WRITE_EXTERNAL_STORAGE]) &&- PermissionHelper.hasPermission(this, permissions[RECORD_AUDIO])) {- this.startRecordingAudio(recordId, FileHelper.stripFileProtocol(fileUriStr));- }- else if(PermissionHelper.hasPermission(this, permissions[RECORD_AUDIO]))- {- getWritePermission(WRITE_EXTERNAL_STORAGE);- }- else- {- getMicPermission(RECORD_AUDIO);- }-- }-- /**- * Get current amplitude of recording.- * @param id The id of the audio player- * @return amplitude- */- public float getCurrentAmplitudeAudio(String id) {- AudioPlayer audio = this.players.get(id);- if (audio != null) {- return (audio.getCurrentAmplitude());- }- return 0;- }-}diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioPlayer.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioPlayer.javadeleted file mode 100644index 861421e72..000000000--- a/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/AudioPlayer.java+++ /dev/null@@ -1,722 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you 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.-*/-package org.apache.cordova.media;--import android.media.AudioManager;-import android.media.MediaPlayer;-import android.media.MediaPlayer.OnCompletionListener;-import android.media.MediaPlayer.OnErrorListener;-import android.media.MediaPlayer.OnPreparedListener;-import android.media.MediaRecorder;-import android.os.Environment;--import org.apache.cordova.LOG;--import org.json.JSONException;-import org.json.JSONObject;--import java.io.File;-import java.io.FileInputStream;-import java.io.FileOutputStream;-import java.io.InputStream;-import java.io.OutputStream;-import java.io.IOException;-import java.util.LinkedList;--/**- * This class implements the audio playback and recording capabilities used by Cordova.- * It is called by the AudioHandler Cordova class.- * Only one file can be played or recorded per class instance.- *- * Local audio files must reside in one of two places:- * android_asset: file name must start with /android_asset/sound.mp3- * sdcard: file name is just sound.mp3- */-public class AudioPlayer implements OnCompletionListener, OnPreparedListener, OnErrorListener {-- // AudioPlayer modes- public enum MODE { NONE, PLAY, RECORD };-- // AudioPlayer states- public enum STATE { MEDIA_NONE,- MEDIA_STARTING,- MEDIA_RUNNING,- MEDIA_PAUSED,- MEDIA_STOPPED,- MEDIA_LOADING- };-- private static final String LOG_TAG = "AudioPlayer";-- // AudioPlayer message ids- private static int MEDIA_STATE = 1;- private static int MEDIA_DURATION = 2;- private static int MEDIA_POSITION = 3;- private static int MEDIA_ERROR = 9;-- // Media error codes- private static int MEDIA_ERR_NONE_ACTIVE = 0;- private static int MEDIA_ERR_ABORTED = 1;-// private static int MEDIA_ERR_NETWORK = 2;-// private static int MEDIA_ERR_DECODE = 3;-// private static int MEDIA_ERR_NONE_SUPPORTED = 4;-- private AudioHandler handler; // The AudioHandler object- private String id; // The id of this player (used to identify Media object in JavaScript)- private MODE mode = MODE.NONE; // Playback or Recording mode- private STATE state = STATE.MEDIA_NONE; // State of recording or playback-- private String audioFile = null; // File name to play or record to- private float duration = -1; // Duration of audio-- private MediaRecorder recorder = null; // Audio recording object- private LinkedList<String> tempFiles = null; // Temporary recording file name- private String tempFile = null;-- private MediaPlayer player = null; // Audio player object- private boolean prepareOnly = true; // playback after file prepare flag- private int seekOnPrepared = 0; // seek to this location once media is prepared-- /**- * Constructor.- *- * @param handler The audio handler object- * @param id The id of this audio player- */- public AudioPlayer(AudioHandler handler, String id, String file) {- this.handler = handler;- this.id = id;- this.audioFile = file;- this.tempFiles = new LinkedList<String>();- }-- private String generateTempFile() {- String tempFileName = null;- if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {- tempFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmprecording-" + System.currentTimeMillis() + ".3gp";- } else {- tempFileName = "/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/tmprecording-" + System.currentTimeMillis() + ".3gp";- }- return tempFileName;- }-- /**- * Destroy player and stop audio playing or recording.- */- public void destroy() {- // Stop any play or record- if (this.player != null) {- if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {- this.player.stop();- this.setState(STATE.MEDIA_STOPPED);- }- this.player.release();- this.player = null;- }- if (this.recorder != null) {- this.stopRecording(true);- this.recorder.release();- this.recorder = null;- }- }-- /**- * Start recording the specified file.- *- * @param file The name of the file- */- public void startRecording(String file) {- switch (this.mode) {- case PLAY:- LOG.d(LOG_TAG, "AudioPlayer Error: Can't record in play mode.");- sendErrorStatus(MEDIA_ERR_ABORTED);- break;- case NONE:- this.audioFile = file;- this.recorder = new MediaRecorder();- this.recorder.setAudioSource(MediaRecorder.AudioSource.MIC);- this.recorder.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS); // RAW_AMR);- this.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); //AMR_NB);- this.tempFile = generateTempFile();- this.recorder.setOutputFile(this.tempFile);- try {- this.recorder.prepare();- this.recorder.start();- this.setState(STATE.MEDIA_RUNNING);- return;- } catch (IllegalStateException e) {- e.printStackTrace();- } catch (IOException e) {- e.printStackTrace();- }-- sendErrorStatus(MEDIA_ERR_ABORTED);- break;- case RECORD:- LOG.d(LOG_TAG, "AudioPlayer Error: Already recording.");- sendErrorStatus(MEDIA_ERR_ABORTED);- }- }-- /**- * Save temporary recorded file to specified name- *- * @param file- */- public void moveFile(String file) {- /* this is a hack to save the file as the specified name */-- if (!file.startsWith("/")) {- if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {- file = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + file;- } else {- file = "/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/" + file;- }- }-- int size = this.tempFiles.size();- LOG.d(LOG_TAG, "size = " + size);-- // only one file so just copy it- if (size == 1) {- String logMsg = "renaming " + this.tempFile + " to " + file;- LOG.d(LOG_TAG, logMsg);- File f = new File(this.tempFile);- if (!f.renameTo(new File(file))) LOG.e(LOG_TAG, "FAILED " + logMsg);- }- // more than one file so the user must have pause recording. We'll need to concat files.- else {- FileOutputStream outputStream = null;- try {- outputStream = new FileOutputStream(new File(file));- FileInputStream inputStream = null;- File inputFile = null;- for (int i = 0; i < size; i++) {- try {- inputFile = new File(this.tempFiles.get(i));- inputStream = new FileInputStream(inputFile);- copy(inputStream, outputStream, (i>0));- } catch(Exception e) {- LOG.e(LOG_TAG, e.getLocalizedMessage(), e);- } finally {- if (inputStream != null) try {- inputStream.close();- inputFile.delete();- inputFile = null;- } catch (Exception e) {- LOG.e(LOG_TAG, e.getLocalizedMessage(), e);- }- }- }- } catch(Exception e) {- e.printStackTrace();- } finally {- if (outputStream != null) try {- outputStream.close();- } catch (Exception e) {- LOG.e(LOG_TAG, e.getLocalizedMessage(), e);- }- }- }- }-- private static long copy(InputStream from, OutputStream to, boolean skipHeader)- throws IOException {- byte[] buf = new byte[8096];- long total = 0;- if (skipHeader) {- from.skip(6);- }- while (true) {- int r = from.read(buf);- if (r == -1) {- break;- }- to.write(buf, 0, r);- total += r;- }- return total;- }-- /**- * Stop/Pause recording and save to the file specified when recording started.- */- public void stopRecording(boolean stop) {- if (this.recorder != null) {- try{- if (this.state == STATE.MEDIA_RUNNING) {- this.recorder.stop();- }- this.recorder.reset();- if (!this.tempFiles.contains(this.tempFile)) {- this.tempFiles.add(this.tempFile);- }- if (stop) {- LOG.d(LOG_TAG, "stopping recording");- this.setState(STATE.MEDIA_STOPPED);- this.moveFile(this.audioFile);- } else {- LOG.d(LOG_TAG, "pause recording");- this.setState(STATE.MEDIA_PAUSED);- }- }- catch (Exception e) {- e.printStackTrace();- }- }- }-- /**- * Resume recording and save to the file specified when recording started.- */- public void resumeRecording() {- startRecording(this.audioFile);- }-- //==========================================================================- // Playback- //==========================================================================-- /**- * Start or resume playing audio file.- *- * @param file The name of the audio file.- */- public void startPlaying(String file) {- if (this.readyPlayer(file) && this.player != null) {- this.player.start();- this.setState(STATE.MEDIA_RUNNING);- this.seekOnPrepared = 0; //insures this is always reset- } else {- this.prepareOnly = false;- }- }-- /**- * Seek or jump to a new time in the track.- */- public void seekToPlaying(int milliseconds) {- if (this.readyPlayer(this.audioFile)) {- if (milliseconds > 0) {- this.player.seekTo(milliseconds);- }- LOG.d(LOG_TAG, "Send a onStatus update for the new seek");- sendStatusChange(MEDIA_POSITION, null, (milliseconds / 1000.0f));- }- else {- this.seekOnPrepared = milliseconds;- }- }-- /**- * Pause playing.- */- public void pausePlaying() {-- // If playing, then pause- if (this.state == STATE.MEDIA_RUNNING && this.player != null) {- this.player.pause();- this.setState(STATE.MEDIA_PAUSED);- }- else {- LOG.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: " + this.state.ordinal());- sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);- }- }-- /**- * Stop playing the audio file.- */- public void stopPlaying() {- if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {- this.player.pause();- this.player.seekTo(0);- LOG.d(LOG_TAG, "stopPlaying is calling stopped");- this.setState(STATE.MEDIA_STOPPED);- }- else {- LOG.d(LOG_TAG, "AudioPlayer Error: stopPlaying() called during invalid state: " + this.state.ordinal());- sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);- }- }-- /**- * Resume playing.- */- public void resumePlaying() {- this.startPlaying(this.audioFile);- }-- /**- * Callback to be invoked when playback of a media source has completed.- *- * @param player The MediaPlayer that reached the end of the file- */- public void onCompletion(MediaPlayer player) {- LOG.d(LOG_TAG, "on completion is calling stopped");- this.setState(STATE.MEDIA_STOPPED);- }-- /**- * Get current position of playback.- *- * @return position in msec or -1 if not playing- */- public long getCurrentPosition() {- if ((this.state == STATE.MEDIA_RUNNING) || (this.state == STATE.MEDIA_PAUSED)) {- int curPos = this.player.getCurrentPosition();- sendStatusChange(MEDIA_POSITION, null, (curPos / 1000.0f));- return curPos;- }- else {- return -1;- }- }-- /**- * Determine if playback file is streaming or local.- * It is streaming if file name starts with "http://"- *- * @param file The file name- * @return T=streaming, F=local- */- public boolean isStreaming(String file) {- if (file.contains("http://") || file.contains("https://") || file.contains("rtsp://")) {- return true;- }- else {- return false;- }- }-- /**- * Get the duration of the audio file.- *- * @param file The name of the audio file.- * @return The duration in msec.- * -1=can't be determined- * -2=not allowed- */- public float getDuration(String file) {-- // Can't get duration of recording- if (this.recorder != null) {- return (-2); // not allowed- }-- // If audio file already loaded and started, then return duration- if (this.player != null) {- return this.duration;- }-- // If no player yet, then create one- else {- this.prepareOnly = true;- this.startPlaying(file);-- // This will only return value for local, since streaming- // file hasn't been read yet.- return this.duration;- }- }-- /**- * Callback to be invoked when the media source is ready for playback.- *- * @param player The MediaPlayer that is ready for playback- */- public void onPrepared(MediaPlayer player) {- // Listen for playback completion- this.player.setOnCompletionListener(this);- // seek to any location received while not prepared- this.seekToPlaying(this.seekOnPrepared);- // If start playing after prepared- if (!this.prepareOnly) {- this.player.start();- this.setState(STATE.MEDIA_RUNNING);- this.seekOnPrepared = 0; //reset only when played- } else {- this.setState(STATE.MEDIA_STARTING);- }- // Save off duration- this.duration = getDurationInSeconds();- // reset prepare only flag- this.prepareOnly = true;-- // Send status notification to JavaScript- sendStatusChange(MEDIA_DURATION, null, this.duration);- }-- /**- * By default Android returns the length of audio in mills but we want seconds- *- * @return length of clip in seconds- */- private float getDurationInSeconds() {- return (this.player.getDuration() / 1000.0f);- }-- /**- * Callback to be invoked when there has been an error during an asynchronous operation- * (other errors will throw exceptions at method call time).- *- * @param player the MediaPlayer the error pertains to- * @param arg1 the type of error that has occurred: (MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_SERVER_DIED)- * @param arg2 an extra code, specific to the error.- */- public boolean onError(MediaPlayer player, int arg1, int arg2) {- LOG.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2 + ")");-- // we don't want to send success callback- // so we don't call setState() here- this.state = STATE.MEDIA_STOPPED;- this.destroy();- // Send error notification to JavaScript- sendErrorStatus(arg1);-- return false;- }-- /**- * Set the state and send it to JavaScript.- *- * @param state- */- private void setState(STATE state) {- if (this.state != state) {- sendStatusChange(MEDIA_STATE, null, (float)state.ordinal());- }- this.state = state;- }-- /**- * Set the mode and send it to JavaScript.- *- * @param mode- */- private void setMode(MODE mode) {- if (this.mode != mode) {- //mode is not part of the expected behavior, so no notification- //this.handler.webView.sendJavascript("cordova.require('cordova-plugin-media.Media').onStatus('" + this.id + "', " + MEDIA_STATE + ", " + mode + ");");- }- this.mode = mode;- }-- /**- * Get the audio state.- *- * @return int- */- public int getState() {- return this.state.ordinal();- }-- /**- * Set the volume for audio player- *- * @param volume- */- public void setVolume(float volume) {- if (this.player != null) {- this.player.setVolume(volume, volume);- } else {- LOG.d(LOG_TAG, "AudioPlayer Error: Cannot set volume until the audio file is initialized.");- sendErrorStatus(MEDIA_ERR_NONE_ACTIVE);- }- }-- /**- * attempts to put the player in play mode- * @return true if in playmode, false otherwise- */- private boolean playMode() {- switch(this.mode) {- case NONE:- this.setMode(MODE.PLAY);- break;- case PLAY:- break;- case RECORD:- LOG.d(LOG_TAG, "AudioPlayer Error: Can't play in record mode.");- sendErrorStatus(MEDIA_ERR_ABORTED);- return false; //player is not ready- }- return true;- }-- /**- * attempts to initialize the media player for playback- * @param file the file to play- * @return false if player not ready, reports if in wrong mode or state- */- private boolean readyPlayer(String file) {- if (playMode()) {- switch (this.state) {- case MEDIA_NONE:- if (this.player == null) {- this.player = new MediaPlayer();- this.player.setOnErrorListener(this);- }- try {- this.loadAudioFile(file);- } catch (Exception e) {- sendErrorStatus(MEDIA_ERR_ABORTED);- }- return false;- case MEDIA_LOADING:- //cordova js is not aware of MEDIA_LOADING, so we send MEDIA_STARTING instead- LOG.d(LOG_TAG, "AudioPlayer Loading: startPlaying() called during media preparation: " + STATE.MEDIA_STARTING.ordinal());- this.prepareOnly = false;- return false;- case MEDIA_STARTING:- case MEDIA_RUNNING:- case MEDIA_PAUSED:- return true;- case MEDIA_STOPPED:- //if we are readying the same file- if (file!=null && this.audioFile.compareTo(file) == 0) {- //maybe it was recording?- if (player == null) {- this.player = new MediaPlayer();- this.player.setOnErrorListener(this);- this.prepareOnly = false;-- try {- this.loadAudioFile(file);- } catch (Exception e) {- sendErrorStatus(MEDIA_ERR_ABORTED);- }- return false;//we´re not ready yet- }- else {- //reset the audio file- player.seekTo(0);- player.pause();- return true;- }- } else {- //reset the player- this.player.reset();- try {- this.loadAudioFile(file);- } catch (Exception e) {- sendErrorStatus(MEDIA_ERR_ABORTED);- }- //if we had to prepare the file, we won't be in the correct state for playback- return false;- }- default:- LOG.d(LOG_TAG, "AudioPlayer Error: startPlaying() called during invalid state: " + this.state);- sendErrorStatus(MEDIA_ERR_ABORTED);- }- }- return false;- }-- /**- * load audio file- * @throws IOException- * @throws IllegalStateException- * @throws SecurityException- * @throws IllegalArgumentException- */- private void loadAudioFile(String file) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {- if (this.isStreaming(file)) {- this.player.setDataSource(file);- this.player.setAudioStreamType(AudioManager.STREAM_MUSIC);- //if it's a streaming file, play mode is implied- this.setMode(MODE.PLAY);- this.setState(STATE.MEDIA_STARTING);- this.player.setOnPreparedListener(this);- this.player.prepareAsync();- }- else {- if (file.startsWith("/android_asset/")) {- String f = file.substring(15);- android.content.res.AssetFileDescriptor fd = this.handler.cordova.getActivity().getAssets().openFd(f);- this.player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());- }- else {- File fp = new File(file);- if (fp.exists()) {- FileInputStream fileInputStream = new FileInputStream(file);- this.player.setDataSource(fileInputStream.getFD());- fileInputStream.close();- }- else {- this.player.setDataSource(Environment.getExternalStorageDirectory().getPath() + "/" + file);- }- }- this.setState(STATE.MEDIA_STARTING);- this.player.setOnPreparedListener(this);- this.player.prepare();-- // Get duration- this.duration = getDurationInSeconds();- }- }-- private void sendErrorStatus(int errorCode) {- sendStatusChange(MEDIA_ERROR, errorCode, null);- }-- private void sendStatusChange(int messageType, Integer additionalCode, Float value) {-- if (additionalCode != null && value != null) {- throw new IllegalArgumentException("Only one of additionalCode or value can be specified, not both");- }-- JSONObject statusDetails = new JSONObject();- try {- statusDetails.put("id", this.id);- statusDetails.put("msgType", messageType);- if (additionalCode != null) {- JSONObject code = new JSONObject();- code.put("code", additionalCode.intValue());- statusDetails.put("value", code);- }- else if (value != null) {- statusDetails.put("value", value.floatValue());- }- } catch (JSONException e) {- LOG.e(LOG_TAG, "Failed to create status details", e);- }-- this.handler.sendEventMessage("status", statusDetails);- }-- /**- * Get current amplitude of recording.- *- * @return amplitude or 0 if not recording- */- public float getCurrentAmplitude() {- if (this.recorder != null) {- try{- if (this.state == STATE.MEDIA_RUNNING) {- return (float) this.recorder.getMaxAmplitude() / 32762;- }- }- catch (Exception e) {- e.printStackTrace();- }- }- return 0;- }-}diff --git a/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/FileHelper.java b/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/FileHelper.javadeleted file mode 100644index e20752c62..000000000--- a/cordova/platforms/android/app/src/main/java/org/apache/cordova/media/FileHelper.java+++ /dev/null@@ -1,38 +0,0 @@-/*- Licensed to the Apache Software Foundation (ASF) under one- or more contributor license agreements. See the NOTICE file- distributed with this work for additional information- regarding copyright ownership. The ASF licenses this file- to you 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.- */-package org.apache.cordova.media;--import android.net.Uri;--public class FileHelper {-- /**- * Removes the "file://" prefix from the given URI string, if applicable.- * If the given URI string doesn't have a "file://" prefix, it is returned unchanged.- *- * @param uriString the URI string to operate on- * @return a path without the "file://" prefix- */- public static String stripFileProtocol(String uriString) {- if (uriString.startsWith("file://")) {- return Uri.parse(uriString).getPath();- }- return uriString;- }-}diff --git a/cordova/platforms/android/app/src/main/res/xml/config.xml b/cordova/platforms/android/app/src/main/res/xml/config.xmlindex 4fe3a337a..df9ee3aa5 100644--- a/cordova/platforms/android/app/src/main/res/xml/config.xml+++ b/cordova/platforms/android/app/src/main/res/xml/config.xml@@ -1,19 +1,22 @@<?xml version='1.0' encoding='utf-8'?><widget id="org.tagspaces.mobile" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">- <feature name="Camera">- <param name="android-package" value="org.apache.cordova.camera.CameraLauncher" />- </feature><feature name="Device"><param name="android-package" value="org.apache.cordova.device.Device" /></feature>+ <feature name="BackgroundMode">+ <param name="android-package" value="de.appplant.cordova.plugin.background.BackgroundMode" />+ </feature>+ <feature name="BackgroundModeExt">+ <param name="android-package" value="de.appplant.cordova.plugin.background.BackgroundModeExt" />+ </feature>+ <feature name="Camera">+ <param name="android-package" value="org.apache.cordova.camera.CameraLauncher" />+ </feature><feature name="File"><param name="android-package" value="org.apache.cordova.file.FileUtils" /><param name="onload" value="true" /></feature><allow-navigation href="cdvfile:*" />- <feature name="Media">- <param name="android-package" value="org.apache.cordova.media.AudioHandler" />- </feature><feature name="Whitelist"><param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" /><param name="onload" value="true" />@@ -35,6 +38,7 @@<allow-intent href="geo:*" /><allow-intent href="market:*" /><preference name="loglevel" value="DEBUG" />+ <preference name="KeepRunning" value="true" /><preference name="AndroidPersistentFileLocation" value="Compatibility" /><preference name="iosExtraFilesystems" value="library,library-nosync,documents,documents-nosync,cache,bundle,root" /><preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,cache,cache-external,assets,root" />diff --git a/cordova/platforms/android/platform_www/cordova_plugins.js b/cordova/platforms/android/platform_www/cordova_plugins.jsindex 0086aec18..c6aa2a641 100644--- a/cordova/platforms/android/platform_www/cordova_plugins.js+++ b/cordova/platforms/android/platform_www/cordova_plugins.js@@ -1,5 +1,22 @@cordova.define('cordova/plugin_list', function(require, exports, module) {module.exports = [+ {+ "id": "cordova-plugin-device.device",+ "file": "plugins/cordova-plugin-device/www/device.js",+ "pluginId": "cordova-plugin-device",+ "clobbers": [+ "device"+ ]+ },+ {+ "id": "cordova-plugin-background-mode.BackgroundMode",+ "file": "plugins/cordova-plugin-background-mode/www/background-mode.js",+ "pluginId": "cordova-plugin-background-mode",+ "clobbers": [+ "cordova.plugins.backgroundMode",+ "plugin.backgroundMode"+ ]+ },{"id": "cordova-plugin-camera.Camera","file": "plugins/cordova-plugin-camera/www/CameraConstants.js",@@ -32,14 +49,6 @@ module.exports = ["CameraPopoverHandle"]},- {- "id": "cordova-plugin-device.device",- "file": "plugins/cordova-plugin-device/www/device.js",- "pluginId": "cordova-plugin-device",- "clobbers": [- "device"- ]- },{"id": "cordova-plugin-file.DirectoryEntry","file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",@@ -212,31 +221,15 @@ module.exports = ["cordova"],"runs": true- },- {- "id": "cordova-plugin-media.MediaError",- "file": "plugins/cordova-plugin-media/www/MediaError.js",- "pluginId": "cordova-plugin-media",- "clobbers": [- "window.MediaError"- ]- },- {- "id": "cordova-plugin-media.Media",- "file": "plugins/cordova-plugin-media/www/Media.js",- "pluginId": "cordova-plugin-media",- "clobbers": [- "window.Media"- ]}];module.exports.metadata =// TOP OF METADATA{- "cordova-plugin-camera": "4.0.3","cordova-plugin-device": "2.0.2",- "cordova-plugin-file": "6.0.1",- "cordova-plugin-media": "5.0.2",+ "cordova-plugin-background-mode": "0.7.3",+ "cordova-plugin-camera": "4.1.0",+ "cordova-plugin-file": "6.0.2","cordova-plugin-whitelist": "1.3.3"};// BOTTOM OF METADATAdiff --git a/cordova/platforms/android/platform_www/plugins/cordova-plugin-background-mode/www/background-mode.js b/cordova/platforms/android/platform_www/plugins/cordova-plugin-background-mode/www/background-mode.jsnew file mode 100644index 000000000..7895b27ad--- /dev/null+++ b/cordova/platforms/android/platform_www/plugins/cordova-plugin-background-mode/www/background-mode.js@@ -0,0 +1,513 @@+cordova.define("cordova-plugin-background-mode.BackgroundMode", function(require, exports, module) {+/*+ Copyright 2013-2017 appPlant GmbH++ Licensed to the Apache Software Foundation (ASF) under one+ or more contributor license agreements. See the NOTICE file+ distributed with this work for additional information+ regarding copyright ownership. The ASF licenses this file+ to you 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.+*/++var exec = require('cordova/exec'),+ channel = require('cordova/channel');++/**+ * Activates the background mode. When activated the application+ * will be prevented from going to sleep while in background+ * for the next time.+ *+ * @return [ Void ]+ */+exports.enable = function()+{+ if (this.isEnabled())+ return;++ var fn = function() {+ exports._isEnabled = true;+ exports.fireEvent('enable');+ };++ cordova.exec(fn, null, 'BackgroundMode', 'enable', []);+};++/**+ * Deactivates the background mode. When deactivated the application+ * will not stay awake while in background.+ *+ * @return [ Void ]+ */+exports.disable = function()+{+ if (!this.isEnabled())+ return;++ var fn = function() {+ exports._isEnabled = false;+ exports.fireEvent('disable');+ };++ cordova.exec(fn, null, 'BackgroundMode', 'disable', []);+};++/**+ * Enable or disable the background mode.+ *+ * @param [ Bool ] enable The status to set for.+ *+ * @return [ Void ]+ */+exports.setEnabled = function (enable)+{+ if (enable) {+ this.enable();+ } else {+ this.disable();+ }+};++/**+ * List of all available options with their default value.+ *+ * @return [ Object ]+ */+exports.getDefaults = function()+{+ return this._defaults;+};++/**+ * The actual applied settings.+ *+ * @return [ Object ]+ */+exports.getSettings = function()+{+ return this._settings || {};+};++/**+ * Overwrite the default settings.+ *+ * @param [ Object ] overrides Dict of options to be overridden.+ *+ * @return [ Void ]+ */+exports.setDefaults = function (overrides)+{+ var defaults = this.getDefaults();++ for (var key in defaults)+ {+ if (overrides.hasOwnProperty(key))+ {+ defaults[key] = overrides[key];+ }+ }++ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundMode', 'configure', [defaults, false]);+ }+};++/**+ * Configures the notification settings for Android.+ * Will be merged with the defaults.+ *+ * @param [ Object ] options Dict of options to be overridden.+ *+ * @return [ Void ]+ */+exports.configure = function (options)+{+ var settings = this.getSettings(),+ defaults = this.getDefaults();++ if (!this._isAndroid)+ return;++ if (!this._isActive)+ {+ console.log('BackgroundMode is not active, skipped...');+ return;+ }++ this._mergeObjects(options, settings);+ this._mergeObjects(options, defaults);+ this._settings = options;++ cordova.exec(null, null, 'BackgroundMode', 'configure', [options, true]);+};++/**+ * Enable GPS-tracking in background (Android).+ *+ * @return [ Void ]+ */+exports.disableWebViewOptimizations = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'webview', []);+ }+};++/**+ * Disables battery optimazation mode for the app.+ *+ * @return [ Void ]+ */+exports.disableBatteryOptimizations = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'battery', []);+ }+};++/**+ * Opens the system settings dialog where the user can tweak or turn off any+ * custom app start settings added by the manufacturer if available.+ *+ * @param [ Object|Bool ] options Set to false if you dont want to display an+ * alert dialog first.+ *+ * @return [ Void ]+ */+exports.openAppStartSettings = function (options)+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'appstart', [options]);+ }+};++/**+ * Move app to background (Android only).+ *+ * @return [ Void ]+ */+exports.moveToBackground = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'background', []);+ }+};++/**+ * Move app to foreground when in background (Android only).+ *+ * @return [ Void ]+ */+exports.moveToForeground = function()+{+ if (this.isActive() && this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'foreground', []);+ }+};++/**+ * Exclude the app from the recent tasks list (Android only).+ *+ * @return [ Void ]+ */+exports.excludeFromTaskList = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'tasklist', []);+ }+};++/**+ * Override the back button on Android to go to background+ * instead of closing the app.+ *+ * @return [ Void ]+ */+exports.overrideBackButton = function()+{+ document.addEventListener('backbutton', function() {+ exports.moveToBackground();+ }, 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, 'BackgroundModeExt', 'dimmed', []);+ }+ else+ {+ fn(undefined);+ }+};++/**+ * Wake up the device.+ *+ * @return [ Void ]+ */+exports.wakeUp = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'wakeup', []);+ }+};++/**+ * Wake up and unlock the device.+ *+ * @return [ Void ]+ */+exports.unlock = function()+{+ if (this._isAndroid)+ {+ cordova.exec(null, null, 'BackgroundModeExt', 'unlock', []);+ }+};++/**+ * If the mode is enabled or disabled.+ *+ * @return [ Boolean ]+ */+exports.isEnabled = function()+{+ return this._isEnabled !== false;+};++/**+ * If the mode is active.+ *+ * @return [ Boolean ]+ */+exports.isActive = function()+{+ return this._isActive !== false;+};++exports._listener = {};++/**+ * Fire event with given arguments.+ *+ * @param [ String ] event The event's name.+ * @param [ Array<Object> ] The callback's arguments.+ *+ * @return [ Void ]+ */+exports.fireEvent = function (event)+{+ var args = Array.apply(null, arguments).slice(1),+ listener = this._listener[event];++ if (!listener)+ return;++ for (var i = 0; i < listener.length; i++)+ {+ var fn = listener[i][0],+ scope = listener[i][1];++ fn.apply(scope, args);+ }+};++/**+ * Register callback for given event.+ *+ * @param [ String ] event The event's name.+ * @param [ Function ] callback The function to be exec as callback.+ * @param [ Object ] scope The callback function's scope.+ *+ * @return [ Void ]+ */+exports.on = function (event, callback, scope)+{+ if (typeof callback !== "function")+ return;++ if (!this._listener[event])+ {+ this._listener[event] = [];+ }++ var item = [callback, scope || window];++ this._listener[event].push(item);+};++/**+ * Unregister callback for given event.+ *+ * @param [ String ] event The event's name.+ * @param [ Function ] callback The function to be exec as callback.+ *+ * @return [ Void ]+ */+exports.un = function (event, callback)+{+ var listener = this._listener[event];++ if (!listener)+ return;++ for (var i = 0; i < listener.length; i++)+ {+ var fn = listener[i][0];++ if (fn == callback)+ {+ listener.splice(i, 1);+ break;+ }+ }+};++/**+ * @private+ *+ * Flag indicates if the mode is enabled.+ */+exports._isEnabled = false;++/**+ * @private+ *+ * Flag indicates if the mode is active.+ */+exports._isActive = false;++/**+ * @private+ *+ * Default values of all available options.+ */+exports._defaults =+{+ title: 'App is running in background',+ text: 'Doing heavy tasks.',+ bigText: false,+ resume: true,+ silent: false,+ hidden: true,+ color: undefined,+ icon: 'icon'+};++/**+ * @private+ *+ * Merge settings with default values.+ *+ * @param [ Object ] options The custom options.+ * @param [ Object ] toMergeIn The options to merge in.+ *+ * @return [ Object ] Default values merged with custom values.+ */+exports._mergeObjects = function (options, toMergeIn)+{+ for (var key in toMergeIn)+ {+ if (!options.hasOwnProperty(key))+ {+ options[key] = toMergeIn[key];+ continue;+ }+ }++ return options;+};++/**+ * @private+ *+ * Setter for the isActive flag. Resets the+ * settings if the mode isnt active anymore.+ *+ * @param [ Boolean] value The new value for the flag.+ *+ * @return [ Void ]+ */+exports._setActive = function(value)+{+ if (this._isActive == value)+ return;++ this._isActive = value;+ this._settings = value ? this._mergeObjects({}, this._defaults) : {};+};++/**+ * @private+ *+ * Initialize the plugin.+ *+ * Method should be called after the 'deviceready' event+ * but before the event listeners will be called.+ *+ * @return [ Void ]+ */+exports._pluginInitialize = function()+{+ this._isAndroid = device.platform.match(/^android|amazon/i) !== null;+ this.setDefaults({});++ if (device.platform == 'browser')+ {+ this.enable();+ this._isEnabled = true;+ }++ this._isActive = this._isActive || device.platform == 'browser';+};++// Called before 'deviceready' listener will be called+channel.onCordovaReady.subscribe(function()+{+ channel.onCordovaInfoReady.subscribe(function() {+ exports._pluginInitialize();+ });+});++// Called after 'deviceready' event+channel.deviceready.subscribe(function()+{+ if (exports.isEnabled())+ {+ exports.fireEvent('enable');+ }++ if (exports.isActive())+ {+ exports.fireEvent('activate');+ }+});++});diff --git a/cordova/platforms/android/platform_www/plugins/cordova-plugin-camera/www/CameraPopoverOptions.js b/cordova/platforms/android/platform_www/plugins/cordova-plugin-camera/www/CameraPopoverOptions.jsindex 81d7d20ec..6e03c52ee 100644--- a/cordova/platforms/android/platform_www/plugins/cordova-plugin-camera/www/CameraPopoverOptions.js+++ b/cordova/platforms/android/platform_www/plugins/cordova-plugin-camera/www/CameraPopoverOptions.js@@ -40,14 +40,18 @@ var Camera = require('./Camera');* @param {Number} [width=320] - width, in pixels, of the screen element onto which to anchor the popover.* @param {Number} [height=480] - height, in pixels, of the screen element onto which to anchor the popover.* @param {module:Camera.PopoverArrowDirection} [arrowDir=ARROW_ANY] - Direction the arrow on the popover should point.+ * @param {Number} [popoverWidth=0] - width of the popover (0 or not specified will use apple's default width).+ * @param {Number} [popoverHeight=0] - height of the popover (0 or not specified will use apple's default height).*/-var CameraPopoverOptions = function (x, y, width, height, arrowDir) {+var CameraPopoverOptions = function (x, y, width, height, arrowDir, popoverWidth, popoverHeight) {// information of rectangle that popover should be anchored tothis.x = x || 0;this.y = y || 32;this.width = width || 320;this.height = height || 480;this.arrowDir = arrowDir || Camera.PopoverArrowDirection.ARROW_ANY;+ this.popoverWidth = popoverWidth || 0;+ this.popoverHeight = popoverHeight || 0;};module.exports = CameraPopoverOptions;diff --git a/cordova/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileWriter.js b/cordova/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileWriter.jsindex d48a08907..c3e856219 100644--- a/cordova/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileWriter.js+++ b/cordova/platforms/android/platform_www/plugins/cordova-plugin-file/www/FileWriter.js@@ -22,6 +22,7 @@ cordova.define("cordova-plugin-file.FileWriter", function(require, exports, moduvar exec = require('cordova/exec');var FileError = require('./FileError');+var FileReader = require('./FileReader');var ProgressEvent = require('./ProgressEvent');/**diff --git a/cordova/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystems-roots.js b/cordova/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystems-roots.jsindex 935113270..6e02953e8 100644--- a/cordova/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystems-roots.js+++ b/cordova/platforms/android/platform_www/plugins/cordova-plugin-file/www/fileSystems-roots.js@@ -31,8 +31,10 @@ require('./fileSystems').getFs = function (name, callback) {fsMap = {};for (var i = 0; i < response.length; ++i) {var fsRoot = response[i];- var fs = new FileSystem(fsRoot.filesystemName, fsRoot);- fsMap[fs.name] = fs;+ if (fsRoot) {+ var fs = new FileSystem(fsRoot.filesystemName, fsRoot);+ fsMap[fs.name] = fs;+ }}callback(fsMap[name]);}diff --git a/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/Media.js b/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/Media.jsdeleted file mode 100644index 2ca4b2d28..000000000--- a/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/Media.js+++ /dev/null@@ -1,260 +0,0 @@-cordova.define("cordova-plugin-media.Media", function(require, exports, module) {-/*- *- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you 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.- *-*/--var argscheck = require('cordova/argscheck'),- utils = require('cordova/utils'),- exec = require('cordova/exec');--var mediaObjects = {};--/**- * This class provides access to the device media, interfaces to both sound and video- *- * @constructor- * @param src The file name or url to play- * @param successCallback The callback to be called when the file is done playing or recording.- * successCallback()- * @param errorCallback The callback to be called if there is an error.- * errorCallback(int errorCode) - OPTIONAL- * @param statusCallback The callback to be called when media status has changed.- * statusCallback(int statusCode) - OPTIONAL- */-var Media = function(src, successCallback, errorCallback, statusCallback) {- argscheck.checkArgs('sFFF', 'Media', arguments);- this.id = utils.createUUID();- mediaObjects[this.id] = this;- this.src = src;- this.successCallback = successCallback;- this.errorCallback = errorCallback;- this.statusCallback = statusCallback;- this._duration = -1;- this._position = -1;- exec(null, this.errorCallback, "Media", "create", [this.id, this.src]);-};--// Media messages-Media.MEDIA_STATE = 1;-Media.MEDIA_DURATION = 2;-Media.MEDIA_POSITION = 3;-Media.MEDIA_ERROR = 9;--// Media states-Media.MEDIA_NONE = 0;-Media.MEDIA_STARTING = 1;-Media.MEDIA_RUNNING = 2;-Media.MEDIA_PAUSED = 3;-Media.MEDIA_STOPPED = 4;-Media.MEDIA_MSG = ["None", "Starting", "Running", "Paused", "Stopped"];--// "static" function to return existing objs.-Media.get = function(id) {- return mediaObjects[id];-};--/**- * Start or resume playing audio file.- */-Media.prototype.play = function(options) {- exec(null, null, "Media", "startPlayingAudio", [this.id, this.src, options]);-};--/**- * Stop playing audio file.- */-Media.prototype.stop = function() {- var me = this;- exec(function() {- me._position = 0;- }, this.errorCallback, "Media", "stopPlayingAudio", [this.id]);-};--/**- * Seek or jump to a new time in the track..- */-Media.prototype.seekTo = function(milliseconds) {- var me = this;- exec(function(p) {- me._position = p;- }, this.errorCallback, "Media", "seekToAudio", [this.id, milliseconds]);-};--/**- * Pause playing audio file.- */-Media.prototype.pause = function() {- exec(null, this.errorCallback, "Media", "pausePlayingAudio", [this.id]);-};--/**- * Get duration of an audio file.- * The duration is only set for audio that is playing, paused or stopped.- *- * @return duration or -1 if not known.- */-Media.prototype.getDuration = function() {- return this._duration;-};--/**- * Get position of audio.- */-Media.prototype.getCurrentPosition = function(success, fail) {- var me = this;- exec(function(p) {- me._position = p;- success(p);- }, fail, "Media", "getCurrentPositionAudio", [this.id]);-};--/**- * Start recording audio file.- */-Media.prototype.startRecord = function() {- exec(null, this.errorCallback, "Media", "startRecordingAudio", [this.id, this.src]);-};--/**- * Stop recording audio file.- */-Media.prototype.stopRecord = function() {- exec(null, this.errorCallback, "Media", "stopRecordingAudio", [this.id]);-};--/**- * Pause recording audio file.- */-Media.prototype.pauseRecord = function() {- exec(null, this.errorCallback, "Media", "pauseRecordingAudio", [this.id]);-};--/**-* Resume recording audio file.-*/-Media.prototype.resumeRecord = function() {- exec(null, this.errorCallback, "Media", "resumeRecordingAudio", [this.id]);-};--/**- * Release the resources.- */-Media.prototype.release = function() {- exec(null, this.errorCallback, "Media", "release", [this.id]);-};--/**- * Adjust the volume.- */-Media.prototype.setVolume = function(volume) {- exec(null, null, "Media", "setVolume", [this.id, volume]);-};--/**- * Adjust the playback rate.- */-Media.prototype.setRate = function(rate) {- if (cordova.platformId === 'ios'){- exec(null, null, "Media", "setRate", [this.id, rate]);- } else {- console.warn('media.setRate method is currently not supported for', cordova.platformId, 'platform.');- }-};--/**- * Get amplitude of audio.- */-Media.prototype.getCurrentAmplitude = function(success, fail) {- exec(function(p) {- success(p);- }, fail, "Media", "getCurrentAmplitudeAudio", [this.id]);-};--/**- * Audio has status update.- * PRIVATE- *- * @param id The media object id (string)- * @param msgType The 'type' of update this is- * @param value Use of value is determined by the msgType- */-Media.onStatus = function(id, msgType, value) {-- var media = mediaObjects[id];-- if (media) {- switch(msgType) {- case Media.MEDIA_STATE :- if (media.statusCallback) {- media.statusCallback(value);- }- if (value == Media.MEDIA_STOPPED) {- if (media.successCallback) {- media.successCallback();- }- }- break;- case Media.MEDIA_DURATION :- media._duration = value;- break;- case Media.MEDIA_ERROR :- if (media.errorCallback) {- media.errorCallback(value);- }- break;- case Media.MEDIA_POSITION :- media._position = Number(value);- break;- default :- if (console.error) {- console.error("Unhandled Media.onStatus :: " + msgType);- }- break;- }- } else if (console.error) {- console.error("Received Media.onStatus callback for unknown media :: " + id);- }--};--module.exports = Media;--function onMessageFromNative(msg) {- if (msg.action == 'status') {- Media.onStatus(msg.status.id, msg.status.msgType, msg.status.value);- } else {- throw new Error('Unknown media action' + msg.action);- }-}--if (cordova.platformId === 'android' || cordova.platformId === 'amazon-fireos' || cordova.platformId === 'windowsphone') {-- var channel = require('cordova/channel');-- channel.createSticky('onMediaPluginReady');- channel.waitForInitialization('onMediaPluginReady');-- channel.onCordovaReady.subscribe(function() {- exec(onMessageFromNative, undefined, 'Media', 'messageChannel', []);- channel.initializationComplete('onMediaPluginReady');- });-}--});diff --git a/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/MediaError.js b/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/MediaError.jsdeleted file mode 100644index 6c31335af..000000000--- a/cordova/platforms/android/platform_www/plugins/cordova-plugin-media/www/MediaError.js+++ /dev/null@@ -1,58 +0,0 @@-cordova.define("cordova-plugin-media.MediaError", function(require, exports, module) {-/*- *- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you 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.- *-*/--/**- * This class contains information about any Media errors.-*/-/*- According to :: http://dev.w3.org/html5/spec-author-view/video.html#mediaerror- We should never be creating these objects, we should just implement the interface- which has 1 property for an instance, 'code'-- instead of doing :- errorCallbackFunction( new MediaError(3,'msg') );-we should simply use a literal :- errorCallbackFunction( {'code':3} );- */-- var _MediaError = window.MediaError;---if(!_MediaError) {- window.MediaError = _MediaError = function(code, msg) {- this.code = (typeof code != 'undefined') ? code : null;- this.message = msg || ""; // message is NON-standard! do not use!- };-}--_MediaError.MEDIA_ERR_NONE_ACTIVE = _MediaError.MEDIA_ERR_NONE_ACTIVE || 0;-_MediaError.MEDIA_ERR_ABORTED = _MediaError.MEDIA_ERR_ABORTED || 1;-_MediaError.MEDIA_ERR_NETWORK = _MediaError.MEDIA_ERR_NETWORK || 2;-_MediaError.MEDIA_ERR_DECODE = _MediaError.MEDIA_ERR_DECODE || 3;-_MediaError.MEDIA_ERR_NONE_SUPPORTED = _MediaError.MEDIA_ERR_NONE_SUPPORTED || 4;-// TODO: MediaError.MEDIA_ERR_NONE_SUPPORTED is legacy, the W3 spec now defines it as below.-// as defined by http://dev.w3.org/html5/spec-author-view/video.html#error-codes-_MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = _MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED || 4;--module.exports = _MediaError;--});diff --git a/cordova/platforms/android/project.properties b/cordova/platforms/android/project.propertiesindex 49667a2af..93943886f 100644--- a/cordova/platforms/android/project.properties+++ b/cordova/platforms/android/project.properties@@ -11,4 +11,4 @@target=android-27android.library.reference.1=CordovaLibandroid.library.reference.2=app-cordova.system.library.1=com.android.support:support-v4:24.1.1+\ No newline at end of file+cordova.system.library.1=com.android.support:support-v4:27.+\ No newline at end of filediff --git a/cordova/yarn.lock b/cordova/yarn.lockindex ad46c1210..04da17552 100644--- a/cordova/yarn.lock+++ b/cordova/yarn.lock@@ -233,9 +233,10 @@ contains-path@^0.1.0:resolved "https://registry.yarnpkg.com/contains-path/-/contains-path-0.1.0.tgz#fe8cf184ff6670b6baef01a9d4861a5cbec4120a"integrity sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo=-"cordova-android@git+https://github.com/apache/cordova-android.git":- version "8.1.0-dev"- resolved "git+https://github.com/apache/cordova-android.git#576edb53bb5b6f9be4ffb1348f1efbeeb2968905"+cordova-android@^8.0.0:+ version "8.0.0"+ resolved "https://registry.yarnpkg.com/cordova-android/-/cordova-android-8.0.0.tgz#1fbe05a914731df619522b9385d4d1b183c36bdb"+ integrity sha512-Ipv8HbVJpxEyYFSFLTEOaLRp0yxBtJVNbgSuDEB4naa34FzQaRWSNiiMcPJnO+x3hRXNt7pcwa46hARNzhn7+w==dependencies:android-versions "^1.3.0"cordova-common "^3.1.0"@@ -264,30 +265,35 @@ cordova-common@^3.1.0:underscore "^1.8.3"which "^1.3.0"-cordova-plugin-camera@^4.0.3:- version "4.0.3"- resolved "https://registry.yarnpkg.com/cordova-plugin-camera/-/cordova-plugin-camera-4.0.3.tgz#7373a5938318c86ccfd84e3713e2382d10fe076b"- integrity sha1-c3Olk4MYyGzP2E43E+I4LRD+B2s=+cordova-plugin-background-mode@^0.7.3:+ version "0.7.3"+ resolved "https://registry.yarnpkg.com/cordova-plugin-background-mode/-/cordova-plugin-background-mode-0.7.3.tgz#066f92c99f403b3ed3d6fb91f281a0a7ccbc84ba"+ integrity sha512-LsU1v7EgTUROaks+tcQ8TnMzVUcU/TwjDVwj2O/4e4aI2q2ldLGsiZorqKqfqvwh2HoIssmY73OwJk91hQi62w==-cordova-plugin-device@^2.0.2:- version "2.0.2"- resolved "https://registry.yarnpkg.com/cordova-plugin-device/-/cordova-plugin-device-2.0.2.tgz#fc08f3722e67eef7b6c67bfc99a83df6add0baba"- integrity sha1-/Ajzci5n7ve2xnv8mag99q3Quro=+cordova-plugin-camera@^4.1.0:+ version "4.1.0"+ resolved "https://registry.yarnpkg.com/cordova-plugin-camera/-/cordova-plugin-camera-4.1.0.tgz#6474a3e080c4662aa00fd7425705d301c693ddc0"+ integrity sha512-fCLhWjWYn49q3X5xaypAPgTz6MAWSKFFQvD2Gpi5SuVlrRPRphtX2jIqR2zCBuDTBR082QVnlc+yUDXt65Mjgw==-cordova-plugin-file@^6.0.1:- version "6.0.1"- resolved "https://registry.yarnpkg.com/cordova-plugin-file/-/cordova-plugin-file-6.0.1.tgz#49606b8c15a5688d4728f92e4a7325a061de07f5"- integrity sha1-SWBrjBWlaI1HKPkuSnMloGHeB/U=--cordova-plugin-media@^5.0.2:- version "5.0.2"- resolved "https://registry.yarnpkg.com/cordova-plugin-media/-/cordova-plugin-media-5.0.2.tgz#3345769c07e6a46a71c97e1bb434dacca5c8d80b"- integrity sha1-M0V2nAfmpGpxyX4btDTazKXI2As=--cordova-plugin-whitelist@^1.3.3:- version "1.3.3"- resolved "https://registry.yarnpkg.com/cordova-plugin-whitelist/-/cordova-plugin-whitelist-1.3.3.tgz#b5e85ecdbbfe5aeded40a1bf4ee2372e67d96fb4"- integrity sha1-tehezbv+Wu3tQKG/TuI3LmfZb7Q=+cordova-plugin-device@^2.0.3:+ version "2.0.3"+ resolved "https://registry.yarnpkg.com/cordova-plugin-device/-/cordova-plugin-device-2.0.3.tgz#c2b41b7efd0455dd097f89356d85bfdd5dadeb0f"+ integrity sha512-Jb3V72btxf3XHpkPQsGdyc8N6tVBYn1vsxSFj43fIz9vonJDUThYPCJJHqk6PX6N4dJw6I4FjxkpfCR4LDYMlw==++cordova-plugin-file@^6.0.2:+ version "6.0.2"+ resolved "https://registry.yarnpkg.com/cordova-plugin-file/-/cordova-plugin-file-6.0.2.tgz#f3911479f8357e9aacb5576674f8d95b31a1fb20"+ integrity sha512-m7cughw327CjONN/qjzsTpSesLaeybksQh420/gRuSXJX5Zt9NfgsSbqqKDon6jnQ9Mm7h7imgyO2uJ34XMBtA==++cordova-plugin-media@^5.0.3:+ version "5.0.3"+ resolved "https://registry.yarnpkg.com/cordova-plugin-media/-/cordova-plugin-media-5.0.3.tgz#366188bd4f8472651c1e8304be649af6333b0e36"+ integrity sha512-UQPFlpk1zL4BY44zGi8RVmYCvcKBCN4Dyf8ovxqGYCC8zR1yhbTRWYDdO9vJdERwbfgWV7+z7FMWiSUfqWm9bQ==++cordova-plugin-whitelist@^1.3.4:+ version "1.3.4"+ resolved "https://registry.yarnpkg.com/cordova-plugin-whitelist/-/cordova-plugin-whitelist-1.3.4.tgz#31938545c7c3e7de35c20ab08c2c3afa06e8a3f9"+ integrity sha512-EYC5eQFVkoYXq39l7tYKE6lEjHJ04mvTmKXxGL7quHLdFPfJMNzru/UYpn92AOfpl3PQaZmou78C7EgmFOwFQQ==core-util-is@~1.0.0:version "1.0.2"