Compare commits

...

296 Commits

Author SHA1 Message Date
Joe Bowser
909e6645e7 Updating JS for Android 2013-04-25 14:55:11 -07:00
Joe Bowser
a308100288 Prep for 2.7.0 final 2013-04-25 13:42:20 -07:00
Joe Bowser
fea8c5d204 Merge branch '2.7.x' of https://git-wip-us.apache.org/repos/asf/cordova-android into 2.7.x 2013-04-25 10:20:07 -07:00
Joe Bowser
a890c8156e This should be 2.7.0rc1 2013-04-25 10:19:48 -07:00
Shravan Narayan
665c1bd8bb [CB-3226] Fix: plugins can intercept urls with "?", "#", "%20"(cherry picked from commit 53982272d6) 2013-04-25 13:11:02 -04:00
Joe Bowser
b22990ca78 cordova-js wasn't properly auto-incremented either 2013-04-19 17:56:26 -07:00
Joe Bowser
832998b67f 2.7.0rc1 prep 2013-04-18 13:05:03 -07:00
Andrew Grieve
c798d131bb Update JS snapshot for 2.7.0 2013-04-18 15:28:00 -04:00
Ian Clelland
bf3e024648 [CB-3066] Fire onNativeReady from JS, as bridge is available immediately 2013-04-18 14:20:32 -04:00
Andrew Grieve
191f31baa7 [CB-2432] Don't try and write exif info for images from picasa 2013-04-17 16:40:00 -04:00
Joe Bowser
d3b7903af8 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android 2013-04-17 13:37:48 -07:00
Joe Bowser
99e7d1e161 Merge branches 'sunshine' and 'master' 2013-04-17 13:37:19 -07:00
Andrew Grieve
b13166f5d9 [CB-2432] Fix Camera.getPicture() for picasa images 2013-04-17 16:12:28 -04:00
Andrew Grieve
80fe4458c6 Use FileHelper in IceCreamCordovaWebViewClient.
Removes some duplicate logic and makes it a bit more robust.
2013-04-17 15:51:37 -04:00
Andrew Grieve
791574c26e Make URL parsing more robust in FileHelper.
Fixes some cases when query parameters mess things up.
2013-04-17 15:50:29 -04:00
Joe Bowser
ac61ebf2d5 Merge branch 'master' of github.com:SunshineTech/cordova-android into sunshine 2013-04-17 11:44:49 -07:00
avidmich
cb99ed0a01 Fixing URL transformation algorithm
It didn't work with URL like this:
http://host.com/path/to/file.txt#/foo?bar=baz
When hash sign is in front of question mark - it only strips the question mark, leaving the hash and breaking the whole app.
2013-04-16 15:45:32 -04:00
Andrew Grieve
4864d52966 [CB-2202] Remove Plugin.java (was deprecated). 2013-04-16 15:29:16 -04:00
Andrew Grieve
b2d61679fb [CB-2963] Re-enable sending messages in batches.
Disabled by CB-1745, which is now reverted.
2013-04-16 15:04:56 -04:00
lorinbeer
383b3dadd5 [CB-3024] expanded help string for cl create script 2013-04-12 08:32:22 -07:00
Joe Bowser
c65c259123 CB-2200: Remove deprecated Android device.name 2013-04-11 13:53:12 -07:00
Joe Bowser
e7e2730929 Fixing CB-2955, breaking CB-2085, use localStorage, NOT WebSQL 2013-04-08 15:53:14 -07:00
Joe Bowser
bb9615eed0 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android 2013-04-04 16:06:03 -07:00
Joe Bowser
18877bf80e Adding additional condition that the phone must be made by HTC for the setNavDump to be set to true to try and work around CB-2907, if it's still a problem on HTC devices running Android 2.2, that's just the luck of the draw. 2013-04-04 16:05:35 -07:00
HUANG Menghuai
778b784eb6 [CB-2908] Fix the DroidGap activity Lifecycle broken issue
Attempting to invoke the Activity's finish() onDestroy breaks an Activity's lifecycle
flag. OnDestroy can be called by the system, for instance, on restarting an Activity,
it's definitely different from a normal finish().
Finish() incorrectly in onDestroy results in another DroidGap derived activity
is started, while the original one is not yet onDestroy. This issue could be
found when the system is trying to restart the activity upon, for instance,
receiving immediately successive device Config changes.
2013-04-04 16:47:03 -04:00
Andrew Grieve
5ff900f7ec Fixup for CB-2654. 2013-04-04 16:45:39 -04:00
Steren
ba31424604 Keep the splashscreen image ratio instead of streatching it.
An ImageView is used to be able to use ScaleType.CENTER_CROP, which is similar to the background-size:cover CSS property
2013-04-04 16:19:12 -04:00
Ian Clelland
1782111d45 [CB-2654] Delay executeScript/insertCSS callback until resources have loaded; pass JS results to callback 2013-04-04 14:34:58 -04:00
Max Woghiren
1fa63300aa [CB-2666] Added check for null arguments.
If null arguments are received, send an error and an explanation.
2013-04-02 11:51:25 -04:00
Joe Bowser
b42c918973 Prep for 2.6.0 final 2013-04-01 14:54:51 -07:00
Joe Bowser
f12262ea96 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android 2013-03-28 10:02:46 -07:00
Joe Bowser
334cf45d6d Fixing CB-1700, we had the file names reversed, so exif was never being written right. Needed to upload a file to debug this thing 2013-03-28 10:02:18 -07:00
Joe Bowser
b7bb72294a CB-1796: Let's make sure we actually write the file instead of just writing EXIF to NOTHING 2013-03-28 10:02:02 -07:00
Joe Bowser
64ff204371 Updating JS 2013-03-28 10:01:15 -07:00
Ian Clelland
282367c6d5 [CB-1517] Properly report download progress for GZIP-encoded resources 2013-03-27 17:00:22 -04:00
James Jong
36c33a5889 CB-1944: Better error messages for Create script
- fixed to detect missing packages individually
- added a specific message for each missing package
- messages include how to correct and package download link
2013-03-27 15:46:45 -04:00
JasonM23
5ee7e81ff9 [CB-51] Added httpMethod for upload (defaults to POST) 2013-03-27 14:22:41 -04:00
Shravan Narayan
f4859444dd Fixed protocol regex bug. Unknown protocol support Added whitelist support for unknown protocols 2013-03-26 00:20:11 -04:00
Andrew Grieve
73c7994cd1 Fix NPE in InAppBrowser.
When cordova.getActivity().getIntent().getExtras() == null.
2013-03-23 14:07:57 -04:00
Andrew Grieve
0c74090953 Log a message when exec() is made to an unregistered plugin. 2013-03-23 14:07:22 -04:00
Ian Clelland
f60d54eae4 [CB-2305] Add InAppBrowser injectSriptCode command to support InAppBrowser.executeScript and InAppBrowser.insertCSS APIs 2013-03-23 13:13:21 -04:00
Joe Bowser
31bc015cdd Pre-2.6 prep 2013-03-21 10:35:09 -07:00
mbillau
b028ad3604 CB-2675: Add prompt dialog to Notification API 2013-03-20 23:14:42 -04:00
Max Woghiren
d2e4e35c37 [CB-2715] Simplified readAsBinaryHelper.
Also fixed some comments and other minor things.
2013-03-20 22:42:29 -04:00
Ian Clelland
1f37200bb6 [CB-1957] Stop any playing media when closing InAppBrowser 2013-03-20 15:56:27 -04:00
Ian Clelland
77178daad3 [CB-2308] [android] Report errors when InAppBrowser fails to load page 2013-03-20 15:42:08 -04:00
Richard Burton
1648f161d9 Implemented a conditional check to support providing the duration limit for the Android platform SDK 8 and above. The value is passed using the string literal value to ensure the logic is not dependent on SDK version specifics. 2013-03-18 11:23:21 -04:00
Richard Burton
9fa6cea69b Implemented a conditional check to allow for the duration to be provided on the Android platform for SDK 8 and above. 2013-03-18 11:23:21 -04:00
Andrew Grieve
66b827e502 [CB-2632] Implement FileReader.readAsBinaryString 2013-03-15 16:47:33 -04:00
Andrew Grieve
7755a902dd Add a new type to the Native->JS bridge for binary strings.
It's needed since the bridge truncates strings that have null
characters in them :(.
2013-03-15 16:47:04 -04:00
Max Woghiren
d25b73f47d [CB-2546] Moved read calls to a background thread. 2013-03-15 16:01:02 -04:00
Max Woghiren
ac2969c3f8 [CB-2435] Split common methods out of FileUtils into FileHelpers
Also included in this change:
- Fixed getMimeType for content:// URIs.
- Made getRealPath take a URI string.
- Added basic android_asset handling.
There is no such thing as a "real path" for a file:///android_asset URI.  However, it is possible to get an input stream to one.

And even more minor changes:
- removed unused FileReader/FileWriter instance variables
- added logging when getRealPath fails
- fixed indentation issues
- removed a try/catch in favor of throwing
- removed a null check in favor of throwing
- moved getEntry back to FilePlugin
2013-03-14 12:39:51 -04:00
Dave E
ee38b2ef03 Use pushd/popd instead of subshell
Improves the error message that happens when ant is not installed.
2013-03-14 12:31:56 -04:00
Max Woghiren
0f70e04e6e [CB-1933] Changed button labels to an array.
This allows commas to be included in button label text.
2013-03-14 11:34:29 -04:00
Joe Bowser
9fc1e7272e CB-2668: Thanks for supplying a patch, but please make sure it actually builds. 2013-03-13 16:02:06 -07:00
Yavor Georgiev
0d4d0b8a37 Adding workaround for ICS asset URLs with spaces 2013-03-13 19:52:49 +02:00
Andrew Grieve
fcd2c989a2 [CB-2418] Fix geolocation's velocity field broken on Android 2013-03-12 20:54:24 -04:00
Simon MacDonald
e0d0d6c455 CB-2459: Customize InAppBrowser location bar 2013-03-10 10:33:42 -04:00
Simon MacDonald
ce1a961b99 CB-2640: Allow InAppBrowser to open tel, sms, market urls 2013-03-08 14:14:41 -05:00
Joe Bowser
c71a08a9d9 Merge branches 'leon' and 'master' 2013-03-07 13:06:10 -08:00
Joe Bowser
17bfcea65a Merge branch 'master' of git://github.com/sweetleon/cordova-android into leon 2013-03-07 11:20:43 -08:00
Joe Bowser
5e8959bab1 Removing baseURL because it doesn't actually do anything. If we want to make sure remote websites work, we whitelist them 2013-03-07 08:52:02 -08:00
Joe Bowser
9924dc0f92 So much for squashing, I should have branched this. 2013-03-06 15:31:25 -08:00
Joe Bowser
7388c036d7 Making framework only apply for http resources for now, so we don't break non-http handling. I had to squash this to make it pretty 2013-03-06 15:29:40 -08:00
Joe Bowser
ad4512801f Making framework only apply for http resources for now, so we don't break non-http handling 2013-03-06 15:26:13 -08:00
Joe Bowser
409b9af398 CB-2099: Android Whitelisting now blocks images and JS with an empty response 2013-03-06 14:56:27 -08:00
Braden Shepherdson
7cc8fd7e87 Allow plugins to capture shouldInterceptRequest() 2013-03-06 11:53:10 -05:00
Joe Bowser
42c8105f13 CB-2623: Updated windows script, now it works here too for once 2013-03-05 16:13:43 -08:00
Joe Bowser
9a71cc5b4e CB-2623: Added partial work on update script 2013-03-05 14:36:52 -08:00
Joe Bowser
c543b7469d CB-2623 Adding update script to Android 2013-03-05 11:30:38 -08:00
Joe Bowser
7caac3265a Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android 2013-03-04 16:09:55 -08:00
Joe Bowser
5d68d5a246 CB-2198: Removing option to use our broken URL stack as a history as per deprecation policy. 2013-03-04 16:09:37 -08:00
Braden Shepherdson
7187f87eae Add readAsBinaryString and readAsArrayBuffer support 2013-03-04 17:36:40 -05:00
Joe Bowser
fb81f3e77e CB-2596: Fixing the menubutton for text fields 2013-03-04 14:26:28 -08:00
lenny
0ae49ed098 moveFile handles absolute paths by not pre-pending anything to them 2013-03-01 22:11:29 -08:00
lenny
b8e5aaf754 ignore IntelliJ files 2013-03-01 21:56:57 -08:00
Tommy-Carlos Williams
aa4820c3b7 [CB-861] Header support for FileTransfer download
Added support for an optional options object as the final arg. Currently only handles the options.headers object (as per the issue).

`FileTransfer.download(source, target, successCallback, errorCallback, trustAllHosts, options)`

This is needed for using FileTransfer.download with Basic Authentication, etc. Sadly since Android 2.x doesn't support XHR2, this is needed in FileTransfer.

I have only added support to Android and iOS (see other PR's).
2013-02-28 13:10:59 -05:00
Joe Bowser
5d79d6e134 Merge branch 'next' 2013-02-27 11:07:55 -08:00
Joe Bowser
fb1455a17b Preparing to tag 2.5.0 2013-02-26 13:49:47 -08:00
Shravan Narayan
c668eeba0f Added CallbackContext success message with an int parameter
Added a small utility function to convert JSONArray to List<String>
2013-02-25 15:17:40 -05:00
Michal Mocny
62421ee49d CB-2530: Update callbackFromNative syntax to args
New callbackFromNative syntax expects an array of arguments instead of a
single message.
2013-02-25 13:28:26 -05:00
Joe Bowser
e791f29ce1 CB-2333: Probably should be re-factored as a do..while, but need to handle when there is no EOL char in buffer 2013-02-22 11:58:37 -08:00
Joe Bowser
06947cc453 CB-2333: Adding body property to FileTransferError object on Android 2013-02-22 11:48:17 -08:00
Joe Bowser
8c97474524 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android 2013-02-21 16:49:19 -08:00
Joe Bowser
77a8568b28 CB-2522: We used buttons in older versions to send the post, not the submit event. Disabled form saving 2013-02-21 16:48:57 -08:00
Braden Shepherdson
e2dadbd7fe Fix return types of getJSONObject and optJSONObject in CordovaArgs 2013-02-21 15:53:15 -05:00
Joe Bowser
17b668a115 CB-2085: Fixing deleted database for ChildBrowser 2013-02-21 11:53:06 -08:00
Joe Bowser
a30c2b6a75 CB-2504: Merged overscroll disallowance, needed to deal with merge conflict with the InAppStorage toggle 2013-02-21 10:45:50 -08:00
Joe Bowser
2660eebec2 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android 2013-02-21 10:31:00 -08:00
Max Woghiren
f415664b6d [CB-2504] Allow the disabling of overscroll glow. 2013-02-21 12:47:59 -05:00
Takeshi Sone
5092b29312 [CB-2518] Enable Geolocation in InAppBrowser 2013-02-21 09:07:06 -05:00
Joe Bowser
d5be901bc2 Merge branch 'next' 2013-02-20 13:53:15 -08:00
Joe Bowser
5462eddfdb Updating the JS for 2.5.0rc1 2013-02-20 13:52:29 -08:00
Joe Bowser
fef51f12c6 Apparently the JS was wrong when tagging 2013-02-20 13:06:13 -08:00
Joe Bowser
fdb3679cf5 Merge branch 'next' 2013-02-20 11:25:32 -08:00
Joe Bowser
11beb37c50 Setting to turn off Online Storage 2013-02-20 11:21:17 -08:00
Joe Bowser
5cd17730b1 Tagging 2.5.0rc1. Updating files 2013-02-19 11:53:36 -08:00
mbillau
cb192056f8 CB-2458: gracefully exit with back button
If users do extra initialization, we can get NPEs when hitting the back
button before loadUrl() has been called.
-Null fenced code in startOfHistory() that gave us an NPE when hitting
Back button with useBrowserHistory=true
-Call finish() in Back button code when no history since with
useBrowserHistory=true it would just hang while the app inits
-Call loadUrlIntoView() first in handleDestory() since with
useBrowserHistory=false, the default behavior would try to use the baseUrl
which is null
2013-02-18 16:42:14 -05:00
Joe Bowser
892f96e305 CB-2282: Turning on AppCache 2013-02-18 11:37:28 -08:00
Joe Bowser
13ef58a5bb Updated XML for the test project 2013-02-18 11:26:40 -08:00
SunshineTech
2bf6509e1d Modify Issue CB-2273. 2013-02-17 21:50:33 +08:00
Joe Bowser
a45d5a98dd CB-1605: Going through Eclipse warnings, removing the unused imports 2013-02-15 15:46:36 -08:00
Joe Bowser
a31714f8a4 CB-2447: This is a non-trivial task. Migrated test plugin to modern plugin API. 2013-02-15 14:25:56 -08:00
Joe Bowser
23d2a806f0 Merge branch 'CB-2447' of git://github.com/jamesjong/cordova-android 2013-02-15 14:02:23 -08:00
Joe Bowser
c20b2330ab CB-2446: Ugly, but workable fix 2013-02-15 13:57:34 -08:00
Fil Maj
8613551aec minor readme stuff 2013-02-15 13:18:03 -08:00
Fil Maj
2ab01dadc0 Adding link to cordova.io in readme 2013-02-15 13:12:19 -08:00
James Jong
790636c8cd CB-2447: Remove use of deprecate org.apache.cordova.api.Plugin 2013-02-15 13:18:58 -05:00
Andrew Grieve
23938830f7 [CB-2213] Add NATIVE_URI to the quick-return logic. 2013-02-14 10:50:37 -05:00
Benn Mapes
674b87057a [CB-2297] Fix for geolocaion database error 2013-02-12 14:23:01 -08:00
Richard Kolkovich
83d9248ec8 Update framework/src/org/apache/cordova/ContactAccessorSdk5.java
`Im.PROTOCOL` is a String, not an int. Treat it as such to prevent an Exception being thrown when parsing `null`.
2013-02-12 16:18:50 -05:00
Joe Bowser
f9d27e4a67 CB-2408: There should be a check for the browser history, but the logic intentionally doesn't match 2013-02-12 11:16:01 -08:00
patrick kettner
2683803ef3 Add check for build targets in create script
I installed the android sdk via homebrew, which does not install any build targets by default.

That resulted in the create throwing the following somewhat cryptic error.

An unexpected error occurred: "$ANDROID_BIN" create project --target $TARGET --path "$PROJECT_PATH" --package $PACKAGE --activity $ACTIVITY >&/dev/null exited with 1

This just adds a check that the variables that are set to the values of the build targets are properly set, and exit if they are not.
2013-02-12 11:07:51 -05:00
Andrew Grieve
dd86d7a5ed [CB-2095] Delete file on FileTransfer.download fail 2013-02-12 10:55:33 -05:00
Max Woghiren
1246a81d39 [CB-2213] Added NATIVE_URI support.
This is mostly the same as FILE_URI on Android.

Also replaced calls to `stripFileProtocol` with the more general-purpose `getRealPathFromURI`.  This helps support some operations on content URIs.
2013-02-11 22:45:14 -05:00
Andrew Grieve
8ab7278db2 Code clean-up of FileTransfer
- Fix warnings about toLowerCase()
- Don't assume connections are HTTP (fails for file://)
- Use StringBuilder
- Remove no-ops of disconnect() & keep-alive
2013-02-11 22:35:17 -05:00
Joe Bowser
db099e7722 Preparing for 2.4.0 2013-02-04 11:12:52 -08:00
Joe Bowser
fcc01bc37e Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android 2013-01-31 10:45:02 -08:00
Joe Bowser
a18dacf5f2 CB-2296 - Adding the screenshot configuration 2013-01-31 10:44:46 -08:00
Anis Kadri
77f9cae50b CB-1961 update to create script for android/windows 2013-01-30 14:57:49 -08:00
Joe Bowser
3610bbf21b CB-2296: Adding deprecation notices for removing the setProperties methods 2013-01-30 11:31:59 -08:00
Joe Bowser
d5e3be9a55 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android 2013-01-30 11:13:28 -08:00
Joe Bowser
80b369d6d5 CB-2296: Added parsing for Integer and Boolean parameters in config.xml 2013-01-30 11:13:07 -08:00
Andrew Grieve
d29eb84010 Tagging 2.4.0rc2 2013-01-30 09:51:40 -05:00
Joe Bowser
381ce535bf Merge branch 'puritytool' 2013-01-29 15:20:21 -08:00
Andrew Grieve
2e20bb0639 [CB-2293] Fix typo bufferSize->bytesRead.
Also adds a log statement to print out amount uploaded when an
IOException is thrown.
2013-01-29 13:47:15 -05:00
Joe Bowser
56cd24797e Fix for CB-2284. 401s are appearing when we hit them 2013-01-25 16:39:02 -08:00
Joe Bowser
431ca99c23 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android 2013-01-25 14:41:26 -08:00
Joe Bowser
6ced2ff293 CB-2292: Added a check for width and height. You can't scale nothing because you can't divide by zero. 2013-01-25 14:41:14 -08:00
Joe Bowser
31055bb303 Update to purity, adding better touch support 2013-01-25 14:39:44 -08:00
Fil Maj
24a53e39dd hey new line 2013-01-23 18:31:30 -08:00
Fil Maj
2ab113b695 Removing notice about incubation in the readme. 2013-01-23 12:21:49 -08:00
Fil Maj
9a0481a750 tweaking readme 2013-01-23 12:17:42 -08:00
Fil Maj
09035eb4c4 Setting template AndroidManifest values for version to 1.0 and code to 1. 2013-01-23 12:13:07 -08:00
Joe Bowser
1adf268e71 Updates to tests, including the use of Purity 2013-01-22 15:18:21 -08:00
Joe Bowser
23f57ad5a7 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android into puritytool 2013-01-21 14:59:04 -08:00
Joe Bowser
d9b15cf69e Updating with fixed JS from CB-2279 2013-01-21 13:47:26 -08:00
Joe Bowser
dbfe12a993 Partial fix for CB-2269, we probably shoudln't call Config.init twice 2013-01-18 16:41:10 -08:00
Joe Bowser
2b32dfd99d Partial Fix for CB-2269
* Moved Config.init call into DroidGap for the most common use-case
  * The CordovaWebView docuemntation still has to be updated
  * The template has to be changed, since we don't want to have two different types of config
2013-01-18 16:37:55 -08:00
Joe Bowser
679de40780 2.4.0rc1 updating 2013-01-18 15:33:38 -08:00
Joe Bowser
66f15fdd37 Adding purity to the test suite. Purity is a test class that may be renamed later 2013-01-18 15:00:02 -08:00
Joe Bowser
038f0e45b1 Upgrading Test Project properties to 4.2 2013-01-18 11:44:09 -08:00
Joe Bowser
033bfcc804 This should be Android 4.2, not Google APIs 2013-01-18 11:36:12 -08:00
Braden Shepherdson
fa87c08a29 Merge branch 'master' into arraybuffers 2013-01-18 12:33:25 -05:00
Braden Shepherdson
dfb799739a Change binaryEcho to echoArrayBuffer. 2013-01-18 12:32:52 -05:00
Joe Bowser
1193f7ed22 Fixed Android 4.2 filepicker, time for master 2013-01-17 17:00:50 -08:00
Braden Shepherdson
7530c21a9f Full binary data support.
- Removed BinaryEcho; made Echo support a new binaryEcho action.
- Added CordovaArgs wrapper for JSONArray, and a new overload for
  execute that accepts a CordovaArgs. There is now a default
  implementation for the JSONArray version of execute that builds a
  CordovaArgs and calls that version of execute. The default
  implementation for the CordovaArgs execute is to return false.
- Added byte[] version of success() in CallbackContext.
2013-01-17 15:58:38 -05:00
Simon MacDonald
a120614617 Initial input type=file support 2013-01-17 10:10:02 -05:00
Andrew Grieve
0311f0db38 CB-2208 Fix crash on File mobile-spec tests
Crash seems to not happen on every platform, but was showin up on the
x86 4.0.3 emulator.
2013-01-17 09:55:37 -05:00
Braden Shepherdson
547b683e61 Remove debugging. 2013-01-15 13:24:59 -05:00
Braden Shepherdson
ff1d943a69 Add CordovaArguments helper to decode ArrayBuffers 2013-01-15 13:21:09 -05:00
Braden Shepherdson
15a5c89e86 Removed debugging output. 2013-01-15 11:52:06 -05:00
Braden Shepherdson
03b974ee3f Working Base64 encoding. 2013-01-15 11:48:09 -05:00
Braden Shepherdson
f145605c63 Mostly working arraybuffer changes, needs Base64. 2013-01-15 11:16:32 -05:00
Joe Bowser
29230d0316 CB-2171: Patches are welcome. 2013-01-11 11:26:36 -08:00
Joe Bowser
57fc49ddc2 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android 2013-01-11 10:24:50 -08:00
Simon MacDonald
5ac6853fed CB-2154: navigator.splashscreen.show() broken in Phonegap 2.2 and 2.3.0rc2
Fixed the splashscreen so it will show for a minimum of 3 seconds if the user has not called loadUrl with a timeout in their main activity.
2013-01-11 10:24:03 -08:00
Fil Maj
b870214cca Fixes CB-2204: if bin/create fails, exit with code 1 2013-01-11 10:24:03 -08:00
Braden Shepherdson
55074b925f Added a comment to explain where the start page is getting set. 2013-01-11 10:24:03 -08:00
Braden Shepherdson
958424ce59 Add configurable start location to config.xml and template
Still possible to hardcode, there's a comment in the template showing
how that can be done.
2013-01-11 10:24:02 -08:00
Braden Shepherdson
d04fc289ac Move config.xml parsing into its own Config class
Now the parsing happens very early in the bootstrap process, before
loadUrl() is called. This enables a future change to put the start page
in config.xml instead of hardcoding it.
2013-01-11 10:24:02 -08:00
Braden Shepherdson
e14edf134d Merge branch 'master' into start_location 2013-01-11 12:13:43 -05:00
Simon MacDonald
dbb127447f CB-2154: navigator.splashscreen.show() broken in Phonegap 2.2 and 2.3.0rc2
Fixed the splashscreen so it will show for a minimum of 3 seconds if the user has not called loadUrl with a timeout in their main activity.
2013-01-10 22:06:39 -05:00
Fil Maj
dc94fc39ec Fixes CB-2204: if bin/create fails, exit with code 1 2013-01-10 18:29:36 -08:00
Joe Bowser
6db9a7cb12 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android into CordovaActivity 2013-01-10 16:26:24 -08:00
Benn Mapes
1f39386616 Fixed broken functions that were deprecated 2013-01-10 15:07:26 -08:00
Benn Mapes
25aef945d1 Deleted depricated methods 2013-01-10 14:51:20 -08:00
Joe Bowser
c9aa43afe0 CB-2185: Fixing getMimeType to get the mimetype of the file if it is upper-case 2013-01-10 11:32:37 -08:00
Braden Shepherdson
913e177f6f Added a comment to explain where the start page is getting set. 2013-01-09 17:36:12 -05:00
Braden Shepherdson
ae431aec12 Add configurable start location to config.xml and template
Still possible to hardcode, there's a comment in the template showing
how that can be done.
2013-01-09 16:48:43 -05:00
Braden Shepherdson
8ac15048cd Move config.xml parsing into its own Config class
Now the parsing happens very early in the bootstrap process, before
loadUrl() is called. This enables a future change to put the start page
in config.xml instead of hardcoding it.
2013-01-09 14:22:23 -05:00
Simon MacDonald
a1cfe87f1e CB-2093: NullPointerException when attaching image from Gallery that contains spaces in the path
Guarding against a null string being passed into FileUtils.getMimeType()
2013-01-08 21:10:50 -05:00
Simon MacDonald
c130396d4e Merge branch 'master' of http://git-wip-us.apache.org/repos/asf/cordova-android 2013-01-08 18:48:44 -05:00
Joe Bowser
bc2e7cf317 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android 2013-01-08 13:54:44 -08:00
Joe Bowser
7ace1d652d Fixing CB-2171, 0 byte file in filesystem on 404 from server. Patches are welcome. 2013-01-08 13:54:38 -08:00
Simon MacDonald
26effd1def Test for correctOrientation not rotate=0
when determining if we are in the special case where the image should just be retureturned to the user without modification.
2013-01-08 15:21:55 -05:00
Braden Shepherdson
5f6824e5dd Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/cordova-android into file_slicing 2013-01-07 18:13:54 -05:00
Braden Shepherdson
4589bdd31f And support for slicing in readAsDataURL. 2013-01-04 15:00:55 -05:00
Joe Bowser
72e0b49e0b Fixed CB-2089 after I tagged for the release. This will have to sit in 2.4.0 2013-01-03 10:18:41 -08:00
Joe Bowser
3caa45d860 Typo. Missed index.html in incrementation 2013-01-02 17:10:00 -08:00
Joe Bowser
7c069f14f8 Incrementing version to 2.3.0 final 2013-01-02 17:07:21 -08:00
Braden Shepherdson
552885dbd3 Add support for reading slices of text files. 2013-01-02 15:34:39 -08:00
Joe Bowser
6efeb1471c Incremeting version to 2.3.0rc2 2012-12-10 14:26:38 -08:00
Simon MacDonald
01f062d2ba Saving a contact with an email type of work sets it to home 2012-12-08 22:02:34 -05:00
Joe Bowser
2a42c463d2 CB-1973: We don't need to log three damn times! If it wasn't for HTC, I'd remove this entirely. 2012-12-06 10:40:57 -08:00
Joe Bowser
182843edf6 CB-1850 change: Model is getModel, name is getProduct 2012-12-05 14:58:47 -08:00
Simon MacDonald
9a9d36e9d9 CB-1969: Searching for emails in Contacts throws an exception always errors out 2012-12-05 16:28:27 -05:00
Simon MacDonald
7d5249eea6 Clean up warnings in InAppBrowser 2012-12-05 12:09:17 -05:00
Joe Bowser
f7910c41c3 Changing FILL_PARENT to MATCH_PARENT, removing Eclipse deprecation warnings 2012-12-04 14:14:19 -08:00
Joe Bowser
3973f4f952 More back button woes! The Fix for CB-1960 did weird things on both my end and Simon's end, sadly they're both different things. This should simply the code and resolve it. Sadly, all the unit tests pass as usual. 2012-12-04 12:06:05 -08:00
Joe Bowser
8a19769a47 Fix for CB-1960, we now check to see if any view is on the WebView, since they won't always be custom 2012-12-04 09:40:57 -08:00
Brian M Dube
c0ee593c10 [CB-1959] Display usage and exit when no arguments given 2012-12-02 21:21:24 -05:00
Andrew Grieve
c806451b8a Update Android SDK verions and commons-codec version in README.md. 2012-12-02 21:19:58 -05:00
Shazron Abdullah
00e5ff1964 Updated cordova.android.js for CB-1950 - InAppBrowser events 2012-11-30 05:47:37 -08:00
Shazron Abdullah
432aec62a9 [CB-1950] InAppBrowser - support events 2012-11-30 05:40:59 -08:00
Joe Bowser
c8ec7e5191 Doing the merge and fixing DroidGap up a bit 2012-11-28 15:30:22 -08:00
Joe Bowser
a0d2b96de6 Merge commit and hacking on CordovaWebView 2012-11-28 15:10:36 -08:00
Joe Bowser
2c202b82d7 Partial Fix/Workaround for CB-1856. Also removed old deprecated code 2012-11-28 14:42:55 -08:00
Simon MacDonald
a42dc08756 Start adding events to InAppBrowser 2012-11-28 15:44:01 -05:00
Simon MacDonald
48f58110fe CB-1938: Regression, Android back button event is no longer fired 2012-11-27 12:18:49 -05:00
Simon MacDonald
7b3724972b Tagging to 2.3.0rc1 2012-11-26 16:09:52 -05:00
Simon MacDonald
9ca2a16218 Updating JS so that InAppBrowser will work out of the box 2012-11-23 09:38:49 -05:00
Simon MacDonald
f1e8400abf Merge branch 'master' of http://git-wip-us.apache.org/repos/asf/cordova-android 2012-11-22 22:28:34 -05:00
Andrew Grieve
11e0ffa90a Add @JavascriptInterface annotations to ExposedJsApi.
And re-enable the JS bridge on 4.2.
https://issues.apache.org/jira/browse/CB-1879
2012-11-22 22:23:51 -05:00
Anis Kadri
2ee4326a4d updating create command 2012-11-22 22:23:51 -05:00
Anis Kadri
226e72ac18 adding release command 2012-11-22 22:23:51 -05:00
Anis Kadri
65c78b8f3f removing ApplicationInfo.class 2012-11-22 22:23:51 -05:00
Anis Kadri
6137c7ca06 removing appinfo.jar 2012-11-22 22:23:51 -05:00
Simon MacDonald
5bebf11b37 CB-1888: Can't add a Photo from a HTTPS address to Contact 2012-11-22 22:23:51 -05:00
Anis Kadri
68161d2714 refactoring windows scripts 2012-11-22 22:23:51 -05:00
Anis Kadri
a6473cb826 adding install function 2012-11-22 22:23:51 -05:00
Anis Kadri
0084c6f96a refactoring android commands 2012-11-22 22:23:51 -05:00
Simon MacDonald
a87825dbee CB-1508: Implement InAppBrowser feature
Initial checkin. Need to clean up the UI and add eventing.
2012-11-22 22:21:24 -05:00
Andrew Grieve
3566154cd0 Add @JavascriptInterface annotations to ExposedJsApi.
And re-enable the JS bridge on 4.2.
https://issues.apache.org/jira/browse/CB-1879
2012-11-22 12:39:18 -05:00
Anis Kadri
92d69e320f updating create command 2012-11-21 16:35:27 -08:00
Anis Kadri
08a190ef5b adding release command 2012-11-21 16:35:16 -08:00
Anis Kadri
98339ee5d8 removing ApplicationInfo.class 2012-11-21 13:37:19 -08:00
Anis Kadri
fa387fd758 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-cordova-android 2012-11-21 13:33:21 -08:00
Anis Kadri
54979f2fc4 removing appinfo.jar 2012-11-21 13:33:09 -08:00
Simon MacDonald
538e90f23a CB-1888: Can't add a Photo from a HTTPS address to Contact 2012-11-21 11:27:25 -05:00
Anis Kadri
d9107bcac6 refactoring windows scripts 2012-11-20 18:49:16 -08:00
Anis Kadri
3f3a0b9140 adding install function 2012-11-20 14:49:49 -08:00
Anis Kadri
e1347e434e refactoring android commands 2012-11-20 14:39:37 -08:00
Joe Bowser
7657faa9c3 CB-1852: Android version of model implemented, too bad it's all code names and not human readable 2012-11-19 13:26:22 -08:00
Joe Bowser
28ef765913 Upgrading App plugin to CordovaPlugin 2012-11-19 11:33:21 -08:00
Joe Bowser
d2f59391a2 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-cordova-android 2012-11-19 10:36:45 -08:00
Joe Bowser
df90bdb350 Fixing up the tests so they crash less. 2012-11-19 10:36:26 -08:00
Joe Bowser
c416c77d7a Fix for CB-1879 by Tom Clarkson. Hacked in due to lack of pull request 2012-11-19 10:35:47 -08:00
Andrew Grieve
ce05a720d1 Update .gitignore 2012-11-16 15:41:38 -05:00
Joe Bowser
6c19a440f5 CB-1864: Figured out how to simulate back button, test both the CordovaWebView back button and the general DroidGap case using the default implementation 2012-11-15 16:04:09 -08:00
Joe Bowser
f4612fdb5d Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-cordova-android 2012-11-15 13:48:15 -08:00
Joe Bowser
04b9a0b09e Death to tabs while working on CB-1864 2012-11-15 13:47:52 -08:00
Simon MacDonald
f93c438067 CB-1860: NPE in onReceivedError with non local errorUrl 2012-11-15 11:04:50 -05:00
Joe Bowser
e1d608443a Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-cordova-android 2012-11-14 13:23:35 -08:00
Joe Bowser
9233c3a898 Fixing error with the tests, backbuttonmultipage wasn't added 2012-11-14 13:22:58 -08:00
Simon MacDonald
dfa514334b Bumping Android API version to 17 2012-11-14 16:05:50 -05:00
Joe Bowser
5810a96e62 Adding reflection so that this compiles, need to test against HTC Desire HD 2.3.6 device before resolving CB-1845 2012-11-14 11:15:22 -08:00
Joe Bowser
70473a80af Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-cordova-android 2012-11-13 14:31:33 -08:00
Joe Bowser
525fd30cb2 Merge branch 'Android_2.3.4_camera_crash' of git://github.com/IuriiO/incubator-cordova-android into null_camera 2012-11-13 11:37:40 -08:00
Andrew Grieve
5212cd4dcd Disable JS Interface on Honeycomb
Fixes https://issues.apache.org/jira/browse/CB-1818
2012-11-13 12:50:15 -05:00
Simon MacDonald
e95bde62a2 Correctly report the mime type of 3ga files 2012-11-12 10:22:35 -05:00
Simon MacDonald
4fe73cf6ad CB-1835: Camera.getPicture gives error when get a picture from photo library with spaces in its name on Android 2012-11-12 10:00:32 -05:00
Simon MacDonald
78b2835da4 Merge branch 'master' of https://github.com/ilbambino/incubator-cordova-android 2012-11-12 09:57:19 -05:00
Iurii Okhmat
f9a49efae9 Removed unnecessary import. 2012-11-09 16:44:33 -08:00
Iurii Okhmat
b9ddc9e678 Camera plugin (HTC Incredible) is crashing on 2.3.4 devices without SD card 2012-11-09 16:40:56 -08:00
Simon MacDonald
dc459c84a3 CB-1829: Online/Offline events do not fire on subsequent pages of an app 2012-11-09 11:28:50 -05:00
Alvaro
1d26239809 not getting the path correctly if the URI contains a file://
Previous to 2.2 this function was crashing if the URI wasn't different
than a 'content://' but still if it is a 'file://' it fails getting the
correct path.
This happens for example picking a picture from dropbox instead of
local gallery.
2012-11-09 09:28:26 +02:00
Joe Bowser
5ca233779d This is as far as we can get fixing the Camera plugin by recovering state 2012-11-08 15:42:28 -08:00
Simon MacDonald
e51b4897a3 Guard against null mimeType in MediaFile.getFormatData 2012-11-08 14:01:46 -05:00
Anis Kadri
81f283e56f CB-1794 fixing cordova commands for paths with spaces in them 2012-11-07 13:22:14 -08:00
Anis Kadri
ccdd2fd2ca CB-1809 create script should print out meaningful error messages 2012-11-05 17:51:32 -08:00
Joe Bowser
69f11a29e1 Updating the project so that the activities are clearly separated from Test and Helper code 2012-11-02 16:15:51 -07:00
Joe Bowser
cf494f3238 Fixing the tests so that they run as an Activity again 2012-11-02 13:48:05 -07:00
Joe Bowser
d5895c635a Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-cordova-android 2012-11-02 13:33:13 -07:00
Simon MacDonald
2ac9873613 CB-1808: FileEntry.moveTo across file systems incorrectly calls the success callback 2012-11-02 14:50:24 -04:00
Joe Bowser
eb59e76cde Fixing CB-1801 2012-11-01 12:23:18 -07:00
Simon MacDonald
d9db845b43 CB-1795: onCreateOptionsMenu in PhoneGap 2.2.0 Release Candidate 2 isn't working anymore 2012-11-01 10:30:34 -04:00
Joe Bowser
e55327b064 Tagging the 2.2.0 release after this commit 2012-10-31 10:57:57 -07:00
Simon MacDonald
bdd5a4e053 Merge branch 'master' of http://git-wip-us.apache.org/repos/asf/incubator-cordova-android
Somedays, I hate git.
2012-10-29 16:23:36 -04:00
Andrew Grieve
ac2e2c9a42 Update JS to new tag (again). Includes latest fix to CB-1745. 2012-10-29 16:21:12 -04:00
Andrew Grieve
76f9d49e24 Disable limiting of payload size when sending data to JS.
Fixes https://issues.apache.org/jira/browse/CB-1745
2012-10-29 16:21:12 -04:00
Andrew Grieve
6ec8ab95fc Update JS to new 2.2.0rc2 tag. 2012-10-29 16:21:12 -04:00
Joe Bowser
9c98625610 Partial fix for CB-1742, still don't know what this should do for notification.confirm's cancel, so we return zero for now 2012-10-29 16:21:12 -04:00
Joe Bowser
f270cde47d Changing DroidGap back and duplicating code so that we don't have a regression on CB-1568 2012-10-29 16:21:12 -04:00
Joe Bowser
9de7efd072 Added fix for webViewClient. CB-1568 2012-10-29 16:21:12 -04:00
Joe Bowser
7b81d317a0 Moved the initialization of the IceCreamWebViewClient to CordovaWebView, we weren't loading the fix in properly after the refactor - CB-1742 2012-10-29 16:21:12 -04:00
Simon MacDonald
876f975aa2 CB-1691: Android menu button event doesn't fire when textbox has focus 2012-10-29 16:20:39 -04:00
Andrew Grieve
3c5815ac0f Update JS to new tag (again). Includes latest fix to CB-1745. 2012-10-26 16:09:54 -04:00
Andrew Grieve
678ae2d684 Disable limiting of payload size when sending data to JS.
Fixes https://issues.apache.org/jira/browse/CB-1745
2012-10-26 16:08:35 -04:00
Andrew Grieve
e4f8f44fb0 Update JS to new 2.2.0rc2 tag. 2012-10-26 10:41:08 -04:00
Joe Bowser
49566d29f8 Partial fix for CB-1742, still don't know what this should do for notification.confirm's cancel, so we return zero for now 2012-10-25 14:13:17 -07:00
Joe Bowser
7f4ee7b20a Changing DroidGap back and duplicating code so that we don't have a regression on CB-1568 2012-10-25 13:18:28 -07:00
Joe Bowser
32526a8c16 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-cordova-android 2012-10-25 12:17:58 -07:00
Joe Bowser
71a7f72ab9 Added fix for webViewClient. CB-1568 2012-10-25 12:17:38 -07:00
Joe Bowser
4d0824f4a4 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-cordova-android 2012-10-25 12:12:47 -07:00
Joe Bowser
d56dd40d06 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-cordova-android 2012-10-25 12:11:41 -07:00
Joe Bowser
6aafd6dc3a Moved the initialization of the IceCreamWebViewClient to CordovaWebView, we weren't loading the fix in properly after the refactor - CB-1742 2012-10-25 12:11:09 -07:00
Andrew Grieve
011b512f28 Update JS. 2012-10-25 15:02:26 -04:00
Andrew Grieve
aa2d17e489 Disable JS_OBJECT bridge on pre-gingerbread devices.
It's the easiest way to avoid bugs with Java strings not being converted
to JS Strings.
2012-10-25 15:00:21 -04:00
Andrew Grieve
0eee2293dc Add support for null PluginResult payloads.
https://issues.apache.org/jira/browse/CB-1744
2012-10-25 12:05:39 -04:00
Simon MacDonald
a2f35d2bda CB-1743: Globalization.getDateNames will crash Android 2.2 applications 2012-10-25 10:35:22 -04:00
Simon MacDonald
58f58d9ee8 Merge branch 'master' of http://git-wip-us.apache.org/repos/asf/incubator-cordova-android
Conflicts:
	framework/assets/js/cordova.android.js
2012-10-24 16:32:01 -04:00
Simon MacDonald
412bb349ac Pull in exec fix for Android 2.2 2012-10-24 16:29:26 -04:00
Simon MacDonald
652f15f893 Guard against NullPointerException in Compasslistenter 2012-10-24 16:29:02 -04:00
Joe Bowser
8512ebb923 Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-cordova-android 2012-10-24 12:07:20 -07:00
Joe Bowser
f0ac173ec8 Adding the updated blank index 2012-10-24 12:06:37 -07:00
Joe Bowser
bef0d47924 Starting incrementing the tag to RC2 2012-10-24 12:06:00 -07:00
Bryce Curtis
cba0d59021 Fix exception when plugin returns a null string. 2012-10-24 12:36:30 -06:00
Andrew Grieve
7d3afcab94 Tweak the useBrowserHistory deprecation message to make the date is clear 2012-10-23 14:12:48 -04:00
Joe Bowser
5f1cda07e7 Cleaning up code, because negating string comparisons is confusing if the string itself is called false. Also clarified the deprecation message to match the Cordova policy that we agreed on for deprecation changes 2012-10-23 10:46:53 -07:00
Joe Bowser
e11beade4b Merge branch 'master' of https://git-wip-us.apache.org/repos/asf/incubator-cordova-android 2012-10-23 10:25:33 -07:00
Andrew Grieve
6a1e089b73 Change useBrowserHistory to default to true (actually)
Also logs a deprecation mession on start-up when it is set to false.
Fixes issue: https://issues.apache.org/jira/browse/CB-1611
2012-10-23 13:15:44 -04:00
Simon MacDonald
0aa98ac2da CB-1697: openDatabase of Cordova for Android uses the wrong directory separator 2012-10-22 13:50:16 -04:00
Joe Bowser
f9ef38cc7a Updating the config.xml default to be true. See discussion on CB-1611 2012-10-19 07:23:55 -07:00
Simon MacDonald
a3a215a1ba Merge in video tag changes and fix back button issue 2012-10-17 10:14:30 -04:00
Steren Giannini
06aafc96c9 Play <video> tags from the Webview in a Fullscreen video player.
Code from the Froyo Android Browser was adapted to support <video> elements in Cordova. The WebView creates a "CustomView" (a video player) that is displayed fullscreen.
It uses API level 7, work has to be done to support lower version.

Tested on Androdi 2.2: works
Tested on Android 4.1: doesn't work. It seems videos are handled differently (without the use of "Custom views"). To make video playing work on Android 4, add the android:hardwareAccelerated="true" attribute to the main activity of the AndroidManifest.
2012-08-14 18:13:35 +02:00
105 changed files with 12098 additions and 2490 deletions

22
.gitignore vendored
View File

@@ -4,28 +4,32 @@ gen
assets/www/cordova.js
framework/assets/www/.tmp*
local.properties
framework/proguard.cfg
framework/cordova.jar
framework/cordova-*.jar
framework/phonegap-*.jar
framework/lib
proguard.cfg
proguard.cfg
proguard-project.txt
framework/bin
framework/test/org/apache/cordova/*.class
framework/assets/www/.DS_Store
framework/assets/www/cordova-*.js
framework/assets/www/phonegap-*.js
framework/libs
test/libs
example
./test
test/bin
test/assets/www/.tmp*
tmp/**
*.tmp
test/libs/*.jar
bin/node_modules
.metadata
*.bak
tmp/**/*
*.swp
Thumbs.db
Desktop.ini
*.tmp
*.bak
*.swp
*.class
*.jar
# IntelliJ IDEA files
*.iml
.idea

View File

@@ -1,16 +1,12 @@
Cordova Android
===
Cordova Android is an Android application library that allows for Cordova based projects to be built for the Android Platform. Cordova based applications are, at the core, an application written with web technology: HTML, CSS and JavaScript.
Cordova Android is an Android application library that allows for Cordova-based
projects to be built for the Android Platform. Cordova based applications are,
at the core, applications written with web technology: HTML, CSS and JavaScript.
[Apache Cordova](http://cordova.io) is a project at The Apache Software Foundation (ASF).
Apache Cordova is an effort undergoing incubation at The Apache
Software Foundation (ASF), sponsored by the Apache Incubator project.
Incubation is required of all newly accepted projects until a further
review indicates that the infrastructure, communications, and decision
making process have stabilized in a manner consistent with other
successful ASF projects. While incubation status is not necessarily
a reflection of the completeness or stability of the code, it does
indicate that the project has yet to be fully endorsed by the ASF.
Requires
---
@@ -27,13 +23,13 @@ Test Requirements
Building
---
To create your cordova.jar, copy the commons codec:
To create your `cordova.jar` file, copy the commons codec:
mv commons-codec-1.6.jar framework/libs
mv commons-codec-1.7.jar framework/libs
then run in the framework directory:
android update project -p . -t android-16
android update project -p . -t android-17
ant jar

View File

@@ -1 +1 @@
2.2.0rc1
2.7.0

View File

@@ -23,10 +23,13 @@
#
set -e
if [ -n "$1" ] && [ "$1" == "-h" ]
if [ -z "$1" ] || [ "$1" == "-h" ]
then
echo 'usage: create path package activity'
echo "Usage: $0 <path_to_new_project> <package_name> <project_name>"
echo "Make sure the Android SDK tools folder is in your PATH!"
echo " <path_to_new_project>: Path to your new Cordova iOS project"
echo " <package_name>: Package name, following reverse-domain style convention"
echo " <project_name>: Project name"
exit 0
fi
@@ -59,19 +62,21 @@ function on_exit {
}
function createAppInfoJar {
(cd "$BUILD_PATH"/bin/templates/cordova/ApplicationInfo &&
javac ApplicationInfo.java &&
jar -cfe ../appinfo.jar ApplicationInfo ApplicationInfo.class
)
pushd "$BUILD_PATH"/bin/templates/cordova/ApplicationInfo > /dev/null
javac ApplicationInfo.java
jar -cfe ../appinfo.jar ApplicationInfo ApplicationInfo.class
popd > /dev/null
}
function on_error {
echo "An error occurred. Deleting project..."
echo "An unexpected error occurred: $previous_command exited with $?"
echo "Deleting project..."
[ -d "$PROJECT_PATH" ] && rm -rf "$PROJECT_PATH"
exit 1
}
function replace {
local pattern=$1
local pattern=$1
local filename=$2
# Mac OS X requires -i argument
if [[ "$OSTYPE" =~ "darwin" ]]
@@ -84,6 +89,7 @@ function replace {
}
# we do not want the script to silently fail
trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
trap on_error ERR
trap on_exit EXIT
@@ -95,10 +101,17 @@ MANIFEST_PATH="$PROJECT_PATH"/AndroidManifest.xml
TARGET=$("$ANDROID_BIN" list targets | grep id: | tail -1 | cut -f 2 -d ' ' )
API_LEVEL=$("$ANDROID_BIN" list target | grep "API level:" | tail -n 1 | cut -f 2 -d ':' | tr -d ' ')
# check that build targets exist
if [ -z "$TARGET" ] || [ -z "$API_LEVEL" ]
then
echo "No Android Targets are installed. Please install at least one via the android SDK"
exit 1
fi
# if this a distribution release no need to build a jar
if [ ! -e "$BUILD_PATH"/cordova-$VERSION.jar ] && [ -d "$BUILD_PATH"/framework ]
then
# update the cordova-android framework for the desired target
# update the cordova-android framework for the desired target
"$ANDROID_BIN" update project --target $TARGET --path "$BUILD_PATH"/framework &> /dev/null
if [ ! -e "$BUILD_PATH"/framework/libs/commons-codec-1.7.jar ]; then
@@ -111,8 +124,10 @@ then
rm commons-codec-1.7-bin.zip && rm -rf commons-codec-1.7
fi
# compile cordova.js and cordova.jar
(cd "$BUILD_PATH"/framework && ant jar &> /dev/null )
# compile cordova.js and cordova.jar
pushd "$BUILD_PATH"/framework > /dev/null
ant jar > /dev/null
popd > /dev/null
fi
# create new android project
@@ -144,13 +159,13 @@ replace "s/__ACTIVITY__/${ACTIVITY}/g" "$MANIFEST_PATH"
replace "s/__PACKAGE__/${PACKAGE}/g" "$MANIFEST_PATH"
replace "s/__APILEVEL__/${API_LEVEL}/g" "$MANIFEST_PATH"
# creating cordova folder and copying emulate/debug/log/launch scripts
# creating cordova folder and copying run/build/log/launch scripts
mkdir "$PROJECT_PATH"/cordova
createAppInfoJar
cp "$BUILD_PATH"/bin/templates/cordova/appinfo.jar "$PROJECT_PATH"/cordova/appinfo.jar
cp "$BUILD_PATH"/bin/templates/cordova/cordova "$PROJECT_PATH"/cordova/cordova
cp "$BUILD_PATH"/bin/templates/cordova/debug "$PROJECT_PATH"/cordova/debug
cp "$BUILD_PATH"/bin/templates/cordova/build "$PROJECT_PATH"/cordova/build
cp "$BUILD_PATH"/bin/templates/cordova/release "$PROJECT_PATH"/cordova/release
cp "$BUILD_PATH"/bin/templates/cordova/clean "$PROJECT_PATH"/cordova/clean
cp "$BUILD_PATH"/bin/templates/cordova/log "$PROJECT_PATH"/cordova/log
cp "$BUILD_PATH"/bin/templates/cordova/emulate "$PROJECT_PATH"/cordova/emulate
cp "$BUILD_PATH"/bin/templates/cordova/BOOM "$PROJECT_PATH"/cordova/BOOM
cp "$BUILD_PATH"/bin/templates/cordova/run "$PROJECT_PATH"/cordova/run

View File

@@ -16,17 +16,37 @@
:: under the License.
@ECHO OFF
IF NOT DEFINED JAVA_HOME GOTO MISSING
IF NOT DEFINED JAVA_HOME GOTO MISSING_JAVA_HOME
FOR %%X in (java.exe javac.exe ant.bat android.bat) do (
SET FOUND=%%~$PATH:X
IF NOT DEFINED FOUND GOTO MISSING
IF [%%~$PATH:X]==[] (
ECHO Cannot locate %%X using the PATH environment variable.
ECHO Retry after adding directory containing %%X to the PATH variable.
ECHO Remember to open a new command window after updating the PATH variable.
IF "%%X"=="java.exe" GOTO GET_JAVA
IF "%%X"=="javac.exe" GOTO GET_JAVA
IF "%%X"=="ant.bat" GOTO GET_ANT
IF "%%X"=="android.bat" GOTO GET_ANDROID
GOTO ERROR
)
)
cscript "%~dp0\create.js" %*
GOTO END
:MISSING
ECHO Missing one of the following:
ECHO JDK: http://java.oracle.com
ECHO Android SDK: http://developer.android.com
ECHO Apache ant: http://ant.apache.org
:MISSING_JAVA_HOME
ECHO The JAVA_HOME environment variable is not set.
ECHO Set JAVA_HOME to an existing JRE directory.
ECHO Remember to also add JAVA_HOME to the PATH variable.
ECHO After updating system variables, open a new command window and retry.
GOTO ERROR
:GET_JAVA
ECHO Visit http://java.oracle.com if you need to install Java (JDK).
GOTO ERROR
:GET_ANT
ECHO Visit http://ant.apache.org if you need to install Apache Ant.
GOTO ERROR
:GET_ANDROID
ECHO Visit http://developer.android.com if you need to install the Android SDK.
GOTO ERROR
:ERROR
EXIT /B 1
:END

View File

@@ -33,12 +33,22 @@ function read(filename) {
f.Close();
return s;
}
function checkTargets(targets) {
if(!targets) {
WScript.Echo("You do not have any android targets setup. Please create at least one target with the `android` command");
WScript.Quit(69);
}
}
function setTarget() {
var targets = shell.Exec('android.bat list targets').StdOut.ReadAll().match(/id:\s\d+/g);
checkTargets(targets);
return targets[targets.length - 1].replace(/id: /, ""); // TODO: give users the option to set their target
}
function setApiLevel() {
var targets = shell.Exec('android.bat list targets').StdOut.ReadAll().match(/API level:\s\d+/g);
checkTargets(targets);
return targets[targets.length - 1].replace(/API level: /, "");
}
function write(filename, contents) {
@@ -198,10 +208,9 @@ exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\appinfo.jar ' + PRO
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\cordova.js ' + PROJECT_PATH + '\\cordova\\cordova.js /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\cordova.bat ' + PROJECT_PATH + '\\cordova\\cordova.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\clean.bat ' + PROJECT_PATH + '\\cordova\\clean.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\debug.bat ' + PROJECT_PATH + '\\cordova\\debug.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\build.bat ' + PROJECT_PATH + '\\cordova\\build.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\log.bat ' + PROJECT_PATH + '\\cordova\\log.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\emulate.bat ' + PROJECT_PATH + '\\cordova\\emulate.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\BOOM.bat ' + PROJECT_PATH + '\\cordova\\BOOM.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\run.bat ' + PROJECT_PATH + '\\cordova\\run.bat /Y');
// interpolate the activity name and package
WScript.Echo("Updating AndroidManifest.xml and Main Activity...");

View File

@@ -21,4 +21,4 @@ set -e
CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd )
bash $CORDOVA_PATH/cordova emulate
bash "$CORDOVA_PATH"/cordova build

View File

@@ -15,4 +15,4 @@
:: specific language governing permissions and limitations
:: under the License.
%~dp0\cordova.bat BOOM
%~dp0\cordova.bat build

View File

@@ -21,4 +21,4 @@ set -e
CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd )
bash $CORDOVA_PATH/cordova clean
bash "$CORDOVA_PATH"/cordova clean

View File

@@ -17,12 +17,12 @@
#!/bin/bash
set -e
PROJECT_PATH=$( cd "$( dirname "$0" )/.." && pwd )
function check_devices {
local devices=`adb devices | awk '/List of devices attached/ { while(getline > 0) { print }}'`
# FIXME
local devices=`adb devices | awk '/List of devices attached/ { while(getline > 0) { print }}' | grep device`
if [ -z "$devices" ] ; then
echo "1"
else
@@ -37,7 +37,6 @@ function emulate {
# Do not launch an emulator if there is already one running or if a device is attached
if [ $(check_devices) == 0 ] ; then
echo "Device attached or emulator already running"
return
fi
@@ -62,8 +61,9 @@ function emulate {
do
echo "$i) ${avd_list[$i]}"
done
echo -n "> "
read avd_id
read -t 5 -p "> " avd_id
# default value if input timeout
if [ $avd_id -eq 1000 ] ; then avd_id=0 ; fi
done
emulator -cpu-delay 0 -no-boot-anim -cache /tmp/cache -avd ${avd_list[$avd_id]} 1> /dev/null 2>&1 &
fi
@@ -78,25 +78,82 @@ function log {
adb logcat
}
function debug {
if [ $(check_devices) == 0 ] ; then
ant debug install
function run {
clean && emulate && wait_for_device && install && launch
}
function install {
declare -a devices=($(adb devices | awk '/List of devices attached/ { while(getline > 0) { print }}' | grep device | cut -f 1))
local device_id="1000" #FIXME: hopefully user does not have 1000 AVDs
if [ ${#devices[@]} == 0 ]
then
# should not reach here. Emulator should launch or device should be attached
echo "Emulator not running or device not attached. Could not install debug package"
exit 70
fi
if [ ${#devices[@]} == 1 ]
then
export ANDROID_SERIAL=${devices[0]}
# User has more than 1 AVD
elif [ ${#devices[@]} -gt 1 ]
then
while [ -z ${devices[$device_id]} ]
do
echo "Choose from one of the following devices/emulators [0 to $((${#devices[@]}-1))]:"
for(( i = 0 ; i < ${#devices[@]} ; i++ ))
do
echo "$i) ${devices[$i]}"
done
read -t 5 -p "> " device_id
# default value if input timeout
if [ $device_id -eq 1000 ] ; then device_id=0 ; fi
done
export ANDROID_SERIAL=${devices[$device_id]}
fi
ant debug install
}
function build {
ant debug
}
function release {
ant release
}
function wait_for_device {
local i="0"
echo -n "Waiting for device..."
while [ $i -lt 300 ]
do
if [ $(check_devices) -eq 0 ]
then
break
else
sleep 1
i=$[i+1]
echo -n "."
fi
done
# Device timeout: emulator has not started in time or device not attached
if [ $i -eq 300 ]
then
echo "device timeout!"
exit 69
else
ant debug
echo "##################################################################"
echo "# Plug in your device or launch an emulator with cordova/emulate #"
echo "##################################################################"
echo "connected!"
fi
}
function launch {
local launch_str=$(java -jar $PROJECT_PATH/cordova/appinfo.jar $PROJECT_PATH/AndroidManifest.xml)
local launch_str=$(java -jar "$PROJECT_PATH"/cordova/appinfo.jar "$PROJECT_PATH"/AndroidManifest.xml)
adb shell am start -n $launch_str
}
function BOOM {
clean && debug && launch
}
# TODO parse arguments
(cd $PROJECT_PATH && $1)
(cd "$PROJECT_PATH" && $1)

View File

@@ -34,17 +34,19 @@ function exec(command) {
return output;
}
function emulator_running() {
function device_running() {
var local_devices = shell.Exec("%comspec% /c adb devices").StdOut.ReadAll();
if(local_devices.match(/emulator/)) {
if(local_devices.match(/\w+\tdevice/)) {
WScript.Echo("Yes");
return true;
}
WScript.Echo("No");
return false;
}
function emulate() {
// don't run emulator if a device is plugged in or if emulator is already running
if(emulator_running()) {
WScript.Echo("Device or Emulator already running!");
if(device_running()) {
//WScript.Echo("Device or Emulator already running!");
return;
}
var oExec = shell.Exec("%comspec% /c android.bat list avd");
@@ -84,18 +86,18 @@ function emulate() {
}
function clean() {
WScript.Echo("Cleaning project...");
exec("%comspec% /c ant.bat clean -f "+ROOT+"\\build.xml 2>&1");
}
function debug() {
if(emulator_running()) {
exec("%comspec% /c ant.bat debug install -f "+ROOT+"\\build.xml 2>&1");
} else {
exec("%comspec% /c ant.bat debug -f "+ROOT+"\\build.xml 2>&1");
WScript.Echo("##################################################################");
WScript.Echo("# Plug in your device or launch an emulator with cordova/emulate #");
WScript.Echo("##################################################################");
}
function build() {
WScript.Echo("Building project...");
exec("%comspec% /c ant.bat debug -f "+ROOT+"\\build.xml 2>&1");
}
function install() {
WScript.Echo("Building/Installing project...");
exec("%comspec% /c ant.bat debug install -f "+ROOT+"\\build.xml 2>&1");
}
function log() {
@@ -103,14 +105,28 @@ function log() {
}
function launch() {
WScript.Echo("Launching app...");
var launch_str=exec("%comspec% /c java -jar "+ROOT+"\\cordova\\appinfo.jar "+ROOT+"\\AndroidManifest.xml");
//WScript.Echo(launch_str);
exec("%comspec% /c adb shell am start -n "+launch_str+" 2>&1");
}
function BOOM() {
function run() {
var i=0;
clean();
debug();
emulate();
WScript.Stdout.Write('Waiting for device...');
while(!device_running() && i < 300) {
WScript.Stdout.Write('.');
WScript.sleep(1000);
i += 1;
}
if(i == 300) {
WScript.Stderr.WriteLine("device/emulator timeout!");
} else {
WScript.Stdout.WriteLine("connected!");
}
install();
launch();
}
var args = WScript.Arguments;

View File

@@ -1 +0,0 @@
%~dp0\cordova.bat emulate

View File

@@ -19,6 +19,6 @@
set -e
PROJECT_PATH=$( cd "$( dirname "$0" )/.." && pwd )
CORDOVA_PATH=$( cd "$( dirname "$0" )/.." && pwd )
bash $PROJECT_PATH/cordova/cordova log
bash "$CORDOVA_PATH"/cordova/cordova log

View File

@@ -21,4 +21,4 @@ set -e
CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd )
bash $CORDOVA_PATH/cordova debug
bash "$CORDOVA_PATH"/cordova release

View File

@@ -21,4 +21,4 @@ set -e
CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd )
bash $CORDOVA_PATH/cordova BOOM
bash "$CORDOVA_PATH"/cordova run

View File

@@ -0,0 +1 @@
%~dp0\cordova.bat run

View File

@@ -19,7 +19,6 @@
package __ID__;
import android.app.Activity;
import android.os.Bundle;
import org.apache.cordova.*;
@@ -29,7 +28,9 @@ public class __ACTIVITY__ extends DroidGap
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
// Set by <content src="index.html" /> in config.xml
super.loadUrl(Config.getStartUrl());
//super.loadUrl("file:///android_asset/www/index.html")
}
}

View File

@@ -18,7 +18,7 @@
under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:windowSoftInputMode="adjustPan"
package="__PACKAGE__" android:versionName="1.1" android:versionCode="5" android:hardwareAccelerated="true">
package="__PACKAGE__" android:versionName="1.0" android:versionCode="1" android:hardwareAccelerated="true">
<supports-screens
android:largeScreens="true"
android:normalScreens="true"

View File

@@ -19,7 +19,7 @@
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
@@ -33,7 +33,7 @@
<p class="event received">Device is Ready</p>
</div>
</div>
<script type="text/javascript" src="cordova-2.2.0rc1.js"></script>
<script type="text/javascript" src="cordova-2.7.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();

139
bin/update Executable file
View File

@@ -0,0 +1,139 @@
#! /bin/bash
# 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.
#
# update a cordova/android project's command line tools
#
# USAGE
# ./update [path]
#
set -e
if [ -z "$1" ] || [ "$1" == "-h" ]
then
echo 'usage: update path'
echo "Make sure the Android SDK tools folder is in your PATH!"
exit 0
fi
BUILD_PATH="$( cd "$( dirname "$0" )/.." && pwd )"
VERSION=$(cat "$BUILD_PATH"/VERSION)
PROJECT_PATH="${1:-'./example'}"
if [ ! -d "$PROJECT_PATH" ]
then
echo "The project path has to exist for it to be updated"
exit 0
fi
# cleanup after exit and/or on error
function on_exit {
if [ -f "$BUILD_PATH"/framework/assets/www/cordova-$VERSION.js ]
then
rm "$BUILD_PATH"/framework/assets/www/cordova-$VERSION.js
fi
if [ -f "$BUILD_PATH"/framework/cordova-$VERSION.jar ]
then
rm "$BUILD_PATH"/framework/cordova-$VERSION.jar
fi
}
function createAppInfoJar {
(cd "$BUILD_PATH"/bin/templates/cordova/ApplicationInfo &&
javac ApplicationInfo.java &&
jar -cfe ../appinfo.jar ApplicationInfo ApplicationInfo.class
)
}
function on_error {
echo "An unexpected error occurred: $previous_command exited with $?"
echo "Deleting project..."
[ -d "$PROJECT_PATH" ] && rm -rf "$PROJECT_PATH"
exit 1
}
function replace {
local pattern=$1
local filename=$2
# Mac OS X requires -i argument
if [[ "$OSTYPE" =~ "darwin" ]]
then
/usr/bin/sed -i '' -e $pattern "$filename"
elif [[ "$OSTYPE" =~ "linux" ]]
then
/bin/sed -i -e $pattern "$filename"
fi
}
# we do not want the script to silently fail
trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
trap on_error ERR
trap on_exit EXIT
ANDROID_BIN="${ANDROID_BIN:=$( which android )}"
TARGET=$("$ANDROID_BIN" list targets | grep id: | tail -1 | cut -f 2 -d ' ' )
API_LEVEL=$("$ANDROID_BIN" list target | grep "API level:" | tail -n 1 | cut -f 2 -d ':' | tr -d ' ')
# check that build targets exist
if [ -z "$TARGET" ] || [ -z "$API_LEVEL" ]
then
echo "No Android Targets are installed. Please install at least one via the android SDK"
exit 1
fi
# if this a distribution release no need to build a jar
if [ ! -e "$BUILD_PATH"/cordova-$VERSION.jar ] && [ -d "$BUILD_PATH"/framework ]
then
# update the cordova-android framework for the desired target
"$ANDROID_BIN" update project --target $TARGET --path "$BUILD_PATH"/framework &> /dev/null
if [ ! -e "$BUILD_PATH"/framework/libs/commons-codec-1.7.jar ]; then
# Use curl to get the jar (TODO: Support Apache Mirrors)
curl -OL http://archive.apache.org/dist/commons/codec/binaries/commons-codec-1.7-bin.zip &> /dev/null
unzip commons-codec-1.7-bin.zip &> /dev/null
mkdir -p "$BUILD_PATH"/framework/libs
cp commons-codec-1.7/commons-codec-1.7.jar "$BUILD_PATH"/framework/libs
# cleanup yo
rm commons-codec-1.7-bin.zip && rm -rf commons-codec-1.7
fi
# compile cordova.js and cordova.jar
(cd "$BUILD_PATH"/framework && ant jar &> /dev/null )
fi
# copy cordova.js, cordova.jar and res/xml
if [ -d "$BUILD_PATH"/framework ]
then
cp "$BUILD_PATH"/framework/assets/www/cordova-$VERSION.js "$PROJECT_PATH"/assets/www/cordova-$VERSION.js
cp "$BUILD_PATH"/framework/cordova-$VERSION.jar "$PROJECT_PATH"/libs/cordova-$VERSION.jar
else
cp "$BUILD_PATH"/cordova-$VERSION.js "$PROJECT_PATH"/assets/www/cordova-$VERSION.js
cp "$BUILD_PATH"/cordova-$VERSION.jar "$PROJECT_PATH"/libs/cordova-$VERSION.jar
fi
# creating cordova folder and copying run/build/log/launch scripts
cp "$BUILD_PATH"/bin/templates/cordova/appinfo.jar "$PROJECT_PATH"/cordova/appinfo.jar
cp "$BUILD_PATH"/bin/templates/cordova/cordova "$PROJECT_PATH"/cordova/cordova
cp "$BUILD_PATH"/bin/templates/cordova/build "$PROJECT_PATH"/cordova/build
cp "$BUILD_PATH"/bin/templates/cordova/release "$PROJECT_PATH"/cordova/release
cp "$BUILD_PATH"/bin/templates/cordova/clean "$PROJECT_PATH"/cordova/clean
cp "$BUILD_PATH"/bin/templates/cordova/log "$PROJECT_PATH"/cordova/log
cp "$BUILD_PATH"/bin/templates/cordova/run "$PROJECT_PATH"/cordova/run

View File

@@ -15,4 +15,18 @@
:: specific language governing permissions and limitations
:: under the License.
%~dp0\cordova.bat debug
@ECHO OFF
IF NOT DEFINED JAVA_HOME GOTO MISSING
FOR %%X in (java.exe javac.exe ant.bat android.bat) do (
SET FOUND=%%~$PATH:X
IF NOT DEFINED FOUND GOTO MISSING
)
cscript "%~dp0\update.js" %*
GOTO END
:MISSING
ECHO Missing one of the following:
ECHO JDK: http://java.oracle.com
ECHO Android SDK: http://developer.android.com
ECHO Apache ant: http://ant.apache.org
EXIT /B 1
:END

193
bin/update.js Normal file
View File

@@ -0,0 +1,193 @@
/*
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.
*/
/*
* create a cordova/android project
*
* USAGE
* ./update [path]
*/
var fso = WScript.CreateObject('Scripting.FileSystemObject');
function read(filename) {
var fso=WScript.CreateObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile(filename, 1);
var s=f.ReadAll();
f.Close();
return s;
}
function checkTargets(targets) {
if(!targets) {
WScript.Echo("You do not have any android targets setup. Please create at least one target with the `android` command");
WScript.Quit(69);
}
}
function setTarget() {
var targets = shell.Exec('android.bat list targets').StdOut.ReadAll().match(/id:\s\d+/g);
checkTargets(targets);
return targets[targets.length - 1].replace(/id: /, ""); // TODO: give users the option to set their target
}
function setApiLevel() {
var targets = shell.Exec('android.bat list targets').StdOut.ReadAll().match(/API level:\s\d+/g);
checkTargets(targets);
return targets[targets.length - 1].replace(/API level: /, "");
}
function write(filename, contents) {
var fso=WScript.CreateObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile(filename, 2, true);
f.Write(contents);
f.Close();
}
function replaceInFile(filename, regexp, replacement) {
write(filename, read(filename).replace(regexp, replacement));
}
function exec(command) {
var oShell=shell.Exec(command);
while (oShell.Status == 0) {
if(!oShell.StdOut.AtEndOfStream) {
var line = oShell.StdOut.ReadLine();
// XXX: Change to verbose mode
// WScript.StdOut.WriteLine(line);
}
WScript.sleep(100);
}
}
function createAppInfoJar() {
if(!fso.FileExists(ROOT+"\\bin\\templates\\cordova\\appinfo.jar")) {
WScript.Echo("Creating appinfo.jar...");
var cur = shell.CurrentDirectory;
shell.CurrentDirectory = ROOT+"\\bin\\templates\\cordova\\ApplicationInfo";
exec("javac ApplicationInfo.java");
exec("jar -cfe ..\\appinfo.jar ApplicationInfo ApplicationInfo.class");
shell.CurrentDirectory = cur;
}
}
function cleanup() {
if(fso.FileExists(ROOT + '\\framework\\cordova-'+VERSION+'.jar')) {
fso.DeleteFile(ROOT + '\\framework\\cordova-'+VERSION+'.jar');
}
if(fso.FileExists(ROOT + '\\framework\\assets\\www\\cordova-'+VERSION+'.js')) {
fso.DeleteFile(ROOT + '\\framework\\assets\\www\\cordova-'+VERSION+'.js');
}
}
function downloadCommonsCodec() {
if (!fso.FileExists(ROOT + '\\framework\\libs\\commons-codec-1.7.jar')) {
// We need the .jar
var url = 'http://archive.apache.org/dist/commons/codec/binaries/commons-codec-1.7-bin.zip';
var libsPath = ROOT + '\\framework\\libs';
var savePath = libsPath + '\\commons-codec-1.7-bin.zip';
if (!fso.FileExists(savePath)) {
if(!fso.FolderExists(ROOT + '\\framework\\libs')) {
fso.CreateFolder(libsPath);
}
// We need the zip to get the jar
var xhr = WScript.CreateObject('MSXML2.XMLHTTP');
xhr.open('GET', url, false);
xhr.send();
if (xhr.status == 200) {
var stream = WScript.CreateObject('ADODB.Stream');
stream.Open();
stream.Type = 1;
stream.Write(xhr.ResponseBody);
stream.Position = 0;
stream.SaveToFile(savePath);
stream.Close();
} else {
WScript.Echo('Could not retrieve the commons-codec. Please download it yourself and put into the framework/libs directory. This process may fail now. Sorry.');
}
}
var app = WScript.CreateObject('Shell.Application');
var source = app.NameSpace(savePath).Items();
var target = app.NameSpace(ROOT + '\\framework\\libs');
target.CopyHere(source, 256);
// Move the jar into libs
fso.MoveFile(ROOT + '\\framework\\libs\\commons-codec-1.7\\commons-codec-1.7.jar', ROOT + '\\framework\\libs\\commons-codec-1.7.jar');
// Clean up
fso.DeleteFile(ROOT + '\\framework\\libs\\commons-codec-1.7-bin.zip');
fso.DeleteFolder(ROOT + '\\framework\\libs\\commons-codec-1.7', true);
}
}
var args = WScript.Arguments, PROJECT_PATH="example",
shell=WScript.CreateObject("WScript.Shell");
// working dir
var ROOT = WScript.ScriptFullName.split('\\bin\\update.js').join('');
if (args.Count() == 1) {
PROJECT_PATH=args(0);
}
if(!fso.FolderExists(PROJECT_PATH)) {
WScript.Echo("Project doesn't exist!");
WScript.Quit(1);
}
var TARGET=setTarget();
var API_LEVEL=setApiLevel();
var VERSION=read(ROOT+'\\VERSION').replace(/\r\n/,'').replace(/\n/,'');
// build from source. distro should have these files
if (!fso.FileExists(ROOT+'\\cordova-'+VERSION+'.jar') &&
!fso.FileExists(ROOT+'\\cordova-'+VERSION+'.js')) {
WScript.Echo("Building jar and js files...");
// update the cordova framework project to a target that exists on this machine
exec('android.bat update project --target '+TARGET+' --path '+ROOT+'\\framework');
// pull down commons codec if necessary
downloadCommonsCodec();
exec('ant.bat -f \"'+ ROOT +'\\framework\\build.xml\" jar');
}
// check if we have the source or the distro files
WScript.Echo("Copying js, jar & config.xml files...");
if(fso.FolderExists(ROOT + '\\framework')) {
exec('%comspec% /c copy "'+ROOT+'"\\framework\\assets\\www\\cordova-'+VERSION+'.js '+PROJECT_PATH+'\\assets\\www\\cordova-'+VERSION+'.js /Y');
exec('%comspec% /c copy "'+ROOT+'"\\framework\\cordova-'+VERSION+'.jar '+PROJECT_PATH+'\\libs\\cordova-'+VERSION+'.jar /Y');
} else {
// copy in cordova.js
exec('%comspec% /c copy "'+ROOT+'"\\cordova-'+VERSION+'.js '+PROJECT_PATH+'\\assets\\www\\cordova-'+VERSION+'.js /Y');
// copy in cordova.jar
exec('%comspec% /c copy "'+ROOT+'"\\cordova-'+VERSION+'.jar '+PROJECT_PATH+'\\libs\\cordova-'+VERSION+'.jar /Y');
// copy in xml
}
// update cordova scripts
createAppInfoJar();
WScript.Echo("Copying cordova command tools...");
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\appinfo.jar ' + PROJECT_PATH + '\\cordova\\appinfo.jar /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\cordova.js ' + PROJECT_PATH + '\\cordova\\cordova.js /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\cordova.bat ' + PROJECT_PATH + '\\cordova\\cordova.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\clean.bat ' + PROJECT_PATH + '\\cordova\\clean.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\build.bat ' + PROJECT_PATH + '\\cordova\\build.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\log.bat ' + PROJECT_PATH + '\\cordova\\log.bat /Y');
exec('%comspec% /c copy "'+ROOT+'"\\bin\\templates\\cordova\\run.bat ' + PROJECT_PATH + '\\cordova\\run.bat /Y');
cleanup();

View File

@@ -18,7 +18,7 @@
under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:windowSoftInputMode="adjustPan"
package="org.apache.cordova" android:versionName="1.1" android:versionCode="5">
package="org.apache.cordova" android:versionName="1.0" android:versionCode="1">
<supports-screens
android:largeScreens="true"
android:normalScreens="true"

File diff suppressed because it is too large Load Diff

View File

@@ -19,7 +19,7 @@
<html>
<head>
<title></title>
<script src="cordova-2.2.0rc1.js"></script>
<script src="cordova-2.7.0.js"></script>
</head>
<body>

View File

@@ -10,7 +10,7 @@
# Indicates whether an apk should be generated for each density.
split.density=false
# Project target.
target=Google Inc.:Google APIs:16
target=Google Inc.:Google APIs:17
apk-configurations=
renderscript.opt.level=O0
android.library=true

View File

@@ -29,8 +29,11 @@
<!-- <access origin="https://example.com" subdomains="true" /> such as above, but including subdomains, such as www -->
<access origin=".*"/>
<!-- <content src="http://mysite.com/myapp.html" /> for external pages -->
<content src="index.html" />
<log level="DEBUG"/>
<preference name="useBrowserHistory" value="false" />
<preference name="useBrowserHistory" value="true" />
<preference name="exit-on-suspend" value="false" />
<plugins>
<plugin name="App" value="org.apache.cordova.App"/>
@@ -51,6 +54,7 @@
<plugin name="SplashScreen" value="org.apache.cordova.SplashScreen"/>
<plugin name="Echo" value="org.apache.cordova.Echo" />
<plugin name="Globalization" value="org.apache.cordova.Globalization"/>
<plugin name="InAppBrowser" value="org.apache.cordova.InAppBrowser"/>
</plugins>
</cordova>

View File

@@ -19,28 +19,30 @@
package org.apache.cordova;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
/**
* This class exposes methods in DroidGap that can be called from JavaScript.
*/
public class App extends Plugin {
public class App extends CordovaPlugin {
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackContext The callback context from which we were invoked.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
@@ -62,7 +64,7 @@ public class App extends Plugin {
this.loadUrl(args.getString(0), args.optJSONObject(1));
}
else if (action.equals("cancelLoadUrl")) {
this.cancelLoadUrl();
//this.cancelLoadUrl();
}
else if (action.equals("clearHistory")) {
this.clearHistory();
@@ -79,9 +81,11 @@ public class App extends Plugin {
else if (action.equals("exitApp")) {
this.exitApp();
}
return new PluginResult(status, result);
callbackContext.sendPluginResult(new PluginResult(status, result));
return true;
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return false;
}
}
@@ -156,14 +160,6 @@ public class App extends Plugin {
this.webView.showWebPage(url, openExternal, clearHistory, params);
}
/**
* Cancel loadUrl before it has been loaded (Only works on a CordovaInterface class)
*/
@Deprecated
public void cancelLoadUrl() {
this.cordova.cancelLoadUrl();
}
/**
* Clear page history for the app.
*/

View File

@@ -68,13 +68,13 @@ public class AudioHandler extends CordovaPlugin {
String result = "";
if (action.equals("startRecordingAudio")) {
this.startRecordingAudio(args.getString(0), FileUtils.stripFileProtocol(args.getString(1)));
this.startRecordingAudio(args.getString(0), FileHelper.stripFileProtocol(args.getString(1)));
}
else if (action.equals("stopRecordingAudio")) {
this.stopRecordingAudio(args.getString(0));
}
else if (action.equals("startPlayingAudio")) {
this.startPlayingAudio(args.getString(0), FileUtils.stripFileProtocol(args.getString(1)));
this.startPlayingAudio(args.getString(0), FileHelper.stripFileProtocol(args.getString(1)));
}
else if (action.equals("seekToAudio")) {
this.seekToAudio(args.getString(0), args.getInt(1));
@@ -102,7 +102,7 @@ public class AudioHandler extends CordovaPlugin {
}
else if (action.equals("create")) {
String id = args.getString(0);
String src = FileUtils.stripFileProtocol(args.getString(1));
String src = FileHelper.stripFileProtocol(args.getString(1));
AudioPlayer audio = new AudioPlayer(this, id, src);
this.players.put(id, audio);
}

View File

@@ -167,13 +167,18 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
public void moveFile(String file) {
/* this is a hack to save the file as the specified name */
File f = new File(this.tempFile);
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
f.renameTo(new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + file));
} else {
f.renameTo(new File("/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/" + file));
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;
}
}
String logMsg = "renaming " + this.tempFile + " to " + file;
Log.d(LOG_TAG, logMsg);
if (!f.renameTo(new File(file))) Log.e(LOG_TAG, "FAILED " + logMsg);
}
/**

View File

@@ -42,6 +42,7 @@ import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Rect;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
@@ -58,6 +59,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
private static final int DATA_URL = 0; // Return base64 encoded string
private static final int FILE_URI = 1; // Return file uri (content://media/external/images/media/2 for Android)
private static final int NATIVE_URI = 2; // On Android, this is the same as FILE_URI
private static final int PHOTOLIBRARY = 0; // Choose image from picture library (same as SAVEDPHOTOALBUM for Android)
private static final int CAMERA = 1; // Take picture from camera
@@ -288,7 +290,18 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
// If sending base64 image back
if (destType == DATA_URL) {
bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));
bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
if (bitmap == null) {
// Try to get the bitmap from intent.
bitmap = (Bitmap)intent.getExtras().get("data");
}
// Double-check the bitmap.
if (bitmap == null) {
Log.d(LOG_TAG, "I either have a null image path or bitmap");
this.failPicture("Unable to create bitmap!");
return;
}
if (rotate != 0 && this.correctOrientation) {
bitmap = getRotatedBitmap(rotate, bitmap, exif);
@@ -299,11 +312,13 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
}
// If sending filename back
else if (destType == FILE_URI) {
if (!this.saveToPhotoAlbum) {
uri = Uri.fromFile(new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), System.currentTimeMillis() + ".jpg"));
else if (destType == FILE_URI || destType == NATIVE_URI) {
if (this.saveToPhotoAlbum) {
Uri inputUri = getUriFromMediaStore();
//Just because we have a media URI doesn't mean we have a real file, we need to make it
uri = Uri.fromFile(new File(FileHelper.getRealPath(inputUri, this.cordova)));
} else {
uri = getUriFromMediaStore();
uri = Uri.fromFile(new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), System.currentTimeMillis() + ".jpg"));
}
if (uri == null) {
@@ -311,12 +326,13 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
}
// If all this is true we shouldn't compress the image.
if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100 && rotate == 0) {
if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100 &&
!this.correctOrientation) {
writeUncompressedImage(uri);
this.callbackContext.success(uri.toString());
} else {
bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));
bitmap = getScaledBitmap(FileHelper.stripFileProtocol(imageUri.toString()));
if (rotate != 0 && this.correctOrientation) {
bitmap = getRotatedBitmap(rotate, bitmap, exif);
@@ -331,7 +347,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
if (this.encodingType == JPEG) {
String exifPath;
if (this.saveToPhotoAlbum) {
exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
exifPath = FileHelper.getRealPath(uri, this.cordova);
} else {
exifPath = uri.getPath();
}
@@ -376,24 +392,26 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
}
else {
// This is a special case to just return the path as no scaling,
// rotating or compression needs to be done
// rotating, nor compressing needs to be done
if (this.targetHeight == -1 && this.targetWidth == -1 &&
this.mQuality == 100 && destType == FILE_URI && !this.correctOrientation) {
(destType == FILE_URI || destType == NATIVE_URI) && !this.correctOrientation) {
this.callbackContext.success(uri.toString());
} else {
String uriString = uri.toString();
// Get the path to the image. Makes loading so much easier.
String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
String mimeType = FileUtils.getMimeType(imagePath);
// Log.d(LOG_TAG, "Real path = " + imagePath);
// Log.d(LOG_TAG, "mime type = " + mimeType);
String mimeType = FileHelper.getMimeType(uriString, this.cordova);
// If we don't have a valid image so quit.
if (imagePath == null || mimeType == null ||
!(mimeType.equalsIgnoreCase("image/jpeg") || mimeType.equalsIgnoreCase("image/png"))) {
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 = getScaledBitmap(imagePath);
Bitmap bitmap = null;
try {
bitmap = getScaledBitmap(uriString);
} catch (IOException e) {
e.printStackTrace();
}
if (bitmap == null) {
Log.d(LOG_TAG, "I either have a null image path or bitmap");
this.failPicture("Unable to create bitmap!");
@@ -401,14 +419,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
}
if (this.correctOrientation) {
String[] cols = { MediaStore.Images.Media.ORIENTATION };
Cursor cursor = this.cordova.getActivity().getContentResolver().query(intent.getData(),
cols, null, null, null);
if (cursor != null) {
cursor.moveToPosition(0);
rotate = cursor.getInt(0);
cursor.close();
}
rotate = getImageOrientation(uri);
if (rotate != 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotate);
@@ -422,21 +433,23 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
}
// If sending filename back
else if (destType == FILE_URI) {
else if (destType == FILE_URI || destType == NATIVE_URI) {
// Do we need to scale the returned file
if (this.targetHeight > 0 && this.targetWidth > 0) {
try {
// Create an ExifHelper to save the exif data that is lost during compression
String resizePath = DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
// Some content: URIs do not map to file paths (e.g. picasa).
String realPath = FileHelper.getRealPath(uri, this.cordova);
ExifHelper exif = new ExifHelper();
try {
if (this.encodingType == JPEG) {
exif.createInFile(resizePath);
if (realPath != null && this.encodingType == JPEG) {
try {
exif.createInFile(realPath);
exif.readExifData();
rotate = exif.getOrientation();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
OutputStream os = new FileOutputStream(resizePath);
@@ -444,8 +457,8 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
os.close();
// Restore exif data to file
if (this.encodingType == JPEG) {
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
if (realPath != null && this.encodingType == JPEG) {
exif.createOutFile(resizePath);
exif.writeExifData();
}
@@ -478,6 +491,19 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
}
}
private int getImageOrientation(Uri uri) {
String[] cols = { MediaStore.Images.Media.ORIENTATION };
Cursor cursor = cordova.getActivity().getContentResolver().query(uri,
cols, null, null, null);
int rotate = 0;
if (cursor != null) {
cursor.moveToPosition(0);
rotate = cursor.getInt(0);
cursor.close();
}
return rotate;
}
/**
* Figure out if the bitmap should be rotated. For instance if the picture was taken in
* portrait mode
@@ -508,7 +534,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
*/
private void writeUncompressedImage(Uri uri) throws FileNotFoundException,
IOException {
FileInputStream fis = new FileInputStream(FileUtils.stripFileProtocol(imageUri.toString()));
FileInputStream fis = new FileInputStream(FileHelper.stripFileProtocol(imageUri.toString()));
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
byte[] buffer = new byte[4096];
int len;
@@ -548,25 +574,35 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
*
* @param imagePath
* @return
* @throws IOException
*/
private Bitmap getScaledBitmap(String imagePath) {
private Bitmap getScaledBitmap(String imageUrl) throws IOException {
// If no new width or height were specified return the original bitmap
if (this.targetWidth <= 0 && this.targetHeight <= 0) {
return BitmapFactory.decodeFile(imagePath);
return BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova));
}
// figure out the original width and height of the image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova), null, options);
//CB-2292: WTF? Why is the width null?
if(options.outWidth == 0 || options.outHeight == 0)
{
return null;
}
// determine the correct aspect ratio
int[] widthHeight = calculateAspectRatio(options.outWidth, options.outHeight);
// Load in the smallest bitmap possible that is closest to the size we want
options.inJustDecodeBounds = false;
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth, this.targetHeight);
Bitmap unscaledBitmap = BitmapFactory.decodeFile(imagePath, options);
Bitmap unscaledBitmap = BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova), null, options);
if (unscaledBitmap == null) {
return null;
}
return Bitmap.createScaledBitmap(unscaledBitmap, widthHeight[0], widthHeight[1], true);
}
@@ -663,7 +699,7 @@ public class CameraLauncher extends CordovaPlugin implements MediaScannerConnect
}
// Clean up initial camera-written image file.
(new File(FileUtils.stripFileProtocol(oldImage.toString()))).delete();
(new File(FileHelper.stripFileProtocol(oldImage.toString()))).delete();
checkForDuplicateImage(imageType);
// Scan for the gallery to update pic refs in gallery

View File

@@ -23,6 +23,7 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.os.Build;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.LOG;
@@ -127,8 +128,8 @@ public class Capture extends CordovaPlugin {
// If the mimeType isn't set the rest will fail
// so let's see if we can determine it.
if (mimeType == null || mimeType.equals("")) {
mimeType = FileUtils.getMimeType(filePath);
if (mimeType == null || mimeType.equals("") || "null".equals(mimeType)) {
mimeType = FileHelper.getMimeType(filePath, cordova);
}
Log.d(LOG_TAG, "Mime type = " + mimeType);
@@ -155,7 +156,7 @@ public class Capture extends CordovaPlugin {
private JSONObject getImageData(String filePath, JSONObject obj) throws JSONException {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(FileUtils.stripFileProtocol(filePath), options);
BitmapFactory.decodeFile(FileHelper.stripFileProtocol(filePath), options);
obj.put("height", options.outHeight);
obj.put("width", options.outWidth);
return obj;
@@ -216,9 +217,10 @@ public class Capture extends CordovaPlugin {
*/
private void captureVideo(double duration) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_VIDEO_CAPTURE);
// Introduced in API 8
//intent.putExtra(android.provider.MediaStore.EXTRA_DURATION_LIMIT, duration);
if(Build.VERSION.SDK_INT > 8){
intent.putExtra("android.intent.extra.durationLimit", duration);
}
this.cordova.startActivityForResult((CordovaPlugin) this, intent, CAPTURE_VIDEO);
}
@@ -346,7 +348,7 @@ public class Capture extends CordovaPlugin {
* @throws IOException
*/
private JSONObject createMediaFile(Uri data) {
File fp = new File(FileUtils.getRealPathFromURI(data, this.cordova));
File fp = new File(FileHelper.getRealPath(data, this.cordova));
JSONObject obj = new JSONObject();
try {
@@ -363,7 +365,7 @@ public class Capture extends CordovaPlugin {
obj.put("type", VIDEO_3GPP);
}
} else {
obj.put("type", FileUtils.getMimeType(fp.getAbsolutePath()));
obj.put("type", FileHelper.getMimeType(fp.getAbsolutePath(), cordova));
}
obj.put("lastModifiedDate", fp.lastModified());

View File

@@ -202,7 +202,9 @@ public class CompassListener extends CordovaPlugin implements SensorEventListene
private void timeout() {
if (this.status == CompassListener.STARTING) {
this.setStatus(CompassListener.ERROR_FAILED_TO_START);
this.callbackContext.error("Compass listener failed to start.");
if (this.callbackContext != null) {
this.callbackContext.error("Compass listener failed to start.");
}
}
}

View File

@@ -0,0 +1,297 @@
/*
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;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.cordova.api.LOG;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.XmlResourceParser;
import android.graphics.Color;
import android.util.Log;
public class Config {
public static final String TAG = "Config";
private ArrayList<Pattern> whiteList = new ArrayList<Pattern>();
private HashMap<String, Boolean> whiteListCache = new HashMap<String, Boolean>();
private String startUrl;
private static Config self = null;
public static void init(Activity action) {
if (self == null) {
self = new Config(action);
}
}
// Intended to be used for testing only; creates an empty configuration.
public static void init() {
if (self == null) {
self = new Config();
}
}
// Intended to be used for testing only; creates an empty configuration.
private Config() {
}
private Config(Activity action) {
if (action == null) {
LOG.i("CordovaLog", "There is no activity. Is this on the lock screen?");
return;
}
int id = action.getResources().getIdentifier("config", "xml", action.getPackageName());
if (id == 0) {
id = action.getResources().getIdentifier("cordova", "xml", action.getPackageName());
LOG.i("CordovaLog", "config.xml missing, reverting to cordova.xml");
}
if (id == 0) {
LOG.i("CordovaLog", "cordova.xml missing. Ignoring...");
return;
}
XmlResourceParser xml = action.getResources().getXml(id);
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = xml.getName();
if (strNode.equals("access")) {
String origin = xml.getAttributeValue(null, "origin");
String subdomains = xml.getAttributeValue(null, "subdomains");
if (origin != null) {
this._addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));
}
}
else if (strNode.equals("log")) {
String level = xml.getAttributeValue(null, "level");
LOG.i("CordovaLog", "Found log level %s", level);
if (level != null) {
LOG.setLogLevel(level);
}
}
else if (strNode.equals("preference")) {
String name = xml.getAttributeValue(null, "name");
/* Java 1.6 does not support switch-based strings
Java 7 does, but we're using Dalvik, which is apparently not Java.
Since we're reading XML, this has to be an ugly if/else.
Also, due to cast issues, each of them has to call their separate putExtra!
Wheee!!! Isn't Java FUN!?!?!?
Note: We should probably pass in the classname for the variable splash on splashscreen!
*/
if(name.equals("splashscreen")) {
String value = xml.getAttributeValue(null, "value");
int resource = 0;
if (value != null)
{
value = "splash";
}
resource = action.getResources().getIdentifier(value, "drawable", action.getPackageName());
action.getIntent().putExtra(name, resource);
LOG.i("CordovaLog", "Found preference for %s=%s", name, value);
Log.d("CordovaLog", "Found preference for " + name + "=" + value);
}
else if(name.equals("backgroundColor")) {
int value = xml.getAttributeIntValue(null, "value", Color.BLACK);
action.getIntent().putExtra(name, value);
LOG.i("CordovaLog", "Found preference for %s=%d", name, value);
Log.d("CordovaLog", "Found preference for " + name + "=" + Integer.toString(value));
}
else if(name.equals("loadUrlTimeoutValue")) {
int value = xml.getAttributeIntValue(null, "value", 20000);
action.getIntent().putExtra(name, value);
LOG.i("CordovaLog", "Found preference for %s=%d", name, value);
Log.d("CordovaLog", "Found preference for " + name + "=" + Integer.toString(value));
}
else if(name.equals("keepRunning"))
{
boolean value = xml.getAttributeValue(null, "value").equals("true");
action.getIntent().putExtra(name, value);
}
else if(name.equals("InAppBrowserStorageEnabled"))
{
boolean value = xml.getAttributeValue(null, "value").equals("true");
action.getIntent().putExtra(name, value);
}
else if(name.equals("disallowOverscroll"))
{
boolean value = xml.getAttributeValue(null, "value").equals("true");
action.getIntent().putExtra(name, value);
}
else
{
String value = xml.getAttributeValue(null, "value");
action.getIntent().putExtra(name, value);
LOG.i("CordovaLog", "Found preference for %s=%s", name, value);
Log.d("CordovaLog", "Found preference for " + name + "=" + value);
}
/*
LOG.i("CordovaLog", "Found preference for %s=%s", name, value);
Log.d("CordovaLog", "Found preference for " + name + "=" + value);
*/
}
else if (strNode.equals("content")) {
String src = xml.getAttributeValue(null, "src");
LOG.i("CordovaLog", "Found start page location: %s", src);
if (src != null) {
Pattern schemeRegex = Pattern.compile("^[a-z-]+://");
Matcher matcher = schemeRegex.matcher(src);
if (matcher.find()) {
startUrl = src;
} else {
if (src.charAt(0) == '/') {
src = src.substring(1);
}
startUrl = "file:///android_asset/www/" + src;
}
}
}
}
try {
eventType = xml.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Add entry to approved list of URLs (whitelist)
*
* @param origin URL regular expression to allow
* @param subdomains T=include all subdomains under origin
*/
public static void addWhiteListEntry(String origin, boolean subdomains) {
if (self == null) {
return;
}
self._addWhiteListEntry(origin, subdomains);
}
private void _addWhiteListEntry(String origin, boolean subdomains) {
try {
// Unlimited access to network resources
if (origin.compareTo("*") == 0) {
LOG.d(TAG, "Unlimited access to network resources");
this.whiteList.add(Pattern.compile(".*"));
} else { // specific access
// check if subdomains should be included
// TODO: we should not add more domains if * has already been added
Pattern schemeRegex = Pattern.compile("^[a-z-]+://");
Matcher matcher = schemeRegex.matcher(origin);
if (subdomains) {
// Check for http or https protocols
if (origin.startsWith("http")) {
this.whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://(.*\\.)?")));
}
// Check for other protocols
else if(matcher.find()){
this.whiteList.add(Pattern.compile("^" + origin.replaceFirst("//", "//(.*\\.)?")));
}
// XXX making it stupid friendly for people who forget to include protocol/SSL
else {
this.whiteList.add(Pattern.compile("^https?://(.*\\.)?" + origin));
}
LOG.d(TAG, "Origin to allow with subdomains: %s", origin);
} else {
// Check for http or https protocols
if (origin.startsWith("http")) {
this.whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://")));
}
// Check for other protocols
else if(matcher.find()){
this.whiteList.add(Pattern.compile("^" + origin));
}
// XXX making it stupid friendly for people who forget to include protocol/SSL
else {
this.whiteList.add(Pattern.compile("^https?://" + origin));
}
LOG.d(TAG, "Origin to allow: %s", origin);
}
}
} catch (Exception e) {
LOG.d(TAG, "Failed to add origin %s", origin);
}
}
/**
* Determine if URL is in approved list of URLs to load.
*
* @param url
* @return
*/
public static boolean isUrlWhiteListed(String url) {
if (self == null) {
return false;
}
// Check to see if we have matched url previously
if (self.whiteListCache.get(url) != null) {
return true;
}
// Look for match in white list
Iterator<Pattern> pit = self.whiteList.iterator();
while (pit.hasNext()) {
Pattern p = pit.next();
Matcher m = p.matcher(url);
// If match found, then cache it to speed up subsequent comparisons
if (m.find()) {
self.whiteListCache.put(url, true);
return true;
}
}
return false;
}
public static String getStartUrl() {
if (self == null || self.startUrl == null) {
return "file:///android_asset/www/index.html";
}
return self.startUrl;
}
}

View File

@@ -18,7 +18,6 @@ package org.apache.cordova;
import java.util.HashMap;
import android.content.Context;
import android.util.Log;
import android.webkit.WebView;

View File

@@ -219,6 +219,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
columnsToFetch.add(ContactsContract.CommonDataKinds.Phone.TYPE);
}
if (isRequired("emails", populate)) {
columnsToFetch.add(ContactsContract.CommonDataKinds.Email._ID);
columnsToFetch.add(ContactsContract.CommonDataKinds.Email.DATA);
columnsToFetch.add(ContactsContract.CommonDataKinds.Email.TYPE);
}
@@ -859,8 +860,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
im.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im._ID)));
im.put("pref", false); // Android does not store pref attribute
im.put("value", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA)));
String type = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL));
im.put("type", getImType(new Integer(type).intValue()));
im.put("type", getImType(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL))));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
@@ -1500,7 +1500,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"))
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, getPhoneType(getJsonString(email, "type")))
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type")))
.build());
}
@@ -1579,7 +1579,7 @@ public class ContactAccessorSdk5 extends ContactAccessor {
Uri uri = Uri.parse(path);
return mApp.getActivity().getContentResolver().openInputStream(uri);
}
if (path.startsWith("http:") || path.startsWith("file:")) {
if (path.startsWith("http:") || path.startsWith("https:") || path.startsWith("file:")) {
URL url = new URL(path);
return url.openStream();
}

View File

@@ -0,0 +1,113 @@
/*
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;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Base64;
public class CordovaArgs {
private JSONArray baseArgs;
public CordovaArgs(JSONArray args) {
this.baseArgs = args;
}
// Pass through the basics to the base args.
public Object get(int index) throws JSONException {
return baseArgs.get(index);
}
public boolean getBoolean(int index) throws JSONException {
return baseArgs.getBoolean(index);
}
public double getDouble(int index) throws JSONException {
return baseArgs.getDouble(index);
}
public int getInt(int index) throws JSONException {
return baseArgs.getInt(index);
}
public JSONArray getJSONArray(int index) throws JSONException {
return baseArgs.getJSONArray(index);
}
public JSONObject getJSONObject(int index) throws JSONException {
return baseArgs.getJSONObject(index);
}
public long getLong(int index) throws JSONException {
return baseArgs.getLong(index);
}
public String getString(int index) throws JSONException {
return baseArgs.getString(index);
}
public Object opt(int index) {
return baseArgs.opt(index);
}
public boolean optBoolean(int index) {
return baseArgs.optBoolean(index);
}
public double optDouble(int index) {
return baseArgs.optDouble(index);
}
public int optInt(int index) {
return baseArgs.optInt(index);
}
public JSONArray optJSONArray(int index) {
return baseArgs.optJSONArray(index);
}
public JSONObject optJSONObject(int index) {
return baseArgs.optJSONObject(index);
}
public long optLong(int index) {
return baseArgs.optLong(index);
}
public String optString(int index) {
return baseArgs.optString(index);
}
public boolean isNull(int index) {
return baseArgs.isNull(index);
}
// The interesting custom helpers.
public byte[] getArrayBuffer(int index) throws JSONException {
String encoded = baseArgs.getString(index);
return Base64.decode(encoded, Base64.DEFAULT);
}
}

View File

@@ -20,33 +20,49 @@ package org.apache.cordova;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.ConsoleMessage;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.GeolocationPermissions.Callback;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
/**
* This class is the WebChromeClient that implements callbacks for our web view.
*/
public class CordovaChromeClient extends WebChromeClient {
public static final int FILECHOOSER_RESULTCODE = 5173;
private static final String LOG_TAG = "CordovaChromeClient";
private String TAG = "CordovaLog";
private long MAX_QUOTA = 100 * 1024 * 1024;
private CordovaInterface cordova;
private CordovaWebView appView;
// the video progress view
private View mVideoProgressView;
// File Chooser
public ValueCallback<Uri> mUploadMessage;
/**
* Constructor.
*
@@ -189,7 +205,7 @@ public class CordovaChromeClient extends WebChromeClient {
// Security check to make sure any requests are coming from the page initially
// loaded in webview and not another loaded in an iframe.
boolean reqOk = false;
if (url.startsWith("file://") || url.indexOf(this.appView.baseUrl) == 0 || this.appView.isUrlWhiteListed(url)) {
if (url.startsWith("file://") || Config.isUrlWhiteListed(url)) {
reqOk = true;
}
@@ -288,12 +304,17 @@ public class CordovaChromeClient extends WebChromeClient {
}
// console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html
// Expect this to not compile in a future Android release!
@SuppressWarnings("deprecation")
@Override
public void onConsoleMessage(String message, int lineNumber, String sourceID)
{
LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message);
super.onConsoleMessage(message, lineNumber, sourceID);
//This is only for Android 2.1
if(android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.ECLAIR_MR1)
{
LOG.d(TAG, "%s: Line %d : %s", sourceID, lineNumber, message);
super.onConsoleMessage(message, lineNumber, sourceID);
}
}
@TargetApi(8)
@@ -316,4 +337,66 @@ public class CordovaChromeClient extends WebChromeClient {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
// API level 7 is required for this, see if we could lower this using something else
@Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
this.appView.showCustomView(view, callback);
}
@Override
public void onHideCustomView() {
this.appView.hideCustomView();
}
@Override
/**
* Ask the host application for a custom progress view to show while
* a <video> is loading.
* @return View The progress view.
*/
public View getVideoLoadingProgressView() {
if (mVideoProgressView == null) {
// Create a new Loading view programmatically.
// create the linear layout
LinearLayout layout = new LinearLayout(this.appView.getContext());
layout.setOrientation(LinearLayout.VERTICAL);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.setLayoutParams(layoutParams);
// the proress bar
ProgressBar bar = new ProgressBar(this.appView.getContext());
LinearLayout.LayoutParams barLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
barLayoutParams.gravity = Gravity.CENTER;
bar.setLayoutParams(barLayoutParams);
layout.addView(bar);
mVideoProgressView = layout;
}
return mVideoProgressView;
}
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
this.openFileChooser(uploadMsg, "*/*");
}
public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) {
this.openFileChooser(uploadMsg, acceptType, null);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
this.cordova.getActivity().startActivityForResult(Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
public ValueCallback<Uri> getValueCallback() {
return this.mUploadMessage;
}
}

View File

@@ -22,6 +22,8 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.cordova.api.CallbackContext;
@@ -42,6 +44,8 @@ public class CordovaLocationListener implements LocationListener {
public HashMap<String, CallbackContext> watches = new HashMap<String, CallbackContext>();
private List<CallbackContext> callbacks = new ArrayList<CallbackContext>();
private Timer timer = null;
private String TAG = "[Cordova Location Listener]";
@@ -52,11 +56,12 @@ public class CordovaLocationListener implements LocationListener {
}
protected void fail(int code, String message) {
this.cancelTimer();
for (CallbackContext callbackContext: this.callbacks)
{
this.owner.fail(code, message, callbackContext);
this.owner.fail(code, message, callbackContext, false);
}
if(this.owner.isGlobalListener(this))
if(this.owner.isGlobalListener(this) && this.watches.size() == 0)
{
Log.d(TAG, "Stopping global listener");
this.stop();
@@ -65,16 +70,17 @@ public class CordovaLocationListener implements LocationListener {
Iterator<CallbackContext> it = this.watches.values().iterator();
while (it.hasNext()) {
this.owner.fail(code, message, it.next());
this.owner.fail(code, message, it.next(), true);
}
}
private void win(Location loc) {
this.cancelTimer();
for (CallbackContext callbackContext: this.callbacks)
{
this.owner.win(loc, callbackContext);
this.owner.win(loc, callbackContext, false);
}
if(this.owner.isGlobalListener(this))
if(this.owner.isGlobalListener(this) && this.watches.size() == 0)
{
Log.d(TAG, "Stopping global listener");
this.stop();
@@ -83,7 +89,7 @@ public class CordovaLocationListener implements LocationListener {
Iterator<CallbackContext> it = this.watches.values().iterator();
while (it.hasNext()) {
this.owner.win(loc, it.next());
this.owner.win(loc, it.next(), true);
}
}
@@ -155,8 +161,12 @@ public class CordovaLocationListener implements LocationListener {
this.start();
}
}
public void addCallback(CallbackContext callbackContext) {
this.callbacks.add(callbackContext);
public void addCallback(CallbackContext callbackContext, int timeout) {
if(this.timer == null) {
this.timer = new Timer();
}
this.timer.schedule(new LocationTimeoutTask(callbackContext, this), timeout);
this.callbacks.add(callbackContext);
if (this.size() == 1) {
this.start();
}
@@ -173,7 +183,7 @@ public class CordovaLocationListener implements LocationListener {
/**
* Destroy listener.
*/
public void destroy() {
public void destroy() {
this.stop();
}
@@ -199,9 +209,43 @@ public class CordovaLocationListener implements LocationListener {
* Stop receiving location updates.
*/
private void stop() {
this.cancelTimer();
if (this.running) {
this.locationManager.removeUpdates(this);
this.running = false;
}
}
private void cancelTimer() {
if(this.timer != null) {
this.timer.cancel();
this.timer.purge();
this.timer = null;
}
}
private class LocationTimeoutTask extends TimerTask {
private CallbackContext callbackContext = null;
private CordovaLocationListener listener = null;
public LocationTimeoutTask(CallbackContext callbackContext, CordovaLocationListener listener) {
this.callbackContext = callbackContext;
this.listener = listener;
}
@Override
public void run() {
for (CallbackContext callbackContext: listener.callbacks) {
if(this.callbackContext == callbackContext) {
listener.callbacks.remove(callbackContext);
break;
}
}
if(listener.size() == 0) {
listener.stop();
}
}
}
}

View File

@@ -19,20 +19,18 @@
package org.apache.cordova;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.cordova.Config;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.PluginManager;
import org.apache.cordova.api.PluginResult;
import org.json.JSONException;
import org.xmlpull.v1.XmlPullParserException;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
@@ -40,35 +38,35 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.XmlResourceParser;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebBackForwardList;
import android.webkit.WebHistoryItem;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.widget.FrameLayout;
public class CordovaWebView extends WebView {
public static final String TAG = "CordovaWebView";
/** The whitelist **/
private ArrayList<Pattern> whiteList = new ArrayList<Pattern>();
private HashMap<String, Boolean> whiteListCache = new HashMap<String, Boolean>();
private ArrayList<Integer> keyDownCodes = new ArrayList<Integer>();
private ArrayList<Integer> keyUpCodes = new ArrayList<Integer>();
public PluginManager pluginManager;
private boolean paused;
private BroadcastReceiver receiver;
@@ -78,27 +76,47 @@ public class CordovaWebView extends WebView {
@SuppressWarnings("unused")
private CordovaChromeClient chromeClient;
//This is for the polyfill history
private String url;
String baseUrl;
private Stack<String> urls = new Stack<String>();
boolean useBrowserHistory = true;
// Flag to track that a loadUrl timeout occurred
int loadUrlTimeout = 0;
private boolean bound;
private boolean volumedownBound;
private boolean volumeupBound;
private boolean handleButton = false;
private long lastMenuEventTime = 0;
NativeToJsMessageQueue jsMessageQueue;
ExposedJsApi exposedJsApi;
NativeToJsMessageQueue jsMessageQueue;
ExposedJsApi exposedJsApi;
/** custom view created by the browser (a video player for example) */
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
private ActivityResult mResult = null;
class ActivityResult {
int request;
int result;
Intent incoming;
public ActivityResult(int req, int res, Intent intent) {
request = req;
result = res;
incoming = intent;
}
}
static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
/**
* Constructor.
*
@@ -159,7 +177,6 @@ public class CordovaWebView extends WebView {
Log.d(TAG, "Your activity must implement CordovaInterface to work");
}
this.setWebChromeClient(new CordovaChromeClient(this.cordova, this));
this.initWebViewClient(this.cordova);
this.loadConfiguration();
this.setup();
}
@@ -172,8 +189,8 @@ public class CordovaWebView extends WebView {
* @param defStyle
* @param privateBrowsing
*/
@TargetApi(11)
public CordovaWebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) {
@TargetApi(11)
public CordovaWebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) {
super(context, attrs, defStyle, privateBrowsing);
if (CordovaInterface.class.isInstance(context))
{
@@ -191,7 +208,8 @@ public class CordovaWebView extends WebView {
private void initWebViewClient(CordovaInterface cordova) {
if(android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.HONEYCOMB)
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB ||
android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.JELLY_BEAN_MR1)
{
this.setWebViewClient(new CordovaWebViewClient(this.cordova, this));
}
@@ -216,19 +234,43 @@ public class CordovaWebView extends WebView {
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
// Set the nav dump for HTC 2.x devices (disabling for ICS, deprecated entirely for Jellybean 4.2)
try {
Method gingerbread_getMethod = WebSettings.class.getMethod("setNavDump", new Class[] { boolean.class });
String manufacturer = android.os.Build.MANUFACTURER;
Log.d(TAG, "CordovaWebView is running on device made by: " + manufacturer);
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB &&
android.os.Build.MANUFACTURER.contains("HTC"))
{
gingerbread_getMethod.invoke(settings, true);
}
} catch (NoSuchMethodException e) {
Log.d(TAG, "We are on a modern version of Android, we will deprecate HTC 2.3 devices in 2.8");
} catch (IllegalArgumentException e) {
Log.d(TAG, "Doing the NavDump failed with bad arguments");
} catch (IllegalAccessException e) {
Log.d(TAG, "This should never happen: IllegalAccessException means this isn't Android anymore");
} catch (InvocationTargetException e) {
Log.d(TAG, "This should never happen: InvocationTargetException means this isn't Android anymore.");
}
//Set the nav dump for HTC 2.x devices (disabling for ICS/Jellybean)
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
settings.setNavDump(true);
//We don't save any form data in the application
settings.setSaveFormData(false);
settings.setSavePassword(false);
// Jellybean rightfully tried to lock this down. Too bad they didn't give us a whitelist
// while we do this
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
Level16Apis.enableUniversalAccess(settings);
Level16Apis.enableUniversalAccess(settings);
// Enable database
settings.setDatabaseEnabled(true);
// We keep this disabled because we use or shim to get around DOM_EXCEPTION_ERROR_16
String databasePath = this.cordova.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
settings.setDatabaseEnabled(true);
settings.setDatabasePath(databasePath);
settings.setGeolocationDatabasePath(databasePath);
// Enable DOM storage
settings.setDomStorageEnabled(true);
@@ -236,6 +278,13 @@ public class CordovaWebView extends WebView {
// Enable built-in geolocation
settings.setGeolocationEnabled(true);
// Enable AppCache
// Fix for CB-2282
settings.setAppCacheMaxSize(5 * 1048576);
String pathToCache = this.cordova.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
settings.setAppCachePath(pathToCache);
settings.setAppCacheEnabled(true);
// Fix for CB-1405
// Google issue 4641
this.updateUserAgentString();
@@ -260,12 +309,20 @@ public class CordovaWebView extends WebView {
}
private void updateUserAgentString() {
this.getSettings().getUserAgentString();
this.getSettings().getUserAgentString();
}
private void exposeJsInterface() {
// addJavascriptInterface crashes on the 2.3 emulator.
if (Build.VERSION.RELEASE.startsWith("2.3") && Build.MANUFACTURER.equals("unknown")) {
int SDK_INT = Build.VERSION.SDK_INT;
boolean isHoneycomb = (SDK_INT >= Build.VERSION_CODES.HONEYCOMB && SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2);
if (isHoneycomb || (SDK_INT < Build.VERSION_CODES.GINGERBREAD)) {
Log.i(TAG, "Disabled addJavascriptInterface() bridge since Android version is old.");
// Bug being that Java Strings do not get converted to JS strings automatically.
// This isn't hard to work-around on the JS side, but it's easier to just
// use the prompt bridge instead.
return;
} else if (SDK_INT < Build.VERSION_CODES.HONEYCOMB && Build.MANUFACTURER.equals("unknown")) {
// addJavascriptInterface crashes on the 2.3 emulator.
Log.i(TAG, "Disabled addJavascriptInterface() bridge callback due to a bug on the 2.3 emulator");
return;
}
@@ -291,71 +348,9 @@ public class CordovaWebView extends WebView {
this.chromeClient = client;
super.setWebChromeClient(client);
}
/**
* Add entry to approved list of URLs (whitelist)
*
* @param origin URL regular expression to allow
* @param subdomains T=include all subdomains under origin
*/
public void addWhiteListEntry(String origin, boolean subdomains) {
try {
// Unlimited access to network resources
if (origin.compareTo("*") == 0) {
LOG.d(TAG, "Unlimited access to network resources");
this.whiteList.add(Pattern.compile(".*"));
} else { // specific access
// check if subdomains should be included
// TODO: we should not add more domains if * has already been added
if (subdomains) {
// XXX making it stupid friendly for people who forget to include protocol/SSL
if (origin.startsWith("http")) {
this.whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://(.*\\.)?")));
} else {
this.whiteList.add(Pattern.compile("^https?://(.*\\.)?" + origin));
}
LOG.d(TAG, "Origin to allow with subdomains: %s", origin);
} else {
// XXX making it stupid friendly for people who forget to include protocol/SSL
if (origin.startsWith("http")) {
this.whiteList.add(Pattern.compile(origin.replaceFirst("https?://", "^https?://")));
} else {
this.whiteList.add(Pattern.compile("^https?://" + origin));
}
LOG.d(TAG, "Origin to allow: %s", origin);
}
}
} catch (Exception e) {
LOG.d(TAG, "Failed to add origin %s", origin);
}
}
/**
* Determine if URL is in approved list of URLs to load.
*
* @param url
* @return
*/
public boolean isUrlWhiteListed(String url) {
// Check to see if we have matched url previously
if (this.whiteListCache.get(url) != null) {
return true;
}
// Look for match in white list
Iterator<Pattern> pit = this.whiteList.iterator();
while (pit.hasNext()) {
Pattern p = pit.next();
Matcher m = p.matcher(url);
// If match found, then cache it to speed up subsequent comparisons
if (m.find()) {
this.whiteListCache.put(url, true);
return true;
}
}
return false;
public CordovaChromeClient getWebChromeClient() {
return this.chromeClient;
}
/**
@@ -373,7 +368,7 @@ public class CordovaWebView extends WebView {
String initUrl = this.getProperty("url", null);
// If first page of app, then set URL to load to be the one passed in
if (initUrl == null || (this.urls.size() > 0)) {
if (initUrl == null) {
this.loadUrlIntoView(url);
}
// Otherwise use the URL specified in the activity's extras bundle
@@ -394,7 +389,7 @@ public class CordovaWebView extends WebView {
String initUrl = this.getProperty("url", null);
// If first page of app, then set URL to load to be the one passed in
if (initUrl == null || (this.urls.size() > 0)) {
if (initUrl == null) {
this.loadUrlIntoView(url, time);
}
// Otherwise use the URL specified in the activity's extras bundle
@@ -412,21 +407,8 @@ public class CordovaWebView extends WebView {
LOG.d(TAG, ">>> loadUrl(" + url + ")");
this.url = url;
if (this.baseUrl == null) {
int i = url.lastIndexOf('/');
if (i > 0) {
this.baseUrl = url.substring(0, i + 1);
}
else {
this.baseUrl = this.url + "/";
}
this.pluginManager.init();
this.pluginManager.init();
if (!this.useBrowserHistory) {
this.urls.push(url);
}
}
// Create a timeout timer for loadUrl
final CordovaWebView me = this;
@@ -481,8 +463,8 @@ public class CordovaWebView extends WebView {
if (LOG.isLoggable(LOG.DEBUG) && !url.startsWith("javascript:")) {
LOG.d(TAG, ">>> loadUrlNow()");
}
if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || url.startsWith("javascript:") || this.isUrlWhiteListed(url)) {
super.loadUrl(url);
if (url.startsWith("file://") || url.startsWith("javascript:") || Config.isUrlWhiteListed(url)) {
super.loadUrl(url);
}
}
@@ -497,7 +479,7 @@ public class CordovaWebView extends WebView {
// If not first page of app, then load immediately
// Add support for browser history if we use it.
if ((url.startsWith("javascript:")) || this.urls.size() > 0 || this.canGoBack()) {
if ((url.startsWith("javascript:")) || this.canGoBack()) {
}
// If first page, then show splashscreen
@@ -545,25 +527,6 @@ public class CordovaWebView extends WebView {
}
}
/**
* Returns the top url on the stack without removing it from
* the stack.
*/
public String peekAtUrlStack() {
if (this.urls.size() > 0) {
return this.urls.peek();
}
return "";
}
/**
* Add a url to the stack
*
* @param url
*/
public void pushUrl(String url) {
this.urls.push(url);
}
/**
* Go to previous page in history. (We manage our own history)
@@ -575,37 +538,14 @@ public class CordovaWebView extends WebView {
// Check webview first to see if there is a history
// This is needed to support curPage#diffLink, since they are added to appView's history, but not our history url array (JQMobile behavior)
if (super.canGoBack()) {
printBackForwardList();
printBackForwardList();
super.goBack();
return true;
}
// If our managed history has prev url
if (this.urls.size() > 1 && !this.useBrowserHistory) {
this.urls.pop(); // Pop current url
String url = this.urls.pop(); // Pop prev url that we want to load, since it will be added back by loadUrl()
this.loadUrl(url);
return true;
}
return false;
}
/**
* Return true if there is a history item.
*
* @return
*/
public boolean canGoBack() {
if (super.canGoBack()) {
return true;
}
if (this.urls.size() > 1) {
return true;
}
return false;
}
/**
* Load the specified URL in the Cordova webview or a new browser instance.
@@ -629,14 +569,8 @@ public class CordovaWebView extends WebView {
if (!openExternal) {
// Make sure url is in whitelist
if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || isUrlWhiteListed(url)) {
if (url.startsWith("file://") || Config.isUrlWhiteListed(url)) {
// TODO: What about params?
// Clear out current url from history, since it will be replacing it
if (clearHistory) {
this.urls.clear();
}
// Load new URL
this.loadUrl(url);
}
@@ -666,70 +600,14 @@ public class CordovaWebView extends WebView {
}
/**
* Load Cordova configuration from res/xml/cordova.xml.
* Check configuration parameters from Config.
* Approved list of URLs that can be loaded into DroidGap
* <access origin="http://server regexp" subdomains="true" />
* Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR)
* <log level="DEBUG" />
*/
private void loadConfiguration() {
int id = getResources().getIdentifier("config", "xml", this.cordova.getActivity().getPackageName());
if(id == 0)
{
id = getResources().getIdentifier("cordova", "xml", this.cordova.getActivity().getPackageName());
Log.i("CordovaLog", "config.xml missing, reverting to cordova.xml");
}
if (id == 0) {
LOG.i("CordovaLog", "cordova.xml missing. Ignoring...");
return;
}
XmlResourceParser xml = getResources().getXml(id);
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = xml.getName();
if (strNode.equals("access")) {
String origin = xml.getAttributeValue(null, "origin");
String subdomains = xml.getAttributeValue(null, "subdomains");
if (origin != null) {
this.addWhiteListEntry(origin, (subdomains != null) && (subdomains.compareToIgnoreCase("true") == 0));
}
}
else if (strNode.equals("log")) {
String level = xml.getAttributeValue(null, "level");
LOG.i("CordovaLog", "Found log level %s", level);
if (level != null) {
LOG.setLogLevel(level);
}
}
else if (strNode.equals("preference")) {
String name = xml.getAttributeValue(null, "name");
String value = xml.getAttributeValue(null, "value");
LOG.i("CordovaLog", "Found preference for %s=%s", name, value);
Log.d("CordovaLog", "Found preference for " + name + "=" + value);
// Save preferences in Intent
this.cordova.getActivity().getIntent().putExtra(name, value);
}
}
try {
eventType = xml.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Init preferences
if ("false".equals(this.getProperty("useBrowserHistory", "false"))) {
this.useBrowserHistory = false;
}
else {
this.useBrowserHistory = true;
}
if ("true".equals(this.getProperty("fullscreen", "false"))) {
this.cordova.getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
this.cordova.getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
@@ -782,13 +660,20 @@ public class CordovaWebView extends WebView {
}
else if(keyCode == KeyEvent.KEYCODE_BACK)
{
//Because exit is fired on the keyDown and not the key up on Android 4.x
//we need to check for this.
//Also, I really wished "canGoBack" worked!
if(this.useBrowserHistory)
return !(this.startOfHistory()) || this.bound;
else
return this.urls.size() > 1 || this.bound;
return !(this.startOfHistory()) || this.bound;
}
else if(keyCode == KeyEvent.KEYCODE_MENU)
{
//How did we get here? Is there a childView?
View childView = this.getFocusedChild();
if(childView != null)
{
//Make sure we close the keyboard if it's present
InputMethodManager imm = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(childView.getWindowToken(), 0);
cordova.getActivity().openOptionsMenu();
}
return true;
}
return super.onKeyDown(keyCode, event);
@@ -800,26 +685,37 @@ public class CordovaWebView extends WebView {
{
// If back key
if (keyCode == KeyEvent.KEYCODE_BACK) {
// If back key is bound, then send event to JavaScript
if (this.bound) {
this.loadUrl("javascript:cordova.fireDocumentEvent('backbutton');");
return true;
// A custom view is currently displayed (e.g. playing a video)
if(mCustomView != null) {
this.hideCustomView();
} else {
// If not bound
// Go to previous page in webview if it is possible to go back
if (this.backHistory()) {
// The webview is currently displayed
// If back key is bound, then send event to JavaScript
if (this.bound) {
this.loadUrl("javascript:cordova.fireDocumentEvent('backbutton');");
return true;
}
// If not, then invoke default behavior
else {
//this.activityState = ACTIVITY_EXITING;
return false;
} else {
// If not bound
// Go to previous page in webview if it is possible to go back
if (this.backHistory()) {
return true;
}
// If not, then invoke default behaviour
else {
//this.activityState = ACTIVITY_EXITING;
//return false;
// If they hit back button when app is initializing, app should exit instead of hang until initilazation (CB2-458)
this.cordova.getActivity().finish();
}
}
}
}
// Legacy
else if (keyCode == KeyEvent.KEYCODE_MENU) {
this.loadUrl("javascript:cordova.fireDocumentEvent('menubutton');");
if (this.lastMenuEventTime < event.getEventTime()) {
this.loadUrl("javascript:cordova.fireDocumentEvent('menubutton');");
}
this.lastMenuEventTime = event.getEventTime();
return super.onKeyUp(keyCode, event);
}
// If search key
@@ -892,9 +788,8 @@ public class CordovaWebView extends WebView {
public void handleResume(boolean keepRunning, boolean activityResultKeepRunning)
{
// Send resume event to JavaScript
this.loadUrl("javascript:try{cordova.fireDocumentEvent('resume');}catch(e){console.log('exception firing resume event from native');};");
// Forward to plugins
if (this.pluginManager != null) {
this.pluginManager.onResume(keepRunning);
@@ -908,7 +803,8 @@ public class CordovaWebView extends WebView {
public void handleDestroy()
{
// Send destroy event to JavaScript
this.loadUrl("javascript:try{cordova.require('cordova/channel').onDestroy.fire();}catch(e){console.log('exception firing destroy event from native');};");
// Since baseUrl is set in loadUrlIntoView, if user hit Back button before loadUrl was called, we'll get an NPE on baseUrl (CB-2458)
this.loadUrlIntoView("javascript:try{cordova.require('cordova/channel').onDestroy.fire();}catch(e){console.log('exception firing destroy event from native');};");
// Load blank page so that JavaScript onunload is called
this.loadUrl("about:blank");
@@ -955,14 +851,14 @@ public class CordovaWebView extends WebView {
}
public void printBackForwardList() {
WebBackForwardList currentList = this.copyBackForwardList();
int currentSize = currentList.getSize();
for(int i = 0; i < currentSize; ++i)
{
WebHistoryItem item = currentList.getItemAtIndex(i);
String url = item.getUrl();
LOG.d(TAG, "The URL at index: " + Integer.toString(i) + "is " + url );
}
WebBackForwardList currentList = this.copyBackForwardList();
int currentSize = currentList.getSize();
for(int i = 0; i < currentSize; ++i)
{
WebHistoryItem item = currentList.getItemAtIndex(i);
String url = item.getUrl();
LOG.d(TAG, "The URL at index: " + Integer.toString(i) + "is " + url );
}
}
@@ -971,10 +867,79 @@ public class CordovaWebView extends WebView {
{
WebBackForwardList currentList = this.copyBackForwardList();
WebHistoryItem item = currentList.getItemAtIndex(0);
String url = item.getUrl();
String currentUrl = this.getUrl();
LOG.d(TAG, "The current URL is: " + currentUrl);
LOG.d(TAG, "The URL at item 0 is:" + url);
return currentUrl.equals(url);
if( item!=null){ // Null-fence in case they haven't called loadUrl yet (CB-2458)
String url = item.getUrl();
String currentUrl = this.getUrl();
LOG.d(TAG, "The current URL is: " + currentUrl);
LOG.d(TAG, "The URL at item 0 is:" + url);
return currentUrl.equals(url);
}
return false;
}
public void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
// This code is adapted from the original Android Browser code, licensed under the Apache License, Version 2.0
Log.d(TAG, "showing Custom View");
// if a view already exists then immediately terminate the new one
if (mCustomView != null) {
callback.onCustomViewHidden();
return;
}
// Store the view and its callback for later (to kill it properly)
mCustomView = view;
mCustomViewCallback = callback;
// Add the custom view to its container.
ViewGroup parent = (ViewGroup) this.getParent();
parent.addView(view, COVER_SCREEN_GRAVITY_CENTER);
// Hide the content view.
this.setVisibility(View.GONE);
// Finally show the custom view container.
parent.setVisibility(View.VISIBLE);
parent.bringToFront();
}
public void hideCustomView() {
// This code is adapted from the original Android Browser code, licensed under the Apache License, Version 2.0
Log.d(TAG, "Hidding Custom View");
if (mCustomView == null) return;
// Hide the custom view.
mCustomView.setVisibility(View.GONE);
// Remove the custom view from its container.
ViewGroup parent = (ViewGroup) this.getParent();
parent.removeView(mCustomView);
mCustomView = null;
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
this.setVisibility(View.VISIBLE);
}
/**
* if the video overlay is showing then we need to know
* as it effects back button handling
*
* @return
*/
public boolean isCustomViewShowing() {
return mCustomView != null;
}
public WebBackForwardList restoreState(Bundle savedInstanceState)
{
WebBackForwardList myList = super.restoreState(savedInstanceState);
Log.d(TAG, "WebView restoration crew now restoring!");
//Initialize the plugin manager once more
this.pluginManager.init();
return myList;
}
public void storeResult(int requestCode, int resultCode, Intent intent) {
mResult = new ActivityResult(requestCode, resultCode, intent);
}
}

View File

@@ -18,10 +18,10 @@
*/
package org.apache.cordova;
import java.io.ByteArrayInputStream;
import java.util.Hashtable;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.api.LOG;
import org.json.JSONException;
@@ -39,6 +39,7 @@ import android.util.Log;
import android.view.View;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@@ -67,7 +68,7 @@ public class CordovaWebViewClient extends WebViewClient {
/**
* Constructor.
*
*
* @param cordova
* @param view
*/
@@ -78,7 +79,7 @@ public class CordovaWebViewClient extends WebViewClient {
/**
* Constructor.
*
*
* @param view
*/
public void setWebView(CordovaWebView view) {
@@ -102,8 +103,8 @@ public class CordovaWebViewClient extends WebViewClient {
String callbackId = url.substring(idx3 + 1, idx4);
String jsonArgs = url.substring(idx4 + 1);
appView.pluginManager.exec(service, action, callbackId, jsonArgs);
}
}
/**
* Give the host application a chance to take over the control when a new url
* is about to be loaded in the current WebView.
@@ -193,12 +194,8 @@ public class CordovaWebViewClient extends WebViewClient {
// If our app or file:, then load into a new Cordova webview container by starting a new instance of our activity.
// Our app continues to run. When BACK is pressed, our app is redisplayed.
if (url.startsWith("file://") || url.startsWith("data:") || url.indexOf(this.appView.baseUrl) == 0 || this.appView.isUrlWhiteListed(url)) {
//This will fix iFrames
if (appView.useBrowserHistory || url.startsWith("data:"))
return false;
else
this.appView.loadUrl(url);
if (url.startsWith("file://") || url.startsWith("data:") || Config.isUrlWhiteListed(url)) {
return false;
}
// If not our application, let default viewer handle
@@ -215,6 +212,34 @@ public class CordovaWebViewClient extends WebViewClient {
return true;
}
/**
* Check for intercepting any requests for resources.
* This includes images and scripts and so on, not just top-level pages.
* @param view The WebView.
* @param url The URL to be loaded.
* @return Either null to proceed as normal, or a WebResourceResponse.
*/
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//If something isn't whitelisted, just send a blank response
if(!Config.isUrlWhiteListed(url) && (url.startsWith("http://") || url.startsWith("https://")))
{
return getWhitelistResponse();
}
if (this.appView.pluginManager != null) {
return this.appView.pluginManager.shouldInterceptRequest(url);
}
return null;
}
private WebResourceResponse getWhitelistResponse()
{
WebResourceResponse emptyResponse;
String empty = "";
ByteArrayInputStream data = new ByteArrayInputStream(empty.getBytes());
return new WebResourceResponse("text/plain", "UTF-8", data);
}
/**
* On received http auth request.
* The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination
@@ -232,25 +257,23 @@ public class CordovaWebViewClient extends WebViewClient {
if (token != null) {
handler.proceed(token.getUserName(), token.getPassword());
}
else {
// Handle 401 like we'd normally do!
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
}
/**
* Notify the host application that a page has started loading.
* This method is called once for each main frame load so a page with iframes or framesets will call onPageStarted
* one time for the main frame. This also means that onPageStarted will not be called when the contents of an
* embedded frame changes, i.e. clicking a link whose target is an iframe.
*
* Notify the host application that a page has started loading.
* This method is called once for each main frame load so a page with iframes or framesets will call onPageStarted
* one time for the main frame. This also means that onPageStarted will not be called when the contents of an
* embedded frame changes, i.e. clicking a link whose target is an iframe.
*
* @param view The webview initiating the callback.
* @param url The url of the page.
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Clear history so history.back() doesn't do anything.
// So we can reinit() native side CallbackServer & PluginManager.
if (!this.appView.useBrowserHistory) {
view.clearHistory();
this.doClearHistory = true;
}
// Flush stale messages.
this.appView.jsMessageQueue.reset();
@@ -267,7 +290,7 @@ public class CordovaWebViewClient extends WebViewClient {
/**
* Notify the host application that a page has finished loading.
* This method is called only for main frame. When onPageFinished() is called, the rendering picture may not be updated yet.
*
*
*
* @param view The webview initiating the callback.
* @param url The url of the page.
@@ -291,14 +314,6 @@ public class CordovaWebViewClient extends WebViewClient {
// Clear timeout flag
this.appView.loadUrlTimeout++;
// Try firing the onNativeReady event in JS. If it fails because the JS is
// not loaded yet then just set a flag so that the onNativeReady can be fired
// from the JS side when the JS gets to that code.
if (!url.equals("about:blank")) {
this.appView.loadUrl("javascript:try{ cordova.require('cordova/channel').onNativeReady.fire();}catch(e){_nativeReady = true;}");
this.appView.postMessage("onNativeReady", null);
}
// Broadcast message that page has loaded
this.appView.postMessage("onPageFinished", url);
@@ -355,11 +370,11 @@ public class CordovaWebViewClient extends WebViewClient {
}
/**
* Notify the host application that an SSL error occurred while loading a resource.
* The host application must call either handler.cancel() or handler.proceed().
* Note that the decision may be retained for use in response to future SSL errors.
* Notify the host application that an SSL error occurred while loading a resource.
* The host application must call either handler.cancel() or handler.proceed().
* Note that the decision may be retained for use in response to future SSL errors.
* The default behavior is to cancel the load.
*
*
* @param view The WebView that is initiating the callback.
* @param handler An SslErrorHandler object that will handle the user's response.
* @param error The SSL error object.
@@ -388,27 +403,10 @@ public class CordovaWebViewClient extends WebViewClient {
}
}
/**
* Notify the host application to update its visited links database.
*
* @param view The WebView that is initiating the callback.
* @param url The url being visited.
* @param isReload True if this url is being reloaded.
*/
@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
/*
* If you do a document.location.href the url does not get pushed on the stack
* so we do a check here to see if the url should be pushed.
*/
if (!this.appView.peekAtUrlStack().equals(url)) {
this.appView.pushUrl(url);
}
}
/**
* Sets the authentication token.
*
*
* @param authenticationToken
* @param host
* @param realm
@@ -425,10 +423,10 @@ public class CordovaWebViewClient extends WebViewClient {
/**
* Removes the authentication token.
*
*
* @param host
* @param realm
*
*
* @return the authentication token or null if did not exist
*/
public AuthenticationToken removeAuthenticationToken(String host, String realm) {
@@ -437,16 +435,16 @@ public class CordovaWebViewClient extends WebViewClient {
/**
* Gets the authentication token.
*
*
* In order it tries:
* 1- host + realm
* 2- host
* 3- realm
* 4- no host, no realm
*
*
* @param host
* @param realm
*
*
* @return the authentication token
*/
public AuthenticationToken getAuthenticationToken(String host, String realm) {

View File

@@ -24,7 +24,6 @@ import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@@ -39,7 +38,7 @@ import android.telephony.TelephonyManager;
public class Device extends CordovaPlugin {
public static final String TAG = "Device";
public static String cordovaVersion = "2.2.0rc1"; // Cordova version
public static String cordovaVersion = "2.7.0"; // Cordova version
public static String platform = "Android"; // Device OS
public static String uuid; // Device UUID
@@ -78,11 +77,8 @@ public class Device extends CordovaPlugin {
r.put("uuid", Device.uuid);
r.put("version", this.getOSVersion());
r.put("platform", Device.platform);
r.put("name", this.getProductName());
r.put("cordova", Device.cordovaVersion);
//JSONObject pg = new JSONObject();
//pg.put("version", Device.CordovaVersion);
//r.put("cordova", pg);
r.put("model", this.getModel());
callbackContext.success(r);
}
else {

View File

@@ -28,6 +28,7 @@ import org.apache.cordova.api.LOG;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
@@ -38,6 +39,7 @@ import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
@@ -49,7 +51,8 @@ import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.ImageView;
import android.webkit.ValueCallback;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
@@ -156,11 +159,6 @@ public class DroidGap extends Activity implements CordovaInterface {
private static int ACTIVITY_EXITING = 2;
private int activityState = 0; // 0=starting, 1=running (after 1st resume), 2=shutting down
// The base of the initial URL for our app.
// Does not include file name. Ends with /
// ie http://server/path/
String baseUrl = null;
// Plugin to call when activity result is received
protected CordovaPlugin activityResultCallback = null;
protected boolean activityResultKeepRunning;
@@ -176,7 +174,7 @@ public class DroidGap extends Activity implements CordovaInterface {
// Draw a splash screen using an image located in the drawable resource directory.
// This is not the same as calling super.loadSplashscreen(url)
protected int splashscreen = 0;
protected int splashscreenTime = 0;
protected int splashscreenTime = 3000;
// LoadUrl timeout value in msec (default of 20 sec)
protected int loadUrlTimeoutValue = 20000;
@@ -186,6 +184,18 @@ public class DroidGap extends Activity implements CordovaInterface {
// when another application (activity) is started.
protected boolean keepRunning = true;
private int lastRequestCode;
private Object responseCode;
private Intent lastIntent;
private Object lastResponseCode;
private String initCallbackClass;
private Object LOG_TAG;
/**
* Sets the authentication token.
*
@@ -252,11 +262,15 @@ public class DroidGap extends Activity implements CordovaInterface {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
//preferences = new PreferenceSet();
Config.init(this);
LOG.d(TAG, "DroidGap.onCreate()");
super.onCreate(savedInstanceState);
if(savedInstanceState != null)
{
initCallbackClass = savedInstanceState.getString("callbackClass");
}
if(!this.getBooleanProperty("showTitle", false))
{
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
@@ -301,7 +315,16 @@ public class DroidGap extends Activity implements CordovaInterface {
*/
public void init() {
CordovaWebView webView = new CordovaWebView(DroidGap.this);
this.init(webView, new CordovaWebViewClient(this, webView), new CordovaChromeClient(this, webView));
CordovaWebViewClient webViewClient;
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
{
webViewClient = new CordovaWebViewClient(this, webView);
}
else
{
webViewClient = new IceCreamCordovaWebViewClient(this, webView);
}
this.init(webView, webViewClient, new CordovaChromeClient(this, webView));
}
/**
@@ -311,6 +334,7 @@ public class DroidGap extends Activity implements CordovaInterface {
* @param webViewClient
* @param webChromeClient
*/
@SuppressLint("NewApi")
public void init(CordovaWebView webView, CordovaWebViewClient webViewClient, CordovaChromeClient webChromeClient) {
LOG.d(TAG, "DroidGap.init()");
@@ -328,6 +352,12 @@ public class DroidGap extends Activity implements CordovaInterface {
ViewGroup.LayoutParams.MATCH_PARENT,
1.0F));
if (this.getBooleanProperty("disallowOverscroll", false)) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
this.appView.setOverScrollMode(CordovaWebView.OVER_SCROLL_NEVER);
}
}
// Add web view but make it invisible while loading URL
this.appView.setVisibility(View.INVISIBLE);
this.root.addView(this.appView);
@@ -335,6 +365,7 @@ public class DroidGap extends Activity implements CordovaInterface {
// Clear cancel flag
this.cancelLoadUrl = false;
}
/**
@@ -568,6 +599,7 @@ public class DroidGap extends Activity implements CordovaInterface {
* @param value
*/
public void setBooleanProperty(String name, boolean value) {
Log.d(TAG, "Setting boolean properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml");
this.getIntent().putExtra(name, value);
}
@@ -578,6 +610,7 @@ public class DroidGap extends Activity implements CordovaInterface {
* @param value
*/
public void setIntegerProperty(String name, int value) {
Log.d(TAG, "Setting integer properties in DroidGap will be deprecated in 3.1 on August 2013, please use config.xml");
this.getIntent().putExtra(name, value);
}
@@ -588,6 +621,7 @@ public class DroidGap extends Activity implements CordovaInterface {
* @param value
*/
public void setStringProperty(String name, String value) {
Log.d(TAG, "Setting string properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml");
this.getIntent().putExtra(name, value);
}
@@ -598,6 +632,7 @@ public class DroidGap extends Activity implements CordovaInterface {
* @param value
*/
public void setDoubleProperty(String name, double value) {
Log.d(TAG, "Setting double properties in DroidGap will be deprecated in 3.0 on July 2013, please use config.xml");
this.getIntent().putExtra(name, value);
}
@@ -683,7 +718,7 @@ public class DroidGap extends Activity implements CordovaInterface {
appView.handleDestroy();
}
else {
this.endActivity();
this.activityState = ACTIVITY_EXITING;
}
}
@@ -797,9 +832,35 @@ public class DroidGap extends Activity implements CordovaInterface {
* @param data An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
*/
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
LOG.d(TAG, "Incoming Result");
super.onActivityResult(requestCode, resultCode, intent);
Log.d(TAG, "Request code = " + requestCode);
ValueCallback<Uri> mUploadMessage = this.appView.getWebChromeClient().getValueCallback();
if (requestCode == CordovaChromeClient.FILECHOOSER_RESULTCODE) {
Log.d(TAG, "did we get here?");
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
Log.d(TAG, "result = " + result);
// Uri filepath = Uri.parse("file://" + FileUtils.getRealPathFromURI(result, this));
// Log.d(TAG, "result = " + filepath);
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
CordovaPlugin callback = this.activityResultCallback;
if (callback != null) {
if(callback == null)
{
if(initCallbackClass != null)
{
this.activityResultCallback = appView.pluginManager.getPlugin(initCallbackClass);
callback = activityResultCallback;
LOG.d(TAG, "We have a callback to send this result to");
callback.onActivityResult(requestCode, resultCode, intent);
}
}
else
{
LOG.d(TAG, "We have a callback to send this result to");
callback.onActivityResult(requestCode, resultCode, intent);
}
}
@@ -821,7 +882,7 @@ public class DroidGap extends Activity implements CordovaInterface {
// If errorUrl specified, then load it
final String errorUrl = me.getStringProperty("errorUrl", null);
if ((errorUrl != null) && (errorUrl.startsWith("file://") || errorUrl.indexOf(me.baseUrl) == 0 || this.appView.isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) {
if ((errorUrl != null) && (errorUrl.startsWith("file://") || Config.isUrlWhiteListed(errorUrl)) && (!failingUrl.equals(errorUrl))) {
// Load URL on UI thread
me.runOnUiThread(new Runnable() {
@@ -837,8 +898,7 @@ public class DroidGap extends Activity implements CordovaInterface {
final boolean exit = !(errorCode == WebViewClient.ERROR_HOST_LOOKUP);
me.runOnUiThread(new Runnable() {
public void run() {
if (exit)
{
if (exit) {
me.appView.setVisibility(View.GONE);
me.displayError("Application Error", description + " (" + failingUrl + ")", "OK", exit);
}
@@ -889,11 +949,7 @@ public class DroidGap extends Activity implements CordovaInterface {
* @return
*/
public boolean isUrlWhiteListed(String url) {
// Check to see if we have matched url previously
if (this.appView != null) {
return this.appView.isUrlWhiteListed(url);
}
return false;
return Config.isUrlWhiteListed(url);
}
/*
@@ -909,7 +965,7 @@ public class DroidGap extends Activity implements CordovaInterface {
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
this.postMessage("onPrepareOptionsMenu", menu);
return false;
return true;
}
@Override
@@ -976,7 +1032,13 @@ public class DroidGap extends Activity implements CordovaInterface {
root.setBackgroundColor(that.getIntegerProperty("backgroundColor", Color.BLACK));
root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT, 0.0F));
root.setBackgroundResource(that.splashscreen);
// We want the splashscreen to keep its ratio,
// for this we need to use an ImageView and not simply the background of the LinearLayout
ImageView splashscreenView = new ImageView(that.getActivity());
splashscreenView.setImageResource(that.splashscreen);
splashscreenView.setScaleType(ImageView.ScaleType.CENTER_CROP); // similar to the background-size:cover CSS property
splashscreenView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
root.addView(splashscreenView);
// Create and show the dialog
splashDialog = new Dialog(that, android.R.style.Theme_Translucent_NoTitleBar);
@@ -1005,14 +1067,14 @@ public class DroidGap extends Activity implements CordovaInterface {
@Override
public boolean onKeyUp(int keyCode, KeyEvent event)
{
//Determine if the focus is on the current view or not
if (appView.getHitTestResult() != null &&
appView.getHitTestResult().getType() == WebView.HitTestResult.EDIT_TEXT_TYPE &&
keyCode == KeyEvent.KEYCODE_BACK) {
return appView.onKeyUp(keyCode, event);
//Get whatever has focus!
View childView = appView.getFocusedChild();
if ((appView.isCustomViewShowing() || childView != null ) &&
(keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU)) {
return appView.onKeyUp(keyCode, event);
} else {
return super.onKeyUp(keyCode, event);
}
else
return super.onKeyUp(keyCode, event);
}
/*
@@ -1025,10 +1087,10 @@ public class DroidGap extends Activity implements CordovaInterface {
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//Get whatever has focus!
View childView = appView.getFocusedChild();
//Determine if the focus is on the current view or not
if (appView.getHitTestResult() != null &&
appView.getHitTestResult().getType() == WebView.HitTestResult.EDIT_TEXT_TYPE &&
keyCode == KeyEvent.KEYCODE_BACK) {
if (childView != null && (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU)) {
return appView.onKeyDown(keyCode, event);
}
else
@@ -1051,9 +1113,9 @@ public class DroidGap extends Activity implements CordovaInterface {
}
else {
// If the splash dialog is showing don't try to show it again
if (this.splashDialog != null && !this.splashDialog.isShowing()) {
this.splashscreen = this.getIntegerProperty("splashscreen", 0);
this.showSplashScreen(this.splashscreenTime);
if (this.splashDialog == null || !this.splashDialog.isShowing()) {
this.splashscreen = this.getIntegerProperty("splashscreen", 0);
this.showSplashScreen(this.splashscreenTime);
}
}
}
@@ -1080,4 +1142,15 @@ public class DroidGap extends Activity implements CordovaInterface {
public ExecutorService getThreadPool() {
return threadPool;
}
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if(this.activityResultCallback != null)
{
String cClass = this.activityResultCallback.getClass().getName();
outState.putString("callbackClass", cClass);
}
}
}

View File

@@ -20,24 +20,28 @@ package org.apache.cordova;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
public class Echo extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String result = args.getString(0);
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) throws JSONException {
if ("echo".equals(action)) {
final String result = args.isNull(0) ? null : args.getString(0);
callbackContext.success(result);
return true;
} else if ("echoAsync".equals(action)) {
final String result = args.isNull(0) ? null : args.getString(0);
cordova.getThreadPool().execute(new Runnable() {
public void run() {
callbackContext.success(result);
}
});
return true;
} else if ("echoArrayBuffer".equals(action)) {
final byte[] result = args.getArrayBuffer(0);
callbackContext.success(result);
return true;
}
return false;
}

View File

@@ -18,6 +18,7 @@
*/
package org.apache.cordova;
import android.webkit.JavascriptInterface;
import org.apache.cordova.api.PluginManager;
import org.apache.cordova.api.PluginResult;
import org.json.JSONException;
@@ -37,7 +38,14 @@ import org.json.JSONException;
this.jsMessageQueue = jsMessageQueue;
}
@JavascriptInterface
public String exec(String service, String action, String callbackId, String arguments) throws JSONException {
// If the arguments weren't received, send a message back to JS. It will switch bridge modes and try again. See CB-2666.
// We send a message meant specifically for this case. It starts with "@" so no other message can be encoded into the same string.
if (arguments == null) {
return "@Null arguments.";
}
jsMessageQueue.setPaused(true);
try {
boolean wasSync = pluginManager.exec(service, action, callbackId, arguments);
@@ -51,10 +59,12 @@ import org.json.JSONException;
}
}
@JavascriptInterface
public void setNativeToJsBridgeMode(int value) {
jsMessageQueue.setBridgeMode(value);
}
@JavascriptInterface
public String retrieveJsMessages() {
return jsMessageQueue.popAndEncode();
}

View File

@@ -0,0 +1,149 @@
/*
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;
import android.database.Cursor;
import android.net.Uri;
import android.webkit.MimeTypeMap;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.LOG;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.util.Locale;
public class FileHelper {
private static final String LOG_TAG = "FileUtils";
private static final String _DATA = "_data";
/**
* Returns the real path of the given URI string.
* If the given URI string represents a content:// URI, the real path is retrieved from the media store.
*
* @param uriString the URI string of the audio/image/video
* @param cordova the current application context
* @return the full path to the file
*/
@SuppressWarnings("deprecation")
public static String getRealPath(String uriString, CordovaInterface cordova) {
String realPath = null;
if (uriString.startsWith("content://")) {
String[] proj = { _DATA };
Cursor cursor = cordova.getActivity().managedQuery(Uri.parse(uriString), proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(_DATA);
cursor.moveToFirst();
realPath = cursor.getString(column_index);
if (realPath == null) {
LOG.e(LOG_TAG, "Could get real path for URI string %s", uriString);
}
} else if (uriString.startsWith("file://")) {
realPath = uriString.substring(7);
if (realPath.startsWith("/android_asset/")) {
LOG.e(LOG_TAG, "Cannot get real path for URI string %s because it is a file:///android_asset/ URI.", uriString);
realPath = null;
}
} else {
realPath = uriString;
}
return realPath;
}
/**
* Returns the real path of the given URI.
* If the given URI is a content:// URI, the real path is retrieved from the media store.
*
* @param uri the URI of the audio/image/video
* @param cordova the current application context
* @return the full path to the file
*/
public static String getRealPath(Uri uri, CordovaInterface cordova) {
return FileHelper.getRealPath(uri.toString(), cordova);
}
/**
* Returns an input stream based on given URI string.
*
* @param uriString the URI string from which to obtain the input stream
* @param cordova the current application context
* @return an input stream into the data at the given URI or null if given an invalid URI string
* @throws IOException
*/
public static InputStream getInputStreamFromUriString(String uriString, CordovaInterface cordova) throws IOException {
if (uriString.startsWith("content")) {
Uri uri = Uri.parse(uriString);
return cordova.getActivity().getContentResolver().openInputStream(uri);
} else if (uriString.startsWith("file:///android_asset/")) {
Uri uri = Uri.parse(uriString);
String relativePath = uri.getPath().substring(15);
return cordova.getActivity().getAssets().open(relativePath);
} else {
return new FileInputStream(getRealPath(uriString, cordova));
}
}
/**
* 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://")) {
uriString = uriString.substring(7);
}
return uriString;
}
/**
* Returns the mime type of the data specified by the given URI string.
*
* @param uriString the URI string of the data
* @return the mime type of the specified data
*/
public static String getMimeType(String uriString, CordovaInterface cordova) {
String mimeType = null;
Uri uri = Uri.parse(uriString);
if (uriString.startsWith("content://")) {
mimeType = cordova.getActivity().getContentResolver().getType(uri);
} else {
// MimeTypeMap.getFileExtensionFromUrl() fails when there are query parameters.
String extension = uri.getPath();
int lastDot = extension.lastIndexOf('.');
if (lastDot != -1) {
extension = extension.substring(lastDot + 1);
}
// Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
extension = extension.toLowerCase();
if (extension.equals("3ga")) {
mimeType = "audio/3gpp";
} else {
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
}
return mimeType;
}
}

View File

@@ -18,9 +18,9 @@
*/
package org.apache.cordova;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -28,16 +28,21 @@ import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
@@ -77,6 +82,7 @@ public class FileTransfer extends CordovaPlugin {
private static final class RequestContext {
String source;
String target;
File targetFile;
CallbackContext callbackContext;
InputStream currentInputStream;
OutputStream currentOutputStream;
@@ -95,11 +101,84 @@ public class FileTransfer extends CordovaPlugin {
}
}
/**
* Adds an interface method to an InputStream to return the number of bytes
* read from the raw stream. This is used to track total progress against
* the HTTP Content-Length header value from the server.
*/
private static abstract class TrackingInputStream extends FilterInputStream {
public TrackingInputStream(final InputStream in) {
super(in);
}
public abstract long getTotalRawBytesRead();
}
private static class ExposedGZIPInputStream extends GZIPInputStream {
public ExposedGZIPInputStream(final InputStream in) throws IOException {
super(in);
}
public Inflater getInflater() {
return inf;
}
}
/**
* Provides raw bytes-read tracking for a GZIP input stream. Reports the
* total number of compressed bytes read from the input, rather than the
* number of uncompressed bytes.
*/
private static class TrackingGZIPInputStream extends TrackingInputStream {
private ExposedGZIPInputStream gzin;
public TrackingGZIPInputStream(final ExposedGZIPInputStream gzin) throws IOException {
super(gzin);
this.gzin = gzin;
}
public long getTotalRawBytesRead() {
return gzin.getInflater().getBytesRead();
}
}
/**
* Provides simple total-bytes-read tracking for an existing InputStream
*/
private static class TrackingHTTPInputStream extends TrackingInputStream {
private long bytesRead = 0;
public TrackingHTTPInputStream(InputStream stream) {
super(stream);
}
private int updateBytesRead(int newBytesRead) {
if (newBytesRead != -1) {
bytesRead += newBytesRead;
}
return newBytesRead;
}
@Override
public int read() throws IOException {
return updateBytesRead(super.read());
}
@Override
public int read(byte[] buffer) throws IOException {
return updateBytesRead(super.read(buffer));
}
@Override
public int read(byte[] bytes, int offset, int count) throws IOException {
return updateBytesRead(super.read(bytes, offset, count));
}
public long getTotalRawBytesRead() {
return bytesRead;
}
}
/**
* Works around a bug on Android 2.3.
* http://code.google.com/p/android/issues/detail?id=14562
*/
private static final class DoneHandlerInputStream extends FilterInputStream {
private static final class DoneHandlerInputStream extends TrackingHTTPInputStream {
private boolean done;
public DoneHandlerInputStream(InputStream stream) {
@@ -154,6 +233,25 @@ public class FileTransfer extends CordovaPlugin {
return false;
}
private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {
try {
for (Iterator<?> iter = headers.keys(); iter.hasNext(); ) {
String headerKey = iter.next().toString();
JSONArray headerValues = headers.optJSONArray(headerKey);
if (headerValues == null) {
headerValues = new JSONArray();
headerValues.put(headers.getString(headerKey));
}
connection.setRequestProperty(headerKey, headerValues.getString(0));
for (int i = 1; i < headerValues.length(); ++i) {
connection.addRequestProperty(headerKey, headerValues.getString(i));
}
}
} catch (JSONException e1) {
// No headers to be manipulated!
}
}
/**
* Uploads the specified file to the server URL provided using an HTTP multipart request.
* @param source Full path of the file on the file system
@@ -181,6 +279,7 @@ public class FileTransfer extends CordovaPlugin {
// Look for headers on the params map for backwards compatibility with older Cordova versions.
final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8);
final String objectId = args.getString(9);
final String httpMethod = getArgument(args, 10, "POST");
Log.d(LOG_TAG, "fileKey: " + fileKey);
Log.d(LOG_TAG, "fileName: " + fileName);
@@ -190,17 +289,18 @@ public class FileTransfer extends CordovaPlugin {
Log.d(LOG_TAG, "chunkedMode: " + chunkedMode);
Log.d(LOG_TAG, "headers: " + headers);
Log.d(LOG_TAG, "objectId: " + objectId);
Log.d(LOG_TAG, "httpMethod: " + httpMethod);
final URL url;
try {
url = new URL(target);
} catch (MalformedURLException e) {
JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, 0);
JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
Log.e(LOG_TAG, error.toString(), e);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
return;
}
final boolean useHttps = url.getProtocol().toLowerCase().equals("https");
final boolean useHttps = url.getProtocol().equals("https");
final RequestContext context = new RequestContext(source, target, callbackContext);
synchronized (activeRequests) {
@@ -215,6 +315,8 @@ public class FileTransfer extends CordovaPlugin {
HttpURLConnection conn = null;
HostnameVerifier oldHostnameVerifier = null;
SSLSocketFactory oldSocketFactory = null;
int totalBytes = 0;
int fixedLength = -1;
try {
// Create return object
FileUploadResult result = new FileUploadResult();
@@ -255,8 +357,7 @@ public class FileTransfer extends CordovaPlugin {
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestMethod(httpMethod);
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
// Set the cookies on the response
@@ -267,60 +368,42 @@ public class FileTransfer extends CordovaPlugin {
// Handle the other headers
if (headers != null) {
try {
for (Iterator<?> iter = headers.keys(); iter.hasNext(); ) {
String headerKey = iter.next().toString();
JSONArray headerValues = headers.optJSONArray(headerKey);
if (headerValues == null) {
headerValues = new JSONArray();
headerValues.put(headers.getString(headerKey));
}
conn.setRequestProperty(headerKey, headerValues.getString(0));
for (int i = 1; i < headerValues.length(); ++i) {
conn.addRequestProperty(headerKey, headerValues.getString(i));
}
}
} catch (JSONException e1) {
// No headers to be manipulated!
}
addHeadersToRequest(conn, headers);
}
/*
* Store the non-file portions of the multipart data as a string, so that we can add it
* to the contentSize, since it is part of the body of the HTTP request.
*/
String extraParams = "";
StringBuilder beforeData = new StringBuilder();
try {
for (Iterator<?> iter = params.keys(); iter.hasNext();) {
Object key = iter.next();
if(!String.valueOf(key).equals("headers"))
{
extraParams += LINE_START + BOUNDARY + LINE_END;
extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";";
extraParams += LINE_END + LINE_END;
extraParams += params.getString(key.toString());
extraParams += LINE_END;
beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString()).append('"');
beforeData.append(LINE_END).append(LINE_END);
beforeData.append(params.getString(key.toString()));
beforeData.append(LINE_END);
}
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
extraParams += LINE_START + BOUNDARY + LINE_END;
extraParams += "Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"";
byte[] extraBytes = extraParams.getBytes("UTF-8");
String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END;
String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END;
byte[] fileNameBytes = fileName.getBytes("UTF-8");
beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END);
beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";");
beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END);
beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END);
byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8");
byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END).getBytes("UTF-8");
// Get a input stream of the file on the phone
InputStream sourceInputStream = getPathFromUri(source);
int stringLength = extraBytes.length + midParams.length() + tailParams.length() + fileNameBytes.length;
Log.d(LOG_TAG, "String Length: " + stringLength);
int fixedLength = -1;
int stringLength = beforeDataBytes.length + tailParamsBytes.length;
if (sourceInputStream instanceof FileInputStream) {
fixedLength = (int) ((FileInputStream)sourceInputStream).getChannel().size() + stringLength;
progress.setLengthComputable(true);
@@ -332,7 +415,7 @@ public class FileTransfer extends CordovaPlugin {
// It also causes OOM if HTTPS is used, even on newer devices.
boolean useChunkedMode = chunkedMode && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps);
useChunkedMode = useChunkedMode || (fixedLength == -1);
if (useChunkedMode) {
conn.setChunkedStreamingMode(MAX_BUFFER_SIZE);
// Although setChunkedStreamingMode sets this header, setting it explicitly here works
@@ -342,19 +425,20 @@ public class FileTransfer extends CordovaPlugin {
conn.setFixedLengthStreamingMode(fixedLength);
}
DataOutputStream dos = null;
conn.connect();
OutputStream sendStream = null;
try {
dos = new DataOutputStream( conn.getOutputStream() );
sendStream = conn.getOutputStream();
synchronized (context) {
if (context.aborted) {
return;
}
context.currentOutputStream = dos;
context.currentOutputStream = sendStream;
}
//We don't want to change encoding, we just want this to write for all Unicode.
dos.write(extraBytes);
dos.write(fileNameBytes);
dos.writeBytes(midParams);
sendStream.write(beforeDataBytes);
totalBytes += beforeDataBytes.length;
// create a buffer of maximum size
int bytesAvailable = sourceInputStream.available();
@@ -363,13 +447,12 @@ public class FileTransfer extends CordovaPlugin {
// read file and write it into form...
int bytesRead = sourceInputStream.read(buffer, 0, bufferSize);
long totalBytes = 0;
long prevBytesRead = 0;
while (bytesRead > 0) {
totalBytes += bytesRead;
result.setBytesSent(totalBytes);
dos.write(buffer, 0, bufferSize);
sendStream.write(buffer, 0, bytesRead);
totalBytes += bytesRead;
if (totalBytes > prevBytesRead + 102400) {
prevBytesRead = totalBytes;
Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes");
@@ -386,18 +469,22 @@ public class FileTransfer extends CordovaPlugin {
}
// send multipart form data necessary after file data...
dos.writeBytes(tailParams);
dos.flush();
sendStream.write(tailParamsBytes);
totalBytes += tailParamsBytes.length;
sendStream.flush();
} finally {
safeClose(sourceInputStream);
safeClose(dos);
safeClose(sendStream);
}
context.currentOutputStream = null;
Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength);
//------------------ read the SERVER RESPONSE
String responseString;
int responseCode = conn.getResponseCode();
InputStream inStream = null;
Log.d(LOG_TAG, "response code: " + responseCode);
Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields());
TrackingInputStream inStream = null;
try {
inStream = getInputStream(conn);
synchronized (context) {
@@ -407,8 +494,7 @@ public class FileTransfer extends CordovaPlugin {
context.currentInputStream = inStream;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(1024, conn.getContentLength()));
byte[] buffer = new byte[1024];
int bytesRead = 0;
// write bytes to file
@@ -436,6 +522,7 @@ public class FileTransfer extends CordovaPlugin {
} catch (IOException e) {
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn);
Log.e(LOG_TAG, error.toString(), e);
Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes.");
context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
@@ -458,8 +545,6 @@ public class FileTransfer extends CordovaPlugin {
https.setHostnameVerifier(oldHostnameVerifier);
https.setSSLSocketFactory(oldSocketFactory);
}
conn.disconnect();
}
}
}
@@ -475,11 +560,15 @@ public class FileTransfer extends CordovaPlugin {
}
}
private static InputStream getInputStream(HttpURLConnection conn) throws IOException {
private static TrackingInputStream getInputStream(URLConnection conn) throws IOException {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
return new DoneHandlerInputStream(conn.getInputStream());
}
return conn.getInputStream();
String encoding = conn.getContentEncoding();
if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
return new TrackingGZIPInputStream(new ExposedGZIPInputStream(conn.getInputStream()));
}
return new TrackingHTTPInputStream(conn.getInputStream());
}
// always verify the host - don't check for certificate
@@ -526,19 +615,36 @@ public class FileTransfer extends CordovaPlugin {
return oldFactory;
}
private static JSONObject createFileTransferError(int errorCode, String source, String target, HttpURLConnection connection) {
Integer httpStatus = null;
private static JSONObject createFileTransferError(int errorCode, String source, String target, URLConnection connection) {
int httpStatus = 0;
StringBuilder bodyBuilder = new StringBuilder();
String body = null;
if (connection != null) {
try {
httpStatus = connection.getResponseCode();
if (connection instanceof HttpURLConnection) {
httpStatus = ((HttpURLConnection)connection).getResponseCode();
InputStream err = ((HttpURLConnection) connection).getErrorStream();
if(err != null)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(err, "UTF-8"));
String line = reader.readLine();
while(line != null)
{
bodyBuilder.append(line);
line = reader.readLine();
if(line != null)
bodyBuilder.append('\n');
}
body = bodyBuilder.toString();
}
}
} catch (IOException e) {
Log.w(LOG_TAG, "Error getting HTTP status code from connection.", e);
}
}
return createFileTransferError(errorCode, source, target, httpStatus);
return createFileTransferError(errorCode, source, target, body, httpStatus);
}
/**
@@ -546,13 +652,17 @@ public class FileTransfer extends CordovaPlugin {
* @param errorCode the error
* @return JSONObject containing the error
*/
private static JSONObject createFileTransferError(int errorCode, String source, String target, Integer httpStatus) {
private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus) {
JSONObject error = null;
try {
error = new JSONObject();
error.put("code", errorCode);
error.put("source", source);
error.put("target", target);
if(body != null)
{
error.put("body", body);
}
if (httpStatus != null) {
error.put("http_status", httpStatus);
}
@@ -591,21 +701,22 @@ public class FileTransfer extends CordovaPlugin {
final boolean trustEveryone = args.optBoolean(2);
final String objectId = args.getString(3);
final JSONObject headers = args.optJSONObject(4);
final URL url;
try {
url = new URL(source);
} catch (MalformedURLException e) {
JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, 0);
JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0);
Log.e(LOG_TAG, error.toString(), e);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
return;
}
final boolean useHttps = url.getProtocol().toLowerCase().equals("https");
if (!webView.isUrlWhiteListed(source)) {
final boolean useHttps = url.getProtocol().equals("https");
if (!Config.isUrlWhiteListed(source)) {
Log.w(LOG_TAG, "Source URL is not in white list: '" + source + "'");
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, 401);
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, null, 401);
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
return;
}
@@ -621,14 +732,16 @@ public class FileTransfer extends CordovaPlugin {
if (context.aborted) {
return;
}
HttpURLConnection connection = null;
URLConnection connection = null;
HostnameVerifier oldHostnameVerifier = null;
SSLSocketFactory oldSocketFactory = null;
File file = null;
PluginResult result = null;
try {
file = getFileFromPath(target);
context.targetFile = file;
// create needed directories
File file = getFileFromPath(target);
file.getParentFile().mkdirs();
// connect to server
@@ -653,10 +766,12 @@ public class FileTransfer extends CordovaPlugin {
}
// Return a standard HTTP connection
else {
connection = (HttpURLConnection) url.openConnection();
connection = url.openConnection();
}
connection.setRequestMethod("GET");
if (connection instanceof HttpURLConnection) {
((HttpURLConnection)connection).setRequestMethod("GET");
}
//Add cookie support
String cookie = CookieManager.getInstance().getCookie(source);
@@ -664,23 +779,33 @@ public class FileTransfer extends CordovaPlugin {
{
connection.setRequestProperty("cookie", cookie);
}
// This must be explicitly set for gzip progress tracking to work.
connection.setRequestProperty("Accept-Encoding", "gzip");
// Handle the other headers
if (headers != null) {
addHeadersToRequest(connection, headers);
}
connection.connect();
Log.d(LOG_TAG, "Download file:" + url);
FileProgressResult progress = new FileProgressResult();
if (connection.getContentEncoding() == null) {
// Only trust content-length header if no gzip etc
if (connection.getContentEncoding() == null || connection.getContentEncoding().equalsIgnoreCase("gzip")) {
// Only trust content-length header if we understand
// the encoding -- identity or gzip
progress.setLengthComputable(true);
progress.setTotal(connection.getContentLength());
}
FileOutputStream outputStream = new FileOutputStream(file);
InputStream inputStream = null;
FileOutputStream outputStream = null;
TrackingInputStream inputStream = null;
try {
inputStream = getInputStream(connection);
outputStream = new FileOutputStream(file);
synchronized (context) {
if (context.aborted) {
return;
@@ -691,12 +816,10 @@ public class FileTransfer extends CordovaPlugin {
// write bytes to file
byte[] buffer = new byte[MAX_BUFFER_SIZE];
int bytesRead = 0;
long totalBytes = 0;
while ((bytesRead = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, bytesRead);
totalBytes += bytesRead;
// Send a progress event.
progress.setLoaded(totalBytes);
progress.setLoaded(inputStream.getTotalRawBytesRead());
PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject());
progressResult.setKeepCallback(true);
context.sendPluginResult(progressResult);
@@ -710,25 +833,24 @@ public class FileTransfer extends CordovaPlugin {
Log.d(LOG_TAG, "Saved file: " + target);
// create FileEntry object
FileUtils fileUtil = new FileUtils();
JSONObject fileEntry = fileUtil.getEntry(file);
JSONObject fileEntry = FileUtils.getEntry(file);
context.sendPluginResult(new PluginResult(PluginResult.Status.OK, fileEntry));
result = new PluginResult(PluginResult.Status.OK, fileEntry);
} catch (FileNotFoundException e) {
JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, connection);
Log.e(LOG_TAG, error.toString(), e);
context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (IOException e) {
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection);
Log.e(LOG_TAG, error.toString(), e);
context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
} catch (Throwable e) {
JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, connection);
Log.e(LOG_TAG, error.toString(), e);
context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error));
result = new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
} finally {
synchronized (activeRequests) {
activeRequests.remove(objectId);
@@ -741,9 +863,16 @@ public class FileTransfer extends CordovaPlugin {
https.setHostnameVerifier(oldHostnameVerifier);
https.setSSLSocketFactory(oldSocketFactory);
}
connection.disconnect();
}
if (result == null) {
result = new PluginResult(PluginResult.Status.ERROR, createFileTransferError(CONNECTION_ERR, source, target, connection));
}
// Remove incomplete download.
if (result.getStatus() != PluginResult.Status.OK.ordinal() && file != null) {
file.delete();
}
context.sendPluginResult(result);
}
}
});
@@ -806,8 +935,12 @@ public class FileTransfer extends CordovaPlugin {
context = activeRequests.remove(objectId);
}
if (context != null) {
File file = context.targetFile;
if (file != null) {
file.delete();
}
// Trigger the abort callback immediately to minimize latency between it and abort() being called.
JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, -1);
JSONObject error = createFileTransferError(ABORTED_ERR, context.source, context.target, null, -1);
synchronized (context) {
context.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, error));
context.aborted = true;

View File

@@ -15,18 +15,17 @@
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
*/
package org.apache.cordova;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.channels.FileChannel;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import org.apache.commons.codec.binary.Base64;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.file.EncodingException;
@@ -38,23 +37,25 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
//import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.webkit.MimeTypeMap;
//import android.app.Activity;
import java.io.ByteArrayInputStream;
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.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.channels.FileChannel;
/**
* This class provides SD card file and directory services to JavaScript.
* Only files on the SD card can be accessed.
*/
public class FileUtils extends CordovaPlugin {
@SuppressWarnings("unused")
private static final String LOG_TAG = "FileUtils";
private static final String _DATA = "_data"; // The column name where the file path is stored
public static int NOT_FOUND_ERR = 1;
public static int SECURITY_ERR = 2;
@@ -75,9 +76,6 @@ public class FileUtils extends CordovaPlugin {
public static int RESOURCE = 2;
public static int APPLICATION = 3;
FileReader f_in;
FileWriter f_out;
/**
* Constructor.
*/
@@ -88,7 +86,7 @@ public class FileUtils extends CordovaPlugin {
* Executes the request and returns whether the action was valid.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param args JSONArray of arguments for the plugin.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return True if the action was valid, false otherwise.
*/
@@ -111,12 +109,29 @@ public class FileUtils extends CordovaPlugin {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, b));
}
else if (action.equals("readAsText")) {
String s = this.readAsText(args.getString(0), args.getString(1));
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, s));
String encoding = args.getString(1);
int start = args.getInt(2);
int end = args.getInt(3);
this.readFileAs(args.getString(0), start, end, callbackContext, encoding, PluginResult.MESSAGE_TYPE_STRING);
}
else if (action.equals("readAsDataURL")) {
String s = this.readAsDataURL(args.getString(0));
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, s));
int start = args.getInt(1);
int end = args.getInt(2);
this.readFileAs(args.getString(0), start, end, callbackContext, null, -1);
}
else if (action.equals("readAsArrayBuffer")) {
int start = args.getInt(1);
int end = args.getInt(2);
this.readFileAs(args.getString(0), start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_ARRAYBUFFER);
}
else if (action.equals("readAsBinaryString")) {
int start = args.getInt(1);
int end = args.getInt(2);
this.readFileAs(args.getString(0), start, end, callbackContext, null, PluginResult.MESSAGE_TYPE_BINARYSTRING);
}
else if (action.equals("write")) {
long fileSize = this.write(args.getString(0), args.getString(1), args.getInt(2));
@@ -219,10 +234,16 @@ public class FileUtils extends CordovaPlugin {
* @param filePath the path to check
*/
private void notifyDelete(String filePath) {
String newFilePath = stripFileProtocol(filePath);
this.cordova.getActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.Images.Media.DATA + " = ?",
new String[] { newFilePath });
String newFilePath = FileHelper.getRealPath(filePath, cordova);
try {
this.cordova.getActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.Images.Media.DATA + " = ?",
new String[] { newFilePath });
} catch (UnsupportedOperationException t) {
// Was seeing this on the File mobile-spec tests on 4.0.3 x86 emulator.
// The ContentResolver applies only when the file was registered in the
// first case, which is generally only the case with images.
}
}
/**
@@ -317,17 +338,18 @@ public class FileUtils extends CordovaPlugin {
* @throws InvalidModificationException
* @throws EncodingException
* @throws JSONException
* @throws FileExistsException
*/
private JSONObject transferTo(String fileName, String newParent, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException {
fileName = stripFileProtocol(fileName);
newParent = stripFileProtocol(newParent);
private JSONObject transferTo(String fileName, String newParent, String newName, boolean move) throws JSONException, NoModificationAllowedException, IOException, InvalidModificationException, EncodingException, FileExistsException {
String newFileName = FileHelper.getRealPath(fileName, cordova);
newParent = FileHelper.getRealPath(newParent, cordova);
// Check for invalid file name
if (newName != null && newName.contains(":")) {
throw new EncodingException("Bad file name");
}
File source = new File(fileName);
File source = new File(newFileName);
if (!source.exists()) {
// The file/directory we are copying doesn't exist so we should fail.
@@ -359,7 +381,14 @@ public class FileUtils extends CordovaPlugin {
}
} else {
if (move) {
return moveFile(source, destination);
JSONObject newFileEntry = moveFile(source, destination);
// If we've moved a file given its content URI, we need to clean up.
if (fileName.startsWith("content://")) {
notifyDelete(fileName);
}
return newFileEntry;
} else {
return copyFile(source, destination);
}
@@ -406,6 +435,16 @@ public class FileUtils extends CordovaPlugin {
throw new InvalidModificationException("Can't rename a file to a directory");
}
copyAction(srcFile, destFile);
return getEntry(destFile);
}
/**
* Moved this code into it's own method so moveTo could use it when the move is across file systems
*/
private void copyAction(File srcFile, File destFile)
throws FileNotFoundException, IOException {
FileInputStream istream = new FileInputStream(srcFile);
FileOutputStream ostream = new FileOutputStream(destFile);
FileChannel input = istream.getChannel();
@@ -419,8 +458,6 @@ public class FileUtils extends CordovaPlugin {
input.close();
output.close();
}
return getEntry(destFile);
}
/**
@@ -449,7 +486,7 @@ public class FileUtils extends CordovaPlugin {
if (!destinationDir.exists()) {
if (!destinationDir.mkdir()) {
// If we can't create the directory then fail
throw new NoModificationAllowedException("Couldn't create the destination direcotry");
throw new NoModificationAllowedException("Couldn't create the destination directory");
}
}
@@ -495,7 +532,7 @@ public class FileUtils extends CordovaPlugin {
* @throws InvalidModificationException
* @throws JSONException
*/
private JSONObject moveFile(File srcFile, File destFile) throws JSONException, InvalidModificationException {
private JSONObject moveFile(File srcFile, File destFile) throws IOException, JSONException, InvalidModificationException {
// Renaming a file to an existing directory should fail
if (destFile.exists() && destFile.isDirectory()) {
throw new InvalidModificationException("Can't rename a file to a directory");
@@ -507,6 +544,12 @@ public class FileUtils extends CordovaPlugin {
// Now we have to do things the hard way
// 1) Copy all the old file
// 2) delete the src file
copyAction(srcFile, destFile);
if (destFile.exists()) {
srcFile.delete();
} else {
throw new IOException("moved failed");
}
}
return getEntry(destFile);
@@ -521,8 +564,10 @@ public class FileUtils extends CordovaPlugin {
* @throws JSONException
* @throws IOException
* @throws InvalidModificationException
* @throws NoModificationAllowedException
* @throws FileExistsException
*/
private JSONObject moveDirectory(File srcDir, File destinationDir) throws JSONException, InvalidModificationException {
private JSONObject moveDirectory(File srcDir, File destinationDir) throws IOException, JSONException, InvalidModificationException, NoModificationAllowedException, FileExistsException {
// Renaming a file to an existing directory should fail
if (destinationDir.exists() && destinationDir.isFile()) {
throw new InvalidModificationException("Can't rename a file to a directory");
@@ -546,6 +591,12 @@ public class FileUtils extends CordovaPlugin {
// Now we have to do things the hard way
// 1) Copy all the old files
// 2) delete the src directory
copyDirectory(srcDir, destinationDir);
if (destinationDir.exists()) {
removeDirRecursively(srcDir);
} else {
throw new IOException("moved failed");
}
}
return getEntry(destinationDir);
@@ -694,7 +745,7 @@ public class FileUtils extends CordovaPlugin {
if (fileName.startsWith("/")) {
fp = new File(fileName);
} else {
dirPath = stripFileProtocol(dirPath);
dirPath = FileHelper.getRealPath(dirPath, cordova);
fp = new File(dirPath + File.separator + fileName);
}
return fp;
@@ -709,7 +760,7 @@ public class FileUtils extends CordovaPlugin {
* @throws JSONException
*/
private JSONObject getParent(String filePath) throws JSONException {
filePath = stripFileProtocol(filePath);
filePath = FileHelper.getRealPath(filePath, cordova);
if (atRootDirectory(filePath)) {
return getEntry(filePath);
@@ -725,7 +776,7 @@ public class FileUtils extends CordovaPlugin {
* @return true if we are at the root, false otherwise.
*/
private boolean atRootDirectory(String filePath) {
filePath = stripFileProtocol(filePath);
filePath = FileHelper.getRealPath(filePath, cordova);
if (filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + cordova.getActivity().getPackageName() + "/cache") ||
filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath()) ||
@@ -735,19 +786,6 @@ public class FileUtils extends CordovaPlugin {
return false;
}
/**
* This method removes the "file://" from the passed in filePath
*
* @param filePath to be checked.
* @return
*/
public static String stripFileProtocol(String filePath) {
if (filePath.startsWith("file://")) {
filePath = filePath.substring(7);
}
return filePath;
}
/**
* Create a File object from the passed in path
*
@@ -755,7 +793,7 @@ public class FileUtils extends CordovaPlugin {
* @return
*/
private File createFileObject(String filePath) {
filePath = stripFileProtocol(filePath);
filePath = FileHelper.getRealPath(filePath, cordova);
File file = new File(filePath);
return file;
@@ -795,9 +833,9 @@ public class FileUtils extends CordovaPlugin {
JSONObject metadata = new JSONObject();
metadata.put("size", file.length());
metadata.put("type", getMimeType(filePath));
metadata.put("type", FileHelper.getMimeType(filePath, cordova));
metadata.put("name", file.getName());
metadata.put("fullPath", file.getAbsolutePath());
metadata.put("fullPath", filePath);
metadata.put("lastModifiedDate", file.lastModified());
return metadata;
@@ -846,21 +884,21 @@ public class FileUtils extends CordovaPlugin {
}
/**
* Returns a JSON Object representing a directory on the device's file system
* Returns a JSON object representing the given File.
*
* @param path to the directory
* @return
* @param file the File to convert
* @return a JSON representation of the given File
* @throws JSONException
*/
public JSONObject getEntry(File file) throws JSONException {
public static JSONObject getEntry(File file) throws JSONException {
JSONObject entry = new JSONObject();
entry.put("isFile", file.isFile());
entry.put("isDirectory", file.isDirectory());
entry.put("name", file.getName());
entry.put("fullPath", "file://" + file.getAbsolutePath());
// I can't add the next thing it as it would be an infinite loop
//entry.put("filesystem", null);
// The file system can't be specified, as it would lead to an infinite loop.
// entry.put("filesystem", null);
return entry;
}
@@ -876,92 +914,83 @@ public class FileUtils extends CordovaPlugin {
return getEntry(new File(path));
}
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
public boolean isSynch(String action) {
if (action.equals("testSaveLocationExists")) {
return true;
}
else if (action.equals("getFreeDiskSpace")) {
return true;
}
else if (action.equals("testFileExists")) {
return true;
}
else if (action.equals("testDirectoryExists")) {
return true;
}
return false;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Read content of text file.
* Read the contents of a file.
* This is done in a background thread; the result is sent to the callback.
*
* @param filename The name of the file.
* @param encoding The encoding to return contents as. Typical value is UTF-8.
* (see http://www.iana.org/assignments/character-sets)
* @return Contents of file.
* @throws FileNotFoundException, IOException
* @param filename The name of the file.
* @param start Start position in the file.
* @param end End position to stop at (exclusive).
* @param callbackContext The context through which to send the result.
* @param encoding The encoding to return contents as. Typical value is UTF-8. (see http://www.iana.org/assignments/character-sets)
* @param resultType The desired type of data to send to the callback.
* @return Contents of file.
*/
public String readAsText(String filename, String encoding) throws FileNotFoundException, IOException {
byte[] bytes = new byte[1000];
BufferedInputStream bis = new BufferedInputStream(getPathFromUri(filename), 1024);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int numRead = 0;
while ((numRead = bis.read(bytes, 0, 1000)) >= 0) {
bos.write(bytes, 0, numRead);
}
return new String(bos.toByteArray(), encoding);
public void readFileAs(final String filename, final int start, final int end, final CallbackContext callbackContext, final String encoding, final int resultType) {
this.cordova.getThreadPool().execute(new Runnable() {
public void run() {
try {
byte[] bytes = readAsBinaryHelper(filename, start, end);
PluginResult result;
switch (resultType) {
case PluginResult.MESSAGE_TYPE_STRING:
result = new PluginResult(PluginResult.Status.OK, new String(bytes, encoding));
break;
case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
result = new PluginResult(PluginResult.Status.OK, bytes);
break;
case PluginResult.MESSAGE_TYPE_BINARYSTRING:
result = new PluginResult(PluginResult.Status.OK, bytes, true);
break;
default: // Base64.
String contentType = FileHelper.getMimeType(filename, cordova);
byte[] base64 = Base64.encodeBase64(bytes);
String s = "data:" + contentType + ";base64," + new String(base64, "US-ASCII");
result = new PluginResult(PluginResult.Status.OK, s);
}
callbackContext.sendPluginResult(result);
} catch (FileNotFoundException e) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_FOUND_ERR));
} catch (IOException e) {
Log.d(LOG_TAG, e.getLocalizedMessage());
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, NOT_READABLE_ERR));
}
}
});
}
/**
* Read content of text file and return as base64 encoded data url.
* Read the contents of a file as binary.
* This is done synchronously; the result is returned.
*
* @param filename The name of the file.
* @return Contents of file = data:<media type>;base64,<data>
* @throws FileNotFoundException, IOException
* @param filename The name of the file.
* @param start Start position in the file.
* @param end End position to stop at (exclusive).
* @return Contents of the file as a byte[].
* @throws IOException
*/
public String readAsDataURL(String filename) throws FileNotFoundException, IOException {
byte[] bytes = new byte[1000];
BufferedInputStream bis = new BufferedInputStream(getPathFromUri(filename), 1024);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int numRead = 0;
while ((numRead = bis.read(bytes, 0, 1000)) >= 0) {
bos.write(bytes, 0, numRead);
private byte[] readAsBinaryHelper(String filename, int start, int end) throws IOException {
int numBytesToRead = end - start;
byte[] bytes = new byte[numBytesToRead];
InputStream inputStream = FileHelper.getInputStreamFromUriString(filename, cordova);
int numBytesRead = 0;
if (start > 0) {
inputStream.skip(start);
}
// Determine content type from file name
String contentType = null;
if (filename.startsWith("content:")) {
Uri fileUri = Uri.parse(filename);
contentType = this.cordova.getActivity().getContentResolver().getType(fileUri);
}
else {
contentType = getMimeType(filename);
while (numBytesToRead > 0 && (numBytesRead = inputStream.read(bytes, numBytesRead, numBytesToRead)) >= 0) {
numBytesToRead -= numBytesRead;
}
byte[] base64 = Base64.encodeBase64(bos.toByteArray());
String data = "data:" + contentType + ";base64," + new String(base64);
return data;
}
/**
* Looks up the mime type of a given file name.
*
* @param filename
* @return a mime type
*/
public static String getMimeType(String filename) {
MimeTypeMap map = MimeTypeMap.getSingleton();
return map.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(filename));
return bytes;
}
/**
@@ -971,10 +1000,15 @@ public class FileUtils extends CordovaPlugin {
* @param data The contents of the file.
* @param offset The position to begin writing the file.
* @throws FileNotFoundException, IOException
* @throws NoModificationAllowedException
*/
/**/
public long write(String filename, String data, int offset) throws FileNotFoundException, IOException {
filename = stripFileProtocol(filename);
public long write(String filename, String data, int offset) throws FileNotFoundException, IOException, NoModificationAllowedException {
if (filename.startsWith("content://")) {
throw new NoModificationAllowedException("Couldn't write to file given its content URI");
}
filename = FileHelper.getRealPath(filename, cordova);
boolean append = false;
if (offset > 0) {
@@ -1000,9 +1034,14 @@ public class FileUtils extends CordovaPlugin {
* @param filename
* @param size
* @throws FileNotFoundException, IOException
* @throws NoModificationAllowedException
*/
private long truncateFile(String filename, long size) throws FileNotFoundException, IOException {
filename = stripFileProtocol(filename);
private long truncateFile(String filename, long size) throws FileNotFoundException, IOException, NoModificationAllowedException {
if (filename.startsWith("content://")) {
throw new NoModificationAllowedException("Couldn't truncate file given its content URI");
}
filename = FileHelper.getRealPath(filename, cordova);
RandomAccessFile raf = new RandomAccessFile(filename, "rw");
try {
@@ -1011,50 +1050,10 @@ public class FileUtils extends CordovaPlugin {
channel.truncate(size);
return size;
}
return raf.length();
} finally {
raf.close();
}
}
/**
* Get an input stream based on file path or content:// uri
*
* @param path
* @return an input stream
* @throws FileNotFoundException
*/
private InputStream getPathFromUri(String path) throws FileNotFoundException {
if (path.startsWith("content")) {
Uri uri = Uri.parse(path);
return cordova.getActivity().getContentResolver().openInputStream(uri);
}
else {
path = stripFileProtocol(path);
return new FileInputStream(path);
}
}
/**
* Queries the media store to find out what the file path is for the Uri we supply
*
* @param contentUri the Uri of the audio/image/video
* @param cordova the current application context
* @return the full path to the file
*/
@SuppressWarnings("deprecation")
protected static String getRealPathFromURI(Uri contentUri, CordovaInterface cordova) {
String uri = contentUri.toString();
if (uri.startsWith("content:")) {
String[] proj = { _DATA };
Cursor cursor = cordova.getActivity().managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(_DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else {
return uri;
}
}
}

20
framework/src/org/apache/cordova/GeoBroker.java Executable file → Normal file
View File

@@ -38,7 +38,7 @@ import android.location.LocationManager;
public class GeoBroker extends CordovaPlugin {
private GPSListener gpsListener;
private NetworkListener networkListener;
private LocationManager locationManager;
private LocationManager locationManager;
/**
* Constructor.
@@ -73,7 +73,7 @@ public class GeoBroker extends CordovaPlugin {
PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(last));
callbackContext.sendPluginResult(result);
} else {
this.getCurrentLocation(callbackContext, enableHighAccuracy);
this.getCurrentLocation(callbackContext, enableHighAccuracy, args.optInt(2, 60000));
}
}
else if (action.equals("addWatch")) {
@@ -102,11 +102,11 @@ public class GeoBroker extends CordovaPlugin {
this.networkListener.clearWatch(id);
}
private void getCurrentLocation(CallbackContext callbackContext, boolean enableHighAccuracy) {
private void getCurrentLocation(CallbackContext callbackContext, boolean enableHighAccuracy, int timeout) {
if (enableHighAccuracy) {
this.gpsListener.addCallback(callbackContext);
this.gpsListener.addCallback(callbackContext, timeout);
} else {
this.networkListener.addCallback(callbackContext);
this.networkListener.addCallback(callbackContext, timeout);
}
}
@@ -150,7 +150,7 @@ public class GeoBroker extends CordovaPlugin {
o.put("altitude", (loc.hasAltitude() ? loc.getAltitude() : null));
o.put("accuracy", loc.getAccuracy());
o.put("heading", (loc.hasBearing() ? (loc.hasSpeed() ? loc.getBearing() : null) : null));
o.put("speed", loc.getSpeed());
o.put("velocity", loc.getSpeed());
o.put("timestamp", loc.getTime());
} catch (JSONException e) {
// TODO Auto-generated catch block
@@ -160,8 +160,9 @@ public class GeoBroker extends CordovaPlugin {
return o;
}
public void win(Location loc, CallbackContext callbackContext) {
PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(loc));
public void win(Location loc, CallbackContext callbackContext, boolean keepCallback) {
PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(loc));
result.setKeepCallback(keepCallback);
callbackContext.sendPluginResult(result);
}
@@ -172,7 +173,7 @@ public class GeoBroker extends CordovaPlugin {
* @param msg The error message
* @throws JSONException
*/
public void fail(int code, String msg, CallbackContext callbackContext) {
public void fail(int code, String msg, CallbackContext callbackContext, boolean keepCallback) {
JSONObject obj = new JSONObject();
String backup = null;
try {
@@ -189,6 +190,7 @@ public class GeoBroker extends CordovaPlugin {
result = new PluginResult(PluginResult.Status.ERROR, backup);
}
result.setKeepCallback(keepCallback);
callbackContext.sendPluginResult(result);
}

View File

@@ -40,6 +40,7 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.text.format.Time;
/**
@@ -101,7 +102,11 @@ public class Globalization extends CordovaPlugin {
}else if(action.equalsIgnoreCase(GETDATEPATTERN)){
obj = getDatePattern(data);
}else if(action.equalsIgnoreCase(GETDATENAMES)){
obj = getDateNames(data);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.GINGERBREAD) {
throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR);
} else {
obj = getDateNames(data);
}
}else if(action.equalsIgnoreCase(ISDAYLIGHTSAVINGSTIME)){
obj = getIsDayLightSavingsTime(data);
}else if(action.equalsIgnoreCase(GETFIRSTDAYOFWEEK)){
@@ -305,6 +310,7 @@ public class Globalization extends CordovaPlugin {
*
* @throws: GlobalizationError.UNKNOWN_ERROR
*/
@TargetApi(9)
private JSONObject getDateNames(JSONArray options) throws GlobalizationError{
JSONObject obj = new JSONObject();
//String[] value;

View File

@@ -24,11 +24,12 @@ import java.io.InputStream;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.LOG;
import android.content.res.AssetManager;
import android.net.Uri;
import android.annotation.TargetApi;
import android.os.Build;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class IceCreamCordovaWebViewClient extends CordovaWebViewClient {
@@ -42,35 +43,20 @@ public class IceCreamCordovaWebViewClient extends CordovaWebViewClient {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if(url.contains("?") || url.contains("#")){
return generateWebResourceResponse(url);
} else {
return super.shouldInterceptRequest(view, url);
//Check if plugins intercept the request
WebResourceResponse ret = super.shouldInterceptRequest(view, url);
if(ret == null && (url.contains("?") || url.contains("#") || needsIceCreamSpaceInAssetUrlFix(url))){
ret = generateWebResourceResponse(url);
}
return ret;
}
private WebResourceResponse generateWebResourceResponse(String url) {
final String ANDROID_ASSET = "file:///android_asset/";
if (url.startsWith(ANDROID_ASSET)) {
String niceUrl = url;
niceUrl = url.replaceFirst(ANDROID_ASSET, "");
if(niceUrl.contains("?")){
niceUrl = niceUrl.split("\\?")[0];
}
else if(niceUrl.contains("#"))
{
niceUrl = niceUrl.split("#")[0];
}
String mimetype = null;
if(niceUrl.endsWith(".html")){
mimetype = "text/html";
}
if (url.startsWith("file:///android_asset/")) {
String mimetype = FileHelper.getMimeType(url, cordova);
try {
AssetManager assets = cordova.getActivity().getAssets();
Uri uri = Uri.parse(niceUrl);
InputStream stream = assets.open(uri.getPath(), AssetManager.ACCESS_STREAMING);
InputStream stream = FileHelper.getInputStreamFromUriString(url, cordova);
WebResourceResponse response = new WebResourceResponse(mimetype, "UTF-8", stream);
return response;
} catch (IOException e) {
@@ -80,4 +66,18 @@ public class IceCreamCordovaWebViewClient extends CordovaWebViewClient {
return null;
}
private static boolean needsIceCreamSpaceInAssetUrlFix(String url) {
if (!url.contains("%20")){
return false;
}
switch(android.os.Build.VERSION.SDK_INT){
case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH:
case android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1:
return true;
default:
return false;
}
}
}

View File

@@ -0,0 +1,813 @@
/*
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;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.JsPromptResult;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
@SuppressLint("SetJavaScriptEnabled")
public class InAppBrowser extends CordovaPlugin {
private static final String NULL = "null";
protected static final String LOG_TAG = "InAppBrowser";
private static final String SELF = "_self";
private static final String SYSTEM = "_system";
// private static final String BLANK = "_blank";
private static final String LOCATION = "location";
private static final String EXIT_EVENT = "exit";
private static final String LOAD_START_EVENT = "loadstart";
private static final String LOAD_STOP_EVENT = "loadstop";
private static final String LOAD_ERROR_EVENT = "loaderror";
private static final String CLOSE_BUTTON_CAPTION = "closebuttoncaption";
private long MAX_QUOTA = 100 * 1024 * 1024;
private Dialog dialog;
private WebView inAppWebView;
private EditText edittext;
private boolean showLocationBar = true;
private CallbackContext callbackContext;
private String buttonLabel = "Done";
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArry of arguments for the plugin.
* @param callbackId The callback id 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 {
try {
if (action.equals("open")) {
this.callbackContext = callbackContext;
String url = args.getString(0);
String target = args.optString(1);
if (target == null || target.equals("") || target.equals(NULL)) {
target = SELF;
}
HashMap<String, Boolean> features = parseFeature(args.optString(2));
Log.d(LOG_TAG, "target = " + target);
url = updateUrl(url);
String result = "";
// SELF
if (SELF.equals(target)) {
Log.d(LOG_TAG, "in self");
// load in webview
if (url.startsWith("file://") || url.startsWith("javascript:")
|| Config.isUrlWhiteListed(url)) {
this.webView.loadUrl(url);
}
//Load the dialer
else if (url.startsWith(WebView.SCHEME_TEL))
{
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
this.cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
// load in InAppBrowser
else {
result = this.showWebPage(url, features);
}
}
// SYSTEM
else if (SYSTEM.equals(target)) {
Log.d(LOG_TAG, "in system");
result = this.openExternal(url);
}
// BLANK - or anything else
else {
Log.d(LOG_TAG, "in blank");
result = this.showWebPage(url, features);
}
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
pluginResult.setKeepCallback(true);
this.callbackContext.sendPluginResult(pluginResult);
}
else if (action.equals("close")) {
closeDialog();
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
}
else if (action.equals("injectScriptCode")) {
String jsWrapper = null;
if (args.getBoolean(1)) {
jsWrapper = String.format("prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')", callbackContext.getCallbackId());
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectScriptFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleCode")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else if (action.equals("injectStyleFile")) {
String jsWrapper;
if (args.getBoolean(1)) {
jsWrapper = String.format("(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)", callbackContext.getCallbackId());
} else {
jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
}
injectDeferredObject(args.getString(0), jsWrapper);
}
else {
return false;
}
} catch (JSONException e) {
this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
}
return true;
}
/**
* Inject an object (script or style) into the InAppBrowser WebView.
*
* This is a helper method for the inject{Script|Style}{Code|File} API calls, which
* provides a consistent method for injecting JavaScript code into the document.
*
* If a wrapper string is supplied, then the source string will be JSON-encoded (adding
* quotes) and wrapped using string formatting. (The wrapper string should have a single
* '%s' marker)
*
* @param source The source object (filename or script/style text) to inject into
* the document.
* @param jsWrapper A JavaScript string to wrap the source string in, so that the object
* is properly injected, or null if the source string is JavaScript text
* which should be executed directly.
*/
private void injectDeferredObject(String source, String jsWrapper) {
String scriptToInject;
if (jsWrapper != null) {
org.json.JSONArray jsonEsc = new org.json.JSONArray();
jsonEsc.put(source);
String jsonRepr = jsonEsc.toString();
String jsonSourceString = jsonRepr.substring(1, jsonRepr.length()-1);
scriptToInject = String.format(jsWrapper, jsonSourceString);
} else {
scriptToInject = source;
}
// This action will have the side-effect of blurring the currently focused element
this.inAppWebView.loadUrl("javascript:" + scriptToInject);
}
/**
* Put the list of features into a hash map
*
* @param optString
* @return
*/
private HashMap<String, Boolean> parseFeature(String optString) {
if (optString.equals(NULL)) {
return null;
} else {
HashMap<String, Boolean> map = new HashMap<String, Boolean>();
StringTokenizer features = new StringTokenizer(optString, ",");
StringTokenizer option;
while(features.hasMoreElements()) {
option = new StringTokenizer(features.nextToken(), "=");
if (option.hasMoreElements()) {
String key = option.nextToken();
if (key.equalsIgnoreCase(CLOSE_BUTTON_CAPTION)) {
this.buttonLabel = option.nextToken();
} else {
Boolean value = option.nextToken().equals("no") ? Boolean.FALSE : Boolean.TRUE;
map.put(key, value);
}
}
}
return map;
}
}
/**
* Convert relative URL to full path
*
* @param url
* @return
*/
private String updateUrl(String url) {
Uri newUrl = Uri.parse(url);
if (newUrl.isRelative()) {
url = this.webView.getUrl().substring(0, this.webView.getUrl().lastIndexOf("/")+1) + url;
}
return url;
}
/**
* Display a new browser with the specified URL.
*
* @param url The url to load.
* @param usePhoneGap Load url in PhoneGap webview
* @return "" if ok, or error message.
*/
public String openExternal(String url) {
try {
Intent intent = null;
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.cordova.getActivity().startActivity(intent);
return "";
} catch (android.content.ActivityNotFoundException e) {
Log.d(LOG_TAG, "InAppBrowser: Error loading url "+url+":"+ e.toString());
return e.toString();
}
}
/**
* Closes the dialog
*/
private void closeDialog() {
try {
this.inAppWebView.loadUrl("about:blank");
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
if (dialog != null) {
dialog.dismiss();
}
}
/**
* Checks to see if it is possible to go back one page in history, then does so.
*/
private void goBack() {
if (this.inAppWebView.canGoBack()) {
this.inAppWebView.goBack();
}
}
/**
* Checks to see if it is possible to go forward one page in history, then does so.
*/
private void goForward() {
if (this.inAppWebView.canGoForward()) {
this.inAppWebView.goForward();
}
}
/**
* Navigate to the new page
*
* @param url to load
*/
private void navigate(String url) {
InputMethodManager imm = (InputMethodManager)this.cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
if (!url.startsWith("http") && !url.startsWith("file:")) {
this.inAppWebView.loadUrl("http://" + url);
} else {
this.inAppWebView.loadUrl(url);
}
this.inAppWebView.requestFocus();
}
/**
* Should we show the location bar?
*
* @return boolean
*/
private boolean getShowLocationBar() {
return this.showLocationBar;
}
/**
* Display a new browser with the specified URL.
*
* @param url The url to load.
* @param jsonObject
*/
public String showWebPage(final String url, HashMap<String, Boolean> features) {
// Determine if we should hide the location bar.
showLocationBar = true;
if (features != null) {
Boolean show = features.get(LOCATION);
if (show != null) {
showLocationBar = show.booleanValue();
}
}
final CordovaWebView thatWebView = this.webView;
// Create dialog in new thread
Runnable runnable = new Runnable() {
/**
* Convert our DIP units to Pixels
*
* @return int
*/
private int dpToPixels(int dipValue) {
int value = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
(float) dipValue,
cordova.getActivity().getResources().getDisplayMetrics()
);
return value;
}
public void run() {
// Let's create the main dialog
dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
try {
JSONObject obj = new JSONObject();
obj.put("type", EXIT_EVENT);
sendUpdate(obj, false);
} catch (JSONException e) {
Log.d(LOG_TAG, "Should never happen");
}
}
});
// Main container layout
LinearLayout main = new LinearLayout(cordova.getActivity());
main.setOrientation(LinearLayout.VERTICAL);
// Toolbar layout
RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
toolbar.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, this.dpToPixels(44)));
toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
toolbar.setHorizontalGravity(Gravity.LEFT);
toolbar.setVerticalGravity(Gravity.TOP);
// Action Button Container layout
RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
actionButtonContainer.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
actionButtonContainer.setId(1);
// Back button
Button back = new Button(cordova.getActivity());
RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
back.setLayoutParams(backLayoutParams);
back.setContentDescription("Back Button");
back.setId(2);
back.setText("<");
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goBack();
}
});
// Forward button
Button forward = new Button(cordova.getActivity());
RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
forward.setLayoutParams(forwardLayoutParams);
forward.setContentDescription("Forward Button");
forward.setId(3);
forward.setText(">");
forward.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goForward();
}
});
// Edit Text Box
edittext = new EditText(cordova.getActivity());
RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
edittext.setLayoutParams(textLayoutParams);
edittext.setId(4);
edittext.setSingleLine(true);
edittext.setText(url);
edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
navigate(edittext.getText().toString());
return true;
}
return false;
}
});
// Close button
Button close = new Button(cordova.getActivity());
RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
close.setLayoutParams(closeLayoutParams);
forward.setContentDescription("Close Button");
close.setId(5);
close.setText(buttonLabel);
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
closeDialog();
}
});
// WebView
inAppWebView = new WebView(cordova.getActivity());
inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
inAppWebView.setWebChromeClient(new InAppChromeClient(thatWebView));
WebViewClient client = new InAppBrowserClient(thatWebView, edittext);
inAppWebView.setWebViewClient(client);
WebSettings settings = inAppWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(true);
/**
* We need to be careful of this line as a future Android release may deprecate it out of existence.
* Can't replace it with the API 8 level call right now as our minimum SDK is 7 until May 2013
*/
// @TODO: replace with settings.setPluginState(android.webkit.WebSettings.PluginState.ON)
settings.setPluginsEnabled(true);
//Toggle whether this is enabled or not!
Bundle appSettings = cordova.getActivity().getIntent().getExtras();
boolean enableDatabase = appSettings == null ? true : appSettings.getBoolean("InAppBrowserStorageEnabled", true);
if(enableDatabase)
{
String databasePath = cordova.getActivity().getApplicationContext().getDir("inAppBrowserDB", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
settings.setDatabaseEnabled(true);
}
settings.setDomStorageEnabled(true);
inAppWebView.loadUrl(url);
inAppWebView.setId(6);
inAppWebView.getSettings().setLoadWithOverviewMode(true);
inAppWebView.getSettings().setUseWideViewPort(true);
inAppWebView.requestFocus();
inAppWebView.requestFocusFromTouch();
// Add the back and forward buttons to our action button container layout
actionButtonContainer.addView(back);
actionButtonContainer.addView(forward);
// Add the views to our toolbar
toolbar.addView(actionButtonContainer);
toolbar.addView(edittext);
toolbar.addView(close);
// Don't add the toolbar if its been disabled
if (getShowLocationBar()) {
// Add our toolbar to our main view/layout
main.addView(toolbar);
}
// Add our webview to our main view/layout
main.addView(inAppWebView);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
dialog.setContentView(main);
dialog.show();
dialog.getWindow().setAttributes(lp);
}
};
this.cordova.getActivity().runOnUiThread(runnable);
return "";
}
/**
* Create a new plugin success result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
*/
private void sendUpdate(JSONObject obj, boolean keepCallback) {
sendUpdate(obj, keepCallback, PluginResult.Status.OK);
}
/**
* Create a new plugin result and send it back to JavaScript
*
* @param obj a JSONObject contain event payload information
* @param status the status code to return to the JavaScript environment
*/ private void sendUpdate(JSONObject obj, boolean keepCallback, PluginResult.Status status) {
PluginResult result = new PluginResult(status, obj);
result.setKeepCallback(keepCallback);
this.callbackContext.sendPluginResult(result);
}
public class InAppChromeClient extends WebChromeClient {
private CordovaWebView webView;
public InAppChromeClient(CordovaWebView webView) {
super();
this.webView = webView;
}
/**
* Handle database quota exceeded notification.
*
* @param url
* @param databaseIdentifier
* @param currentQuota
* @param estimatedSize
* @param totalUsedQuota
* @param quotaUpdater
*/
@Override
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize,
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater)
{
LOG.d(LOG_TAG, "onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
if (estimatedSize < MAX_QUOTA)
{
//increase for 1Mb
long newQuota = estimatedSize;
LOG.d(LOG_TAG, "calling quotaUpdater.updateQuota newQuota: %d", newQuota);
quotaUpdater.updateQuota(newQuota);
}
else
{
// Set the quota to whatever it is and force an error
// TODO: get docs on how to handle this properly
quotaUpdater.updateQuota(currentQuota);
}
}
/**
* Instructs the client to show a prompt to ask the user to set the Geolocation permission state for the specified origin.
*
* @param origin
* @param callback
*/
@Override
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
/**
* Tell the client to display a prompt dialog to the user.
* If the client returns true, WebView will assume that the client will
* handle the prompt dialog and call the appropriate JsPromptResult method.
*
* The prompt bridge provided for the InAppBrowser is capable of executing any
* oustanding callback belonging to the InAppBrowser plugin. Care has been
* taken that other callbacks cannot be triggered, and that no other code
* execution is possible.
*
* To trigger the bridge, the prompt default value should be of the form:
*
* gap-iab://<callbackId>
*
* where <callbackId> is the string id of the callback to trigger (something
* like "InAppBrowser0123456789")
*
* If present, the prompt message is expected to be a JSON-encoded value to
* pass to the callback. A JSON_EXCEPTION is returned if the JSON is invalid.
*
* @param view
* @param url
* @param message
* @param defaultValue
* @param result
*/
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
// See if the prompt string uses the 'gap-iab' protocol. If so, the remainder should be the id of a callback to execute.
if (defaultValue != null && defaultValue.startsWith("gap-iab://")) {
PluginResult scriptResult;
String scriptCallbackId = defaultValue.substring(10);
if (scriptCallbackId.startsWith("InAppBrowser")) {
if(message == null || message.length() == 0) {
scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray());
} else {
try {
scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray(message));
} catch(JSONException e) {
scriptResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
}
}
this.webView.sendPluginResult(scriptResult, scriptCallbackId);
result.confirm("");
return true;
}
}
return false;
}
}
/**
* The webview client receives notifications about appView
*/
public class InAppBrowserClient extends WebViewClient {
EditText edittext;
CordovaWebView webView;
/**
* Constructor.
*
* @param mContext
* @param edittext
*/
public InAppBrowserClient(CordovaWebView webView, EditText mEditText) {
this.webView = webView;
this.edittext = mEditText;
}
/**
* Notify the host application that a page has started loading.
*
* @param view The webview initiating the callback.
* @param url The url of the page.
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String newloc = "";
if (url.startsWith("http:") || url.startsWith("https:") || url.startsWith("file:")) {
newloc = url;
}
// If dialing phone (tel:5551212)
else if (url.startsWith(WebView.SCHEME_TEL)) {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
}
}
else if (url.startsWith("geo:") || url.startsWith(WebView.SCHEME_MAILTO) || url.startsWith("market:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error with " + url + ": " + e.toString());
}
}
// If sms:5551212?body=This is the message
else if (url.startsWith("sms:")) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get address
String address = null;
int parmIndex = url.indexOf('?');
if (parmIndex == -1) {
address = url.substring(4);
}
else {
address = url.substring(4, parmIndex);
// If body, then set sms body
Uri uri = Uri.parse(url);
String query = uri.getQuery();
if (query != null) {
if (query.startsWith("body=")) {
intent.putExtra("sms_body", query.substring(5));
}
}
}
intent.setData(Uri.parse("sms:" + address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(LOG_TAG, "Error sending sms " + url + ":" + e.toString());
}
}
else {
newloc = "http://" + url;
}
if (!newloc.equals(edittext.getText().toString())) {
edittext.setText(newloc);
}
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_START_EVENT);
obj.put("url", newloc);
sendUpdate(obj, true);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_STOP_EVENT);
obj.put("url", url);
sendUpdate(obj, true);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
try {
JSONObject obj = new JSONObject();
obj.put("type", LOAD_ERROR_EVENT);
obj.put("url", failingUrl);
obj.put("code", errorCode);
obj.put("message", description);
sendUpdate(obj, true, PluginResult.Status.ERROR);
} catch (JSONException ex) {
Log.d(LOG_TAG, "Should never happen");
}
}
}
}

View File

@@ -0,0 +1,24 @@
package org.apache.cordova;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
public class JSONUtils {
public static List<String> toStringList(JSONArray array) throws JSONException {
if(array == null) {
return null;
}
else {
List<String> list = new ArrayList<String>();
for (int i = 0; i < array.length(); i++) {
list.add(array.get(i).toString());
}
return list;
}
}
}

View File

@@ -50,8 +50,10 @@ public class NativeToJsMessageQueue {
// exec() is asynchronous. Set this to true when running bridge benchmarks.
static final boolean DISABLE_EXEC_CHAINING = false;
// Arbitrarily chosen upper limit for how much data to send to JS in one shot.
private static final int MAX_PAYLOAD_SIZE = 50 * 1024;
// Arbitrarily chosen upper limit for how much data to send to JS in one shot.
// This currently only chops up on message boundaries. It may be useful
// to allow it to break up messages.
private static int MAX_PAYLOAD_SIZE = 50 * 1024 * 10240;
/**
* The index into registeredListeners to treat as active.
@@ -125,7 +127,8 @@ public class NativeToJsMessageQueue {
}
private void packMessage(JsMessage message, StringBuilder sb) {
sb.append(message.calculateEncodedLength())
int len = message.calculateEncodedLength();
sb.append(len)
.append(' ');
message.encodeAsMessage(sb);
}
@@ -144,7 +147,7 @@ public class NativeToJsMessageQueue {
int numMessagesToSend = 0;
for (JsMessage message : queue) {
int messageSize = calculatePackedMessageLength(message);
if (numMessagesToSend > 0 && totalPayloadLen + messageSize > MAX_PAYLOAD_SIZE) {
if (numMessagesToSend > 0 && totalPayloadLen + messageSize > MAX_PAYLOAD_SIZE && MAX_PAYLOAD_SIZE > 0) {
break;
}
totalPayloadLen += messageSize;
@@ -161,7 +164,8 @@ public class NativeToJsMessageQueue {
// Attach a char to indicate that there are more messages pending.
sb.append('*');
}
return sb.toString();
String ret = sb.toString();
return ret;
}
}
@@ -178,7 +182,7 @@ public class NativeToJsMessageQueue {
int numMessagesToSend = 0;
for (JsMessage message : queue) {
int messageSize = message.calculateEncodedLength() + 50; // overestimate.
if (numMessagesToSend > 0 && totalPayloadLen + messageSize > MAX_PAYLOAD_SIZE) {
if (numMessagesToSend > 0 && totalPayloadLen + messageSize > MAX_PAYLOAD_SIZE && MAX_PAYLOAD_SIZE > 0) {
break;
}
totalPayloadLen += messageSize;
@@ -204,7 +208,8 @@ public class NativeToJsMessageQueue {
for (int i = willSendAllMessages ? 1 : 0; i < numMessagesToSend; ++i) {
sb.append('}');
}
return sb.toString();
String ret = sb.toString();
return ret;
}
}
@@ -391,7 +396,8 @@ public class NativeToJsMessageQueue {
int statusLen = String.valueOf(pluginResult.getStatus()).length();
int ret = 2 + statusLen + 1 + jsPayloadOrCallbackId.length() + 1;
switch (pluginResult.getMessageType()) {
case PluginResult.MESSAGE_TYPE_BOOLEAN:
case PluginResult.MESSAGE_TYPE_BOOLEAN: // f or t
case PluginResult.MESSAGE_TYPE_NULL: // N
ret += 1;
break;
case PluginResult.MESSAGE_TYPE_NUMBER: // n
@@ -400,6 +406,12 @@ public class NativeToJsMessageQueue {
case PluginResult.MESSAGE_TYPE_STRING: // s
ret += 1 + pluginResult.getStrMessage().length();
break;
case PluginResult.MESSAGE_TYPE_BINARYSTRING:
ret += 1 + pluginResult.getMessage().length();
break;
case PluginResult.MESSAGE_TYPE_ARRAYBUFFER:
ret += 1 + pluginResult.getMessage().length();
break;
case PluginResult.MESSAGE_TYPE_JSON:
default:
ret += pluginResult.getMessage().length();
@@ -428,13 +440,24 @@ public class NativeToJsMessageQueue {
case PluginResult.MESSAGE_TYPE_BOOLEAN:
sb.append(pluginResult.getMessage().charAt(0)); // t or f.
break;
case PluginResult.MESSAGE_TYPE_NULL: // N
sb.append('N');
break;
case PluginResult.MESSAGE_TYPE_NUMBER: // n
sb.append('n')
.append(pluginResult.getMessage());
break;
case PluginResult.MESSAGE_TYPE_STRING: // s
sb.append('s')
.append(pluginResult.getStrMessage());
sb.append('s');
sb.append(pluginResult.getStrMessage());
break;
case PluginResult.MESSAGE_TYPE_BINARYSTRING: // S
sb.append('S');
sb.append(pluginResult.getMessage());
break;
case PluginResult.MESSAGE_TYPE_ARRAYBUFFER: // A
sb.append('A');
sb.append(pluginResult.getMessage());
break;
case PluginResult.MESSAGE_TYPE_JSON:
default:
@@ -454,9 +477,9 @@ public class NativeToJsMessageQueue {
.append(success)
.append(",")
.append(status)
.append(",")
.append(",[")
.append(pluginResult.getMessage())
.append(",")
.append("],")
.append(pluginResult.getKeepCallback())
.append(");");
}

View File

@@ -74,6 +74,7 @@ public class NetworkManager extends CordovaPlugin {
ConnectivityManager sockMan;
BroadcastReceiver receiver;
private String lastStatus = "";
/**
* Constructor.
@@ -99,12 +100,11 @@ public class NetworkManager extends CordovaPlugin {
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
if (this.receiver == null) {
this.receiver = new BroadcastReceiver() {
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
// (The null check is for the ARM Emulator, please use Intel Emulator for better results)
if(NetworkManager.this.webView != null)
updateConnectionInfo((NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO));
if(NetworkManager.this.webView != null)
updateConnectionInfo(sockMan.getActiveNetworkInfo());
}
};
cordova.getActivity().registerReceiver(this.receiver, intentFilter);
@@ -147,13 +147,6 @@ public class NetworkManager extends CordovaPlugin {
}
}
/**
* Stop the network receiver on navigation.
*/
public void onReset() {
this.onDestroy();
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
@@ -166,7 +159,14 @@ public class NetworkManager extends CordovaPlugin {
*/
private void updateConnectionInfo(NetworkInfo info) {
// send update to javascript "navigator.network.connection"
sendUpdate(this.getConnectionInfo(info));
// Jellybean sends its own info
String thisStatus = this.getConnectionInfo(info);
if(!thisStatus.equals(lastStatus))
{
sendUpdate(thisStatus);
lastStatus = thisStatus;
}
}
/**
@@ -186,6 +186,7 @@ public class NetworkManager extends CordovaPlugin {
type = getType(info);
}
}
Log.d("CordovaNetworkManager", "Connection Type: " + type);
return type;
}
@@ -200,7 +201,6 @@ public class NetworkManager extends CordovaPlugin {
result.setKeepCallback(true);
connectionCallbackContext.sendPluginResult(result);
}
webView.postMessage("networkconnection", type);
}

View File

@@ -24,6 +24,7 @@ import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
@@ -32,6 +33,7 @@ import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Vibrator;
import android.widget.EditText;
/**
* This class provides access to notifications on the device.
@@ -68,7 +70,11 @@ public class Notification extends CordovaPlugin {
return true;
}
else if (action.equals("confirm")) {
this.confirm(args.getString(0), args.getString(1), args.getString(2), callbackContext);
this.confirm(args.getString(0), args.getString(1), args.getJSONArray(2), callbackContext);
return true;
}
else if (action.equals("prompt")) {
this.prompt(args.getString(0), args.getString(1), args.getJSONArray(2), callbackContext);
return true;
}
else if (action.equals("activityStart")) {
@@ -163,6 +169,14 @@ public class Notification extends CordovaPlugin {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
dlg.create();
dlg.show();
};
@@ -180,10 +194,9 @@ public class Notification extends CordovaPlugin {
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackContext The callback context.
*/
public synchronized void confirm(final String message, final String title, String buttonLabels, final CallbackContext callbackContext) {
public synchronized void confirm(final String message, final String title, final JSONArray buttonLabels, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
final String[] fButtons = buttonLabels.split(",");
Runnable runnable = new Runnable() {
public void run() {
@@ -193,38 +206,51 @@ public class Notification extends CordovaPlugin {
dlg.setCancelable(true);
// First button
if (fButtons.length > 0) {
dlg.setNegativeButton(fButtons[0],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1));
}
});
if (buttonLabels.length() > 0) {
try {
dlg.setNegativeButton(buttonLabels.getString(0),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1));
}
});
} catch (JSONException e) { }
}
// Second button
if (fButtons.length > 1) {
dlg.setNeutralButton(fButtons[1],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2));
}
});
if (buttonLabels.length() > 1) {
try {
dlg.setNeutralButton(buttonLabels.getString(1),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2));
}
});
} catch (JSONException e) { }
}
// Third button
if (fButtons.length > 2) {
dlg.setPositiveButton(fButtons[2],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3));
}
}
);
if (buttonLabels.length() > 2) {
try {
dlg.setPositiveButton(buttonLabels.getString(2),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3));
}
}
);
} catch (JSONException e) { }
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
dlg.create();
dlg.show();
@@ -233,6 +259,104 @@ public class Notification extends CordovaPlugin {
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Builds and shows a native Android prompt dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The following results are returned to the JavaScript callback identified by callbackId:
* buttonIndex Index number of the button selected
* input1 The text entered in the prompt dialog box
*
* @param message The message the dialog should display
* @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackContext The callback context.
*/
public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
final EditText promptInput = new EditText(cordova.getActivity());
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(cordova.getActivity());
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
dlg.setView(promptInput);
final JSONObject result = new JSONObject();
// First button
if (buttonLabels.length() > 0) {
try {
dlg.setNegativeButton(buttonLabels.getString(0),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",1);
result.put("input1", promptInput.getText());
} catch (JSONException e) { e.printStackTrace(); }
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) { }
}
// Second button
if (buttonLabels.length() > 1) {
try {
dlg.setNeutralButton(buttonLabels.getString(1),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",2);
result.put("input1", promptInput.getText());
} catch (JSONException e) { e.printStackTrace(); }
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) { }
}
// Third button
if (buttonLabels.length() > 2) {
try {
dlg.setPositiveButton(buttonLabels.getString(2),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",3);
result.put("input1", promptInput.getText());
} catch (JSONException e) { e.printStackTrace(); }
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
}
);
} catch (JSONException e) { }
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
dialog.dismiss();
try {
result.put("buttonIndex",0);
result.put("input1", promptInput.getText());
} catch (JSONException e) { e.printStackTrace(); }
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
dlg.create();
dlg.show();
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Show the spinner.
*

View File

@@ -22,7 +22,6 @@ import java.io.File;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@@ -137,7 +136,20 @@ public class Storage extends CordovaPlugin {
this.path = this.cordova.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
}
this.dbName = this.path + File.pathSeparator + db + ".db";
this.dbName = this.path + File.separator + db + ".db";
/*
* What is all this nonsense? Well the separator was incorrect so the db was showing up in the wrong
* directory. This bit of code fixes that issue and moves the db to the correct directory.
*/
File oldDbFile = new File(this.path + File.pathSeparator + db + ".db");
if (oldDbFile.exists()) {
File dbPath = new File(this.path);
File dbFile = new File(dbName);
dbPath.mkdirs();
oldDbFile.renameTo(dbFile);
}
this.myDb = SQLiteDatabase.openOrCreateDatabase(this.dbName, null);
}

View File

@@ -71,6 +71,24 @@ public class CallbackContext {
sendPluginResult(new PluginResult(PluginResult.Status.OK, message));
}
/**
* Helper for success callbacks that just returns the Status.OK by default
*
* @param message The message to add to the success result.
*/
public void success(byte[] message) {
sendPluginResult(new PluginResult(PluginResult.Status.OK, message));
}
/**
* Helper for success callbacks that just returns the Status.OK by default
*
* @param message The message to add to the success result.
*/
public void success(int message) {
sendPluginResult(new PluginResult(PluginResult.Status.OK, message));
}
/**
* Helper for success callbacks that just returns the Status.OK by default
*

View File

@@ -19,7 +19,6 @@
package org.apache.cordova.api;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import java.util.concurrent.ExecutorService;
@@ -54,11 +53,6 @@ public interface CordovaInterface {
*/
public abstract Activity getActivity();
@Deprecated
public abstract Context getContext();
@Deprecated
public abstract void cancelLoadUrl();
/**
* Called when a message is sent to plugin.

View File

@@ -18,11 +18,16 @@
*/
package org.apache.cordova.api;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.webkit.WebResourceResponse;
/**
* Plugins must extend this class and override one of the execute methods.
@@ -76,9 +81,28 @@ public class CordovaPlugin {
* @return Whether the action was valid.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
CordovaArgs cordovaArgs = new CordovaArgs(args);
return execute(action, cordovaArgs, callbackContext);
}
/**
* Executes the request.
*
* This method is called from the WebView thread. To do a non-trivial amount of work, use:
* cordova.getThreadPool().execute(runnable);
*
* To run on the UI thread, use:
* cordova.getActivity().runOnUiThread(runnable);
*
* @param action The action to execute.
* @param args The exec() arguments, wrapped with some Cordova helpers.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return Whether the action was valid.
*/
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
return false;
}
/**
* Called when the system is about to start resuming a previous activity.
*
@@ -131,7 +155,7 @@ public class CordovaPlugin {
}
/**
* By specifying a <url-filter> in plugins.xml you can map a URL (using startsWith atm) to this method.
* By specifying a <url-filter> in config.xml you can map a URL (using startsWith atm) to this method.
*
* @param url The URL that is trying to be loaded in the Cordova webview.
* @return Return true to prevent the URL from loading. Default is false.
@@ -140,6 +164,17 @@ public class CordovaPlugin {
return false;
}
/**
* By specifying a <url-filter> in config.xml you can map a URL prefix to this method. It applies to all resources loaded in the WebView, not just top-level navigation.
*
* @param url The URL of the resource to be loaded.
* @return Return a WebResourceResponse for the resource, or null to let the WebView handle it normally.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public WebResourceResponse shouldInterceptRequest(String url) {
return null;
}
/**
* Called when the WebView does a top-level navigation or refreshes.
*

View File

@@ -43,7 +43,6 @@ public class LegacyContext implements CordovaInterface {
@Deprecated
public void cancelLoadUrl() {
Log.i(LOG_TAG, "Replace ctx.cancelLoadUrl() with cordova.cancelLoadUrl()");
this.cordova.cancelLoadUrl();
}
@Deprecated
@@ -55,7 +54,7 @@ public class LegacyContext implements CordovaInterface {
@Deprecated
public Context getContext() {
Log.i(LOG_TAG, "Replace ctx.getContext() with cordova.getContext()");
return this.cordova.getContext();
return this.cordova.getActivity();
}
@Deprecated

View File

@@ -1,177 +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.api;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Legacy Plugin class. This acts as a shim to support the old execute() signature.
* New plugins should extend CordovaPlugin directly.
*/
@Deprecated
public abstract class Plugin extends CordovaPlugin {
public LegacyContext ctx; // LegacyContext object
public abstract PluginResult execute(String action, JSONArray args, String callbackId);
public boolean isSynch(String action) {
return false;
}
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.setContext(cordova);
this.setView(webView);
}
/**
* Sets the context of the Plugin. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param ctx The context of the main Activity.
*/
public void setContext(CordovaInterface ctx) {
this.cordova = ctx;
this.ctx = new LegacyContext(cordova);
}
/**
* Sets the main View of the application, this is the WebView within which
* a Cordova app runs.
*
* @param webView The Cordova WebView
*/
public void setView(CordovaWebView webView) {
this.webView = webView;
}
@Override
public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String callbackId = callbackContext.getCallbackId();
boolean runAsync = !isSynch(action);
if (runAsync) {
// Run this on a different thread so that this one can return back to JS
cordova.getThreadPool().execute(new Runnable() {
public void run() {
PluginResult cr;
try {
cr = execute(action, args, callbackId);
} catch (Throwable e) {
cr = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
}
sendPluginResult(cr, callbackId);
}
});
} else {
PluginResult cr = execute(action, args, callbackId);
// Interpret a null response as NO_RESULT, which *does* clear the callbacks on the JS side.
if (cr == null) {
cr = new PluginResult(PluginResult.Status.NO_RESULT);
}
callbackContext.sendPluginResult(cr);
}
return true;
}
/**
* Send generic JavaScript statement back to JavaScript.
* sendPluginResult() should be used instead where possible.
*/
public void sendJavascript(String statement) {
this.webView.sendJavascript(statement);
}
/**
* Send generic JavaScript statement back to JavaScript.
*/
public void sendPluginResult(PluginResult pluginResult, String callbackId) {
this.webView.sendPluginResult(pluginResult, callbackId);
}
/**
* Call the JavaScript success callback for this plugin.
*
* This can be used if the execute code for the plugin is asynchronous meaning
* that execute should return null and the callback from the async operation can
* call success(...) or error(...)
*
* @param pluginResult The result to return.
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void success(PluginResult pluginResult, String callbackId) {
this.webView.sendPluginResult(pluginResult, callbackId);
}
/**
* Helper for success callbacks that just returns the Status.OK by default
*
* @param message The message to add to the success result.
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void success(JSONObject message, String callbackId) {
this.webView.sendPluginResult(new PluginResult(PluginResult.Status.OK, message), callbackId);
}
/**
* Helper for success callbacks that just returns the Status.OK by default
*
* @param message The message to add to the success result.
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void success(String message, String callbackId) {
this.webView.sendPluginResult(new PluginResult(PluginResult.Status.OK, message), callbackId);
}
/**
* Call the JavaScript error callback for this plugin.
*
* @param pluginResult The result to return.
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void error(PluginResult pluginResult, String callbackId) {
this.webView.sendPluginResult(pluginResult, callbackId);
}
/**
* Helper for error callbacks that just returns the Status.ERROR by default
*
* @param message The message to add to the error result.
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void error(JSONObject message, String callbackId) {
this.webView.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, message), callbackId);
}
/**
* Helper for error callbacks that just returns the Status.ERROR by default
*
* @param message The message to add to the error result.
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void error(String message, String callbackId) {
this.webView.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, message), callbackId);
}
}

View File

@@ -22,17 +22,16 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Intent;
import android.content.res.XmlResourceParser;
import android.util.Log;
import android.webkit.WebResourceResponse;
/**
* PluginManager is exposed to JavaScript in the Cordova WebView.
@@ -122,7 +121,7 @@ public class PluginManager {
// System.out.println("Plugin: "+name+" => "+value);
onload = "true".equals(xml.getAttributeValue(null, "onload"));
entry = new PluginEntry(service, pluginClass, onload);
this.addService(entry);
this.addService(entry);
}
//What is this?
else if (strNode.equals("url-filter")) {
@@ -215,6 +214,7 @@ public class PluginManager {
public boolean exec(String service, String action, String callbackId, String rawArgs) {
CordovaPlugin plugin = this.getPlugin(service);
if (plugin == null) {
Log.d(TAG, "exec() call to unknown plugin: " + service);
PluginResult cr = new PluginResult(PluginResult.Status.CLASS_NOT_FOUND_EXCEPTION);
app.sendPluginResult(cr, callbackId);
return true;
@@ -248,7 +248,7 @@ public class PluginManager {
* @param service The name of the service.
* @return CordovaPlugin or null
*/
private CordovaPlugin getPlugin(String service) {
public CordovaPlugin getPlugin(String service) {
PluginEntry entry = this.entries.get(service);
if (entry == null) {
return null;
@@ -370,6 +370,25 @@ public class PluginManager {
return false;
}
/**
* Called when the WebView is loading any resource, top-level or not.
*
* Uses the same url-filter tag as onOverrideUrlLoading.
*
* @param url The URL of the resource to be loaded.
* @return Return a WebResourceResponse with the resource, or null if the WebView should handle it.
*/
public WebResourceResponse shouldInterceptRequest(String url) {
Iterator<Entry<String, String>> it = this.urlMap.entrySet().iterator();
while (it.hasNext()) {
HashMap.Entry<String, String> pairs = it.next();
if (url.startsWith(pairs.getKey())) {
return this.getPlugin(pairs.getValue()).shouldInterceptRequest(url);
}
}
return null;
}
/**
* Called when the app navigates or refreshes.
*/

View File

@@ -21,6 +21,8 @@ package org.apache.cordova.api;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Base64;
public class PluginResult {
private final int status;
private final int messageType;
@@ -34,7 +36,7 @@ public class PluginResult {
public PluginResult(Status status, String message) {
this.status = status.ordinal();
this.messageType = MESSAGE_TYPE_STRING;
this.messageType = message == null ? MESSAGE_TYPE_NULL : MESSAGE_TYPE_STRING;
this.strMessage = message;
}
@@ -68,6 +70,16 @@ public class PluginResult {
this.encodedMessage = Boolean.toString(b);
}
public PluginResult(Status status, byte[] data) {
this(status, data, false);
}
public PluginResult(Status status, byte[] data, boolean binaryString) {
this.status = status.ordinal();
this.messageType = binaryString ? MESSAGE_TYPE_BINARYSTRING : MESSAGE_TYPE_ARRAYBUFFER;
this.encodedMessage = Base64.encodeToString(data, Base64.NO_WRAP);
}
public void setKeepCallback(boolean b) {
this.keepCallback = b;
}
@@ -79,7 +91,7 @@ public class PluginResult {
public int getMessageType() {
return messageType;
}
public String getMessage() {
if (encodedMessage == null) {
encodedMessage = JSONObject.quote(strMessage);
@@ -133,7 +145,12 @@ public class PluginResult {
public static final int MESSAGE_TYPE_JSON = 2;
public static final int MESSAGE_TYPE_NUMBER = 3;
public static final int MESSAGE_TYPE_BOOLEAN = 4;
public static final int MESSAGE_TYPE_NULL = 5;
public static final int MESSAGE_TYPE_ARRAYBUFFER = 6;
// Use BINARYSTRING when your string may contain null characters.
// This is required to work around a bug in the platform :(.
public static final int MESSAGE_TYPE_BINARYSTRING = 7;
public static String[] StatusMessages = new String[] {
"No result",
"OK",

View File

@@ -18,7 +18,7 @@
under the License.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:windowSoftInputMode="adjustPan"
package="org.apache.cordova.test" android:versionName="1.1" android:versionCode="5">
package="org.apache.cordova.test" android:versionName="1.0" android:versionCode="1">
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
@@ -59,24 +59,17 @@
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".CordovaWebViewTestActivity" >
android:name=".actions.CordovaWebViewTestActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="tests" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".JailActivity" >
android:name=".actions.backbbuttonmultipage" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
@@ -86,8 +79,8 @@
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".CordovaDriverAction" >
<intent-filter >
android:name=".actions.background" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
@@ -96,62 +89,181 @@
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".CordovaActivity" >
android:name=".actions.basicauth" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="splashscreen" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.CordovaActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="timeout" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.CordovaDriverAction" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="htmlnotfound" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.errorurl" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="errorurl" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="userwebview" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.htmlnotfound" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="menus" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.iframe" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="loading" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.jqmtabbackbutton" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="lifecycle" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.lifecycle" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="jqmtabbackbutton" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.loading" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="backbuttonmultipage" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.menus" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="whitelist" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.splashscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="background" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.tests" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="iframe" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.timeout" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="xhr" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.userwebview" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="basicauth" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.whitelist" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="fullscreen" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.xhr" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
<activity android:name="backgroundcolor" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".actions.backbuttonmultipage" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
</activity>
</application>
</manifest>

File diff suppressed because it is too large Load Diff

View File

@@ -45,24 +45,24 @@
<h4>Cordova Version: <span id="cordova">&nbsp;</span></h4>
</div>
<div id="info">
<h4>Run each of the tests below:</h4>
<h4>Run each of the test activities below:</h4>
</div>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.jqmtabbackbutton');">Backbutton jQM tab</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.backbuttonmultipage');">Backbutton with multiple pages</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.backgroundcolor');">Background Color</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.basicauth');">Basic Authentication</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.errorurl');">Error URL</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.fullscreen');">Full Screen</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.htmlnotfound');">HTML not found</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.iframe');">IFrame</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.lifecycle');">Lifecycle</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.loading');">Loading indicator</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.menus');">Menus</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.background');">No multitasking</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.splashscreen');">Splash screen</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.timeout');">Load timeout</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.userwebview');">User WebView/Client/Chrome</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.whitelist');">Whitelist</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.xhr');">XHR</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.jqmtabbackbutton');">Backbutton jQM tab</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.backbuttonmultipage');">Backbutton with multiple pages</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.backgroundcolor');">Background Color</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.basicauth');">Basic Authentication</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.errorurl');">Error URL</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.fullscreen');">Full Screen</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.htmlnotfound');">HTML not found</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.iframe');">IFrame</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.lifecycle');">Lifecycle</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.loading');">Loading indicator</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.menus');">Menus</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.background');">No multitasking</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.splashscreen');">Splash screen</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.timeout');">Load timeout</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.userwebview');">User WebView/Client/Chrome</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.whitelist');">Whitelist</button>
<button class="btn large" onclick="startActivity('org.apache.cordova.test.actions.xhr');">XHR</button>
</body>
</html>

View File

@@ -8,5 +8,5 @@
# project structure.
# Project target.
target=android-16
target=android-17
android.library.reference.1=../framework

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
<!--
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
@@ -17,6 +17,20 @@
specific language governing permissions and limitations
under the License.
-->
<cordova>
<!--
access elements control the Android whitelist.
Domains are assumed blocked unless set otherwise
-->
<access origin="http://127.0.0.1*"/> <!-- allow local pages -->
<!-- <access origin="https://example.com" /> allow any secure requests to example.com -->
<!-- <access origin="https://example.com" subdomains="true" /> such as above, but including subdomains, such as www -->
<access origin=".*"/>
<log level="DEBUG"/>
<preference name="useBrowserHistory" value="true" />
<plugins>
<plugin name="App" value="org.apache.cordova.App"/>
<plugin name="Activity" value="org.apache.cordova.test.ActivityPlugin"/>
@@ -31,9 +45,13 @@
<plugin name="NetworkStatus" value="org.apache.cordova.NetworkManager"/>
<plugin name="Notification" value="org.apache.cordova.Notification"/>
<plugin name="Storage" value="org.apache.cordova.Storage"/>
<plugin name="Temperature" value="org.apache.cordova.TempListener"/>
<plugin name="FileTransfer" value="org.apache.cordova.FileTransfer"/>
<plugin name="Capture" value="org.apache.cordova.Capture"/>
<plugin name="Battery" value="org.apache.cordova.BatteryListener"/>
<plugin name="SplashScreen" value="org.apache.cordova.SplashScreen"/>
<plugin name="Echo" value="org.apache.cordova.Echo" />
<plugin name="Globalization" value="org.apache.cordova.Globalization"/>
<plugin name="InAppBrowser" value="org.apache.cordova.InAppBrowser"/>
</plugins>
</cordova>

View File

@@ -1,37 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
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.
-->
<cordova>
<!--
access elements control the Android whitelist.
Domains are assumed blocked unless set otherwise
-->
<access origin="http://127.0.0.1*"/> <!-- allow local pages -->
<!-- <access origin="https://example.com" /> allow any secure requests to example.com -->
<!-- <access origin="https://example.com" subdomains="true" /> such as above, but including subdomains, such as www -->
<!-- <access origin=".*"/> Allow all domains, suggested development use only -->
<log level="DEBUG"/>
<preference name="useBrowserHistory" value="true" />
</cordova>

View File

@@ -18,19 +18,21 @@
*/
package org.apache.cordova.test;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.api.LOG;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
/**
* This class provides a service.
*/
public class ActivityPlugin extends Plugin {
public class ActivityPlugin extends CordovaPlugin {
static String TAG = "ActivityPlugin";
@@ -48,19 +50,21 @@ public class ActivityPlugin extends Plugin {
* @param callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext) {
PluginResult result = new PluginResult(PluginResult.Status.OK, "");
try {
if (action.equals("start")) {
this.startActivity(args.getString(0));
callbackContext.sendPluginResult(result);
callbackContext.success();
return true;
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, "JSON Exception");
callbackContext.sendPluginResult(result);
return false;
}
return false;
}
// --------------------------------------------------------------------------
@@ -69,9 +73,9 @@ public class ActivityPlugin extends Plugin {
public void startActivity(String className) {
try {
Intent intent = new Intent().setClass(this.ctx.getActivity(), Class.forName(className));
Intent intent = new Intent().setClass(this.cordova.getActivity(), Class.forName(className));
LOG.d(TAG, "Starting activity %s", className);
this.ctx.getActivity().startActivity(intent);
this.cordova.getActivity().startActivity(intent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
LOG.e(TAG, "Error starting activity %s", className);

View File

@@ -22,9 +22,11 @@ package org.apache.cordova.test;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.test.actions.backbuttonmultipage;
import android.test.ActivityInstrumentationTestCase2;
import android.view.KeyEvent;
import android.view.inputmethod.BaseInputConnection;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
@@ -96,6 +98,54 @@ public class BackButtonMultiPageTest extends ActivityInstrumentationTestCase2<ba
assertTrue(didGoBack);
}
public void testViaBackButtonOnView() {
testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample2.html");
sleep();
String url = testView.getUrl();
assertTrue(url.endsWith("sample2.html"));
testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample3.html");
sleep();
url = testView.getUrl();
assertTrue(url.endsWith("sample3.html"));
BaseInputConnection viewConnection = new BaseInputConnection(testView, true);
KeyEvent backDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
KeyEvent backUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
viewConnection.sendKeyEvent(backDown);
viewConnection.sendKeyEvent(backUp);
sleep();
url = testView.getUrl();
assertTrue(url.endsWith("sample2.html"));
viewConnection.sendKeyEvent(backDown);
viewConnection.sendKeyEvent(backUp);
sleep();
url = testView.getUrl();
assertTrue(url.endsWith("index.html"));
}
public void testViaBackButtonOnLayout() {
testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample2.html");
sleep();
String url = testView.getUrl();
assertTrue(url.endsWith("sample2.html"));
testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample3.html");
sleep();
url = testView.getUrl();
assertTrue(url.endsWith("sample3.html"));
BaseInputConnection viewConnection = new BaseInputConnection(containerView, true);
KeyEvent backDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
KeyEvent backUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
viewConnection.sendKeyEvent(backDown);
viewConnection.sendKeyEvent(backUp);
sleep();
url = testView.getUrl();
assertTrue(url.endsWith("sample2.html"));
viewConnection.sendKeyEvent(backDown);
viewConnection.sendKeyEvent(backUp);
sleep();
url = testView.getUrl();
assertTrue(url.endsWith("index.html"));
}
private void sleep() {
try {
Thread.sleep(TIMEOUT);

View File

@@ -21,6 +21,7 @@ package org.apache.cordova.test;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.api.PluginManager;
import org.apache.cordova.test.actions.CordovaActivity;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;

View File

@@ -20,6 +20,7 @@ package org.apache.cordova.test;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.api.PluginManager;
import org.apache.cordova.test.actions.CordovaWebViewTestActivity;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
@@ -48,10 +49,13 @@ public class CordovaTest extends
}
public void testForCordovaView() {
//Sleep for no reason!!!!
sleep();
String className = testView.getClass().getSimpleName();
assertTrue(className.equals("CordovaWebView"));
}
/*
/*
public void testForPluginManager() {
CordovaWebView v = (CordovaWebView) testView;
PluginManager p = v.getPluginManager();

View File

@@ -22,6 +22,7 @@ package org.apache.cordova.test;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.test.actions.errorurl;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.FrameLayout;

View File

@@ -22,6 +22,7 @@ package org.apache.cordova.test;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaChromeClient;
import org.apache.cordova.api.PluginManager;
import org.apache.cordova.test.actions.CordovaWebViewTestActivity;
import android.content.Context;
import android.content.res.AssetManager;

View File

@@ -22,6 +22,7 @@ package org.apache.cordova.test;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.test.actions.htmlnotfound;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.FrameLayout;

View File

@@ -21,12 +21,72 @@ package org.apache.cordova.test;
*/
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.test.util.Purity;
import org.apache.cordova.test.actions.iframe;
import android.app.Activity;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.test.TouchUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class IFrameTest extends ActivityInstrumentationTestCase2<iframe> {
public class IFrameTest extends ActivityInstrumentationTestCase2 {
public IFrameTest() {
super("org.apache.cordova.test",iframe.class);
}
private Instrumentation mInstr;
private Activity testActivity;
private FrameLayout containerView;
private LinearLayout innerContainer;
private CordovaWebView testView;
private TouchUtils touch;
private Purity touchTool;
public IFrameTest() {
super("org.apache.cordova.test",iframe.class);
}
protected void setUp() throws Exception {
super.setUp();
mInstr = this.getInstrumentation();
testActivity = this.getActivity();
containerView = (FrameLayout) testActivity.findViewById(android.R.id.content);
innerContainer = (LinearLayout) containerView.getChildAt(0);
testView = (CordovaWebView) innerContainer.getChildAt(0);
touch = new TouchUtils();
touchTool = new Purity(testActivity, getInstrumentation());
}
public void testIframeDest()
{
testView.sendJavascript("loadUrl('http://maps.google.com/maps?output=embed');");
sleep(3000);
testView.sendJavascript("loadUrl('index2.html')");
sleep(1000);
String url = testView.getUrl();
assertTrue(url.endsWith("index.html"));
}
public void testIframeHistory()
{
testView.sendJavascript("loadUrl('http://maps.google.com/maps?output=embed');");
sleep(3000);
testView.sendJavascript("loadUrl('index2.html')");
sleep(1000);
String url = testView.getUrl();
testView.backHistory();
sleep(1000);
assertTrue(url.endsWith("index.html"));
}
private void sleep(int timeout) {
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
fail("Unexpected Timeout");
}
}
}

View File

@@ -21,13 +21,55 @@ package org.apache.cordova.test;
*/
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.test.util.Purity;
import org.apache.cordova.test.actions.jqmtabbackbutton;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
public class JQMTabTest extends ActivityInstrumentationTestCase2<jqmtabbackbutton> {
public JQMTabTest(Class<jqmtabbackbutton> activityClass) {
super(activityClass);
// TODO Auto-generated constructor stub
private Instrumentation mInstr;
private jqmtabbackbutton testActivity;
private FrameLayout containerView;
private LinearLayout innerContainer;
private CordovaWebView testView;
private Purity touchTool;
public JQMTabTest()
{
super("org.apache.cordova.test.activity", jqmtabbackbutton.class);
}
protected void setUp() throws Exception {
super.setUp();
mInstr = this.getInstrumentation();
testActivity = this.getActivity();
containerView = (FrameLayout) testActivity.findViewById(android.R.id.content);
innerContainer = (LinearLayout) containerView.getChildAt(0);
testView = (CordovaWebView) innerContainer.getChildAt(0);
touchTool = new Purity(testActivity, getInstrumentation());
}
public void testTouch()
{
sleep(5000);
int viewportHeight = touchTool.getViewportHeight() - 40;
int viewportWidth = touchTool.getViewportWidth();
touchTool.touch(50, viewportHeight);
sleep(10000);
}
private void sleep(int timeout) {
try {
Thread.sleep(timeout);
} catch (InterruptedException e) {
fail("Unexpected Timeout");
}
}
}

View File

@@ -21,6 +21,8 @@ package org.apache.cordova.test;
*/
import org.apache.cordova.test.actions.lifecycle;
import android.test.ActivityInstrumentationTestCase2;
public class LifecycleTest extends ActivityInstrumentationTestCase2<lifecycle> {

View File

@@ -21,6 +21,7 @@ package org.apache.cordova.test;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.api.PluginManager;
import org.apache.cordova.test.actions.CordovaWebViewTestActivity;
import android.test.ActivityInstrumentationTestCase2;
import android.view.View;

View File

@@ -22,6 +22,7 @@ package org.apache.cordova.test;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.test.actions.splashscreen;
import android.app.Dialog;
import android.test.ActivityInstrumentationTestCase2;

View File

@@ -24,6 +24,7 @@ package org.apache.cordova.test;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewClient;
import org.apache.cordova.CordovaChromeClient;
import org.apache.cordova.test.actions.userwebview;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.FrameLayout;

View File

@@ -21,6 +21,8 @@ package org.apache.cordova.test;
*/
import org.apache.cordova.test.actions.xhr;
import android.test.ActivityInstrumentationTestCase2;
public class XhrTest extends ActivityInstrumentationTestCase2<xhr> {

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import org.apache.cordova.DroidGap;

View File

@@ -17,7 +17,7 @@
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import java.util.concurrent.ExecutorService;

View File

@@ -17,13 +17,18 @@
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.LOG;
import org.apache.cordova.test.R;
import org.apache.cordova.test.R.id;
import org.apache.cordova.test.R.layout;
import android.app.Activity;
import android.content.Context;
@@ -33,6 +38,8 @@ import android.os.Bundle;
public class CordovaWebViewTestActivity extends Activity implements CordovaInterface {
CordovaWebView cordovaWebView;
private final ExecutorService threadPool = Executors.newCachedThreadPool();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
@@ -46,14 +53,6 @@ public class CordovaWebViewTestActivity extends Activity implements CordovaInter
}
public void onDestroy()
{
super.onDestroy();
if (cordovaWebView.pluginManager != null) {
cordovaWebView.pluginManager.onDestroy();
}
}
public Context getContext() {
return this;
}
@@ -69,9 +68,9 @@ public class CordovaWebViewTestActivity extends Activity implements CordovaInter
}
//Note: This must always return an activity!
public Activity getActivity() {
// TODO Auto-generated method stub
return null;
return this;
}
@Deprecated
@@ -87,6 +86,19 @@ public class CordovaWebViewTestActivity extends Activity implements CordovaInter
public ExecutorService getThreadPool() {
// TODO Auto-generated method stub
return null;
return threadPool;
}
@Override
/**
* The final call you receive before your activity is destroyed.
*/
public void onDestroy() {
super.onDestroy();
if (cordovaWebView != null) {
// Send destroy event to JavaScript
cordovaWebView.loadUrl("javascript:try{cordova.require('cordova/channel').onDestroy.fire();}catch(e){console.log('exception firing destroy event from native');};");
cordovaWebView.handleDestroy();
}
}
}

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import org.apache.cordova.*;

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import org.apache.cordova.*;
@@ -34,7 +34,8 @@ public class basicauth extends DroidGap {
super.setAuthenticationToken(token, "browserspy.dk:80", "BrowserSpy.dk - HTTP Password Test");
// Add web site to whitelist
super.appView.addWhiteListEntry("http://browserspy.dk*", true);
Config.init();
Config.addWhiteListEntry("http://browserspy.dk*", true);
// Load test
super.loadUrl("file:///android_asset/www/basicauth/index.html");

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import org.apache.cordova.*;

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import org.apache.cordova.*;

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import org.apache.cordova.*;

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import org.apache.cordova.*;

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import org.apache.cordova.*;

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import org.apache.cordova.*;

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import org.apache.cordova.*;

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import android.view.ContextMenu;

View File

@@ -16,10 +16,12 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import org.apache.cordova.*;
import org.apache.cordova.test.R;
import org.apache.cordova.test.R.drawable;
public class splashscreen extends DroidGap {
@Override

View File

@@ -16,7 +16,7 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
package org.apache.cordova.test.actions;
import android.os.Bundle;
import org.apache.cordova.*;

Some files were not shown because too many files have changed in this diff Show More