Compare commits

..

1 Commits

Author SHA1 Message Date
Joe Bowser
11dbf05c84 Incrementing version for tagging 2012-06-12 11:19:58 -07:00
131 changed files with 8919 additions and 6126 deletions

View File

@@ -20,10 +20,6 @@ Requires
- Android SDK [http://developer.android.com](http://developer.android.com)
- Apache Commons Codec [http://commons.apache.org/codec/](http://commons.apache.org/codec/)
Test Requirements
---
- JUnit - [https://github.com/KentBeck/junit](https://github.com/KentBeck/junit)
Building
---
@@ -102,9 +98,6 @@ Importing a Cordova Android Project into Eclipse
5. Right click on the project root: Run as > Run Configurations
6. Click on the Target tab and select Manual (this way you can choose the emulator or device to build to)
Running Tests
----
Please see details under test/README.md.
Further Reading
---

View File

@@ -1 +1 @@
1.9.0rc1
1.8.1

2
bin/autotest Executable file
View File

@@ -0,0 +1,2 @@
#! /usr/bin/env node
require('nodeunit').reporters.default.run(['bin/tests'])

47
bin/bench Executable file
View File

@@ -0,0 +1,47 @@
#! /bin/sh
# 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.
#
#
#
# Creates an app in `./bench` that posts results to http://cordova-bench.heroku.com with current cordova/Android sha.
#
# USAGE
# ./bin/bench
#
# clobber any existing bench
if [ -e ./bench ]
then
rm -rf ./bench
fi
# create a benching app
./bin/create ./bench org.apache.cordova.bench cordovaBench
# grab the latest bench www code
git clone git@github.com:brianleroux/cordova-bench.git
# copy it into the app
cat ./cordova-bench/www/index.html > ./bench/assets/www/index.html
#cat ~/Desktop/cordova-bench/www/index.html > ./bench/assets/www/index.html
# clean up
rm -rf ./cordova-bench
# launch to the first device found
./bin/debug ./bench

View File

@@ -23,103 +23,52 @@
#
set -e
if [ -n "$1" ] && [ "$1" == "-h" ]
then
echo 'usage: create path package activity'
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"}
PACKAGE=${2:-"org.apache.cordova.example"}
ACTIVITY=${3:-"cordovaExample"}
TARGET=$(android list targets | grep 'id: ' | sed 's/id: \([0-9]*\).*/\1/g' | tail -1)
VERSION=$(cat ./VERSION)
# clobber any existing example
if [ -d $PROJECT_PATH ]
if [ $# -eq 0 ]
then
echo "Project already exists! Delete and recreate"
exit 1
rm -rf $PROJECT_PATH
fi
# cleanup after exit and/or on error
function on_exit {
echo "Cleaning up ..."
# [ -f $BUILD_PATH/framework/libs/commons-codec-1.6.jar ] && rm $BUILD_PATH/framework/libs/commons-codec-1.6.jar
# [ -d $BUILD_PATH/framework/libs ] && rmdir $BUILD_PATH/framework/libs
[ -f $BUILD_PATH/framework/assets/www/cordova-$VERSION.js ] && rm $BUILD_PATH/framework/assets/www/cordova-$VERSION.js
[ -f $BUILD_PATH/framework/cordova-$VERSION.jar ] && rm $BUILD_PATH/framework/cordova-$VERSION.jar
}
function on_error {
echo "An error occured. Deleting project..."
[ -d $PROJECT_PATH ] && rm -rf $PROJECT_PATH
}
# we do not want the script to silently fail
trap on_error ERR
trap on_exit EXIT
ANDROID_BIN=$( which android )
PACKAGE_AS_PATH=$(echo $PACKAGE | sed 's/\./\//g')
ACTIVITY_PATH=$PROJECT_PATH/src/$PACKAGE_AS_PATH/$ACTIVITY.java
MANIFEST_PATH=$PROJECT_PATH/AndroidManifest.xml
TARGET=$($ANDROID_BIN list targets | grep id: | tail -1 | cut -f 2 -d ' ' )
# update the cordova-android framework for the desired target
$ANDROID_BIN update project --target $TARGET --path $BUILD_PATH/framework &> /dev/null
android update project --target $TARGET --path ./framework
if [ ! -e $BUILD_PATH/framework/libs/commons-codec-1.6.jar ]; then
if [ ! -e ./framework/libs/commons-codec-1.6.jar ]; then
# Use curl to get the jar (TODO: Support Apache Mirrors)
echo "Downloading common-codecs-1.6 ..."
curl -OL http://mirror.symnds.com/software/Apache//commons/codec/binaries/commons-codec-1.6-bin.zip &> /dev/null
unzip commons-codec-1.6-bin.zip &> /dev/null
mkdir -p $BUILD_PATH/framework/libs
cp commons-codec-1.6/commons-codec-1.6.jar $BUILD_PATH/framework/libs
# cleanup yo
rm commons-codec-1.6-bin.zip && rm -rf commons-codec-1.6
curl -OL http://mirror.symnds.com/software/Apache//commons/codec/binaries/commons-codec-1.6-bin.zip
unzip commons-codec-1.6-bin.zip
mkdir -p ./framework/libs
cp commons-codec-1.6/commons-codec-1.6.jar ./framework/libs/
fi
# compile cordova.js and cordova.jar
echo "Building cordova-$VERSION.jar and cordova-$VERSION.js ..."
(cd $BUILD_PATH/framework && ant jar &> /dev/null )
cd ./framework && ant jar && cd ../
# create new android project
echo "Creating a new cordova android project ..."
$ANDROID_BIN create project --target $TARGET --path $PROJECT_PATH --package $PACKAGE --activity $ACTIVITY &> /dev/null
# copy all the bin scripts etc in there
cp -R ./bin/templates/project/ $PROJECT_PATH
# copy project template
echo "Copying assets and resources ..."
cp -r $BUILD_PATH/bin/templates/project/assets $PROJECT_PATH
cp -r $BUILD_PATH/bin/templates/project/res $PROJECT_PATH
# copy in cordova.js
cp ./framework/assets/www/cordova-$VERSION.js $PROJECT_PATH/.cordova/android/cordova-$VERSION.js
# copy cordova.js, cordova.jar and res/xml
echo "Setting up config and plugins list ..."
cp -r $BUILD_PATH/framework/res/xml $PROJECT_PATH/res
# copy in cordova.jar
cp ./framework/cordova-$VERSION.jar $PROJECT_PATH/.cordova/android/cordova-$VERSION.jar
echo "Adding cordova-$VERSION.js and cordova-$VERSION.jar ..."
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
# copy in res/xml
cp ./framework/res/xml/cordova.xml $PROJECT_PATH/.cordova/android/cordova.xml
cp ./framework/res/xml/plugins.xml $PROJECT_PATH/.cordova/android/plugins.xml
# interpolate the activity name and package
echo "Updating Activity and AndroidManifest ..."
cp $BUILD_PATH/bin/templates/project/Activity.java $ACTIVITY_PATH
sed -i '' -e "s/__ACTIVITY__/${ACTIVITY}/g" $ACTIVITY_PATH
sed -i '' -e "s/__ID__/${PACKAGE}/g" $ACTIVITY_PATH
# app properties
cat > $PROJECT_PATH/.cordova/config <<eom
VERSION=$VERSION
PROJECT_PATH=$PROJECT_PATH
PACKAGE=$PACKAGE
ACTIVITY=$ACTIVITY
TARGET=$TARGET
eom
cp $BUILD_PATH/bin/templates/project/AndroidManifest.xml $MANIFEST_PATH
sed -i '' -e "s/__ACTIVITY__/${ACTIVITY}/g" $MANIFEST_PATH
sed -i '' -e "s/__PACKAGE__/${PACKAGE}/g" $MANIFEST_PATH
# creating cordova folder and copying emulate/debug/log/launch scripts
mkdir $PROJECT_PATH/cordova
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/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
(cd $PROJECT_PATH && ./cordova/create)

View File

@@ -1,15 +1 @@
@ECHO OFF
IF NOT DEFINED JAVA_HOME GOTO MISSING
FOR %%X in (java.exe ant.bat android.bat) do (
SET FOUND=%%~$PATH:X
IF NOT DEFINED FOUND GOTO MISSING
)
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
EXIT /B 1
:END
cscript bin\create.js %*

View File

@@ -24,19 +24,14 @@
* ./create [path package activity]
*/
var fso = WScript.CreateObject('Scripting.FileSystemObject');
function read(filename) {
WScript.Echo('Reading in ' + filename);
var fso=WScript.CreateObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile(filename, 1);
var s=f.ReadAll();
f.Close();
return s;
}
function setTarget() {
var targets = shell.Exec('android.bat list targets').StdOut.ReadAll().match(/id:\s\d+/g);
return targets[targets.length - 1].replace(/id: /, ""); // TODO: give users the option to set their target
}
function write(filename, contents) {
var fso=WScript.CreateObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile(filename, 2, true);
@@ -46,65 +41,24 @@ function write(filename, contents) {
function replaceInFile(filename, regexp, replacement) {
write(filename, read(filename).replace(regexp, replacement));
}
function exec(command) {
var oShell=shell.Exec(command);
while (oShell.Status == 0) {
WScript.sleep(100);
function exec(s, output) {
WScript.Echo('Executing ' + s);
var o=shell.Exec(s);
while (o.Status == 0) {
WScript.Sleep(100);
}
WScript.Echo("Command exited with code " + o.Status);
}
function cleanup() {
// Cleanup
// if(fso.FileExists(ROOT + '\\framework\\libs\\commons-codec-1.6.jar')) {
// fso.DeleteFile(ROOT + '\\framework\\libs\\commons-codec-1.6.jar');
// fso.DeleteFolder(ROOT + '\\framework\\libs', true);
// }
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.6.jar')) {
// We need the .jar
var url = 'http://mirror.symnds.com/software/Apache//commons/codec/binaries/commons-codec-1.6-bin.zip';
var libsPath = ROOT + '\\framework\\libs';
var savePath = libsPath + '\\commons-codec-1.6-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.6\\commons-codec-1.6.jar', ROOT + '\\framework\\libs\\commons-codec-1.6.jar');
// Clean up
fso.DeleteFile(ROOT + '\\framework\\libs\\commons-codec-1.6-bin.zip');
fso.DeleteFolder(ROOT + '\\framework\\libs\\commons-codec-1.6', true);
function fork(s) {
WScript.Echo('Executing ' + s);
var o=shell.Exec(s);
while (o.Status != 1) {
WScript.Sleep(100);
}
WScript.Echo(o.StdOut.ReadAll());
WScript.Echo(o.StdErr.ReadAll());
WScript.Echo("Command exited with code " + o.Status);
}
var args = WScript.Arguments, PROJECT_PATH="example",
@@ -115,65 +69,106 @@ var args = WScript.Arguments, PROJECT_PATH="example",
var ROOT = WScript.ScriptFullName.split('\\bin\\create.js').join('');
if (args.Count() == 3) {
WScript.Echo('Found expected arguments');
PROJECT_PATH=args(0);
PACKAGE=args(1);
ACTIVITY=args(2);
}
if(fso.FolderExists(PROJECT_PATH)) {
WScript.Echo("Project already exists!");
WScript.Quit(1);
}
var PACKAGE_AS_PATH=PACKAGE.replace(/\./g, '\\');
var ACTIVITY_PATH=PROJECT_PATH+'\\src\\'+PACKAGE_AS_PATH+'\\'+ACTIVITY+'.java';
var MANIFEST_PATH=PROJECT_PATH+'\\AndroidManifest.xml';
var TARGET=setTarget();
var VERSION=read(ROOT+'\\VERSION').replace(/\r\n/,'').replace(/\n/,'');
var TARGET=shell.Exec('android.bat list targets').StdOut.ReadAll().match(/id:\s([0-9]).*/)[1];
var VERSION=read('VERSION').replace(/\r\n/,'').replace(/\n/,'');
WScript.Echo("Project path: " + PROJECT_PATH);
WScript.Echo("Package: " + PACKAGE);
WScript.Echo("Activity: " + ACTIVITY);
WScript.Echo("Package as path: " + PACKAGE_AS_PATH);
WScript.Echo("Activity path: " + ACTIVITY_PATH);
WScript.Echo("Manifest path: " + MANIFEST_PATH);
WScript.Echo("Cordova version: " + VERSION);
// TODO: clobber any existing example
/*
if [ $# -eq 0 ]
then
rm -rf $PROJECT_PATH
fi
*/
// create the project
exec('android.bat create project --target '+TARGET+' --path '+PROJECT_PATH+' --package '+PACKAGE+' --activity '+ACTIVITY);
// update the cordova framework project to a target that exists on this machine
exec('android.bat update project --target '+TARGET+' --path '+ROOT+'\\framework');
exec('android.bat update project --target '+TARGET+' --path framework');
// pull down commons codec if necessary
downloadCommonsCodec();
var fso = WScript.CreateObject('Scripting.FileSystemObject');
if (!fso.FileExists(ROOT + '\\framework\\libs\\commons-codec-1.6.jar')) {
// We need the .jar
var url = 'http://mirror.symnds.com/software/Apache//commons/codec/binaries/commons-codec-1.6-bin.zip';
var savePath = ROOT + '\\framework\\libs\\commons-codec-1.6-bin.zip';
if (!fso.FileExists(savePath)) {
// 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.6\\commons-codec-1.6.jar', ROOT + '\\framework\\libs\\commons-codec-1.6.jar');
// Clean up
fso.DeleteFile(ROOT + '\\framework\\libs\\commons-codec-1.6-bin.zip');
fso.DeleteFolder(ROOT + '\\framework\\libs\\commons-codec-1.6', true);
}
exec('ant.bat -f '+ ROOT +'\\framework\\build.xml jar');
// compile cordova.js and cordova.jar
// if you see an error about "Unable to resolve target" then you may need to
// update your android tools or install an additional Android platform version
exec('ant.bat -f framework\\build.xml jar');
// copy in the project template
exec('%comspec% /c xcopy '+ ROOT + '\\bin\\templates\\project\\res '+PROJECT_PATH+'\\res\\ /E /Y');
exec('%comspec% /c xcopy '+ ROOT + '\\bin\\templates\\project\\assets '+PROJECT_PATH+'\\assets\\ /E /Y');
exec('%comspec% /c copy '+ROOT+'\\bin\\templates\\project\\AndroidManifest.xml ' + PROJECT_PATH + '\\AndroidManifest.xml /Y');
exec('%comspec% /c copy '+ROOT+'\\bin\\templates\\project\\Activity.java '+ ACTIVITY_PATH +' /Y');
exec('cmd /c xcopy bin\\templates\\project\\* '+PROJECT_PATH+' /S /Y');
// copy example www assets
exec('cmd /c xcopy ' + PROJECT_PATH + '\\cordova\\assets ' + PROJECT_PATH + ' /S /Y');
// copy in cordova.js
exec('%comspec% /c copy '+ROOT+'\\framework\\assets\\www\\cordova-'+VERSION+'.js '+PROJECT_PATH+'\\assets\\www\\cordova-'+VERSION+'.js /Y');
exec('cmd /c copy framework\\assets\\js\\cordova.android.js '+PROJECT_PATH+'\\.cordova\\android\\cordova-'+VERSION+'.js /Y');
// copy in cordova.jar
exec('%comspec% /c copy '+ROOT+'\\framework\\cordova-'+VERSION+'.jar '+PROJECT_PATH+'\\libs\\cordova-'+VERSION+'.jar /Y');
exec('cmd /c copy framework\\cordova-'+VERSION+'.jar '+PROJECT_PATH+'\\.cordova\\android\\cordova-'+VERSION+'.jar /Y');
// copy in xml
fso.CreateFolder(PROJECT_PATH + '\\res\\xml');
exec('%comspec% /c copy '+ROOT+'\\framework\\res\\xml\\cordova.xml ' + PROJECT_PATH + '\\res\\xml\\cordova.xml /Y');
exec('%comspec% /c copy '+ROOT+'\\framework\\res\\xml\\plugins.xml ' + PROJECT_PATH + '\\res\\xml\\plugins.xml /Y');
exec('cmd /c copy framework\\res\\xml\\cordova.xml ' + PROJECT_PATH + '\\.cordova\\android\\cordova.xml /Y');
exec('cmd /c copy framework\\res\\xml\\plugins.xml ' + PROJECT_PATH + '\\.cordova\\android\\plugins.xml /Y');
// copy cordova scripts
fso.CreateFolder(PROJECT_PATH + '\\cordova');
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\\debug.bat ' + PROJECT_PATH + '\\cordova\\debug.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');
// write out config file
write(PROJECT_PATH + '\\.cordova\\config',
'VERSION=' + VERSION + '\r\n' +
'PROJECT_PATH=' + PROJECT_PATH + '\r\n' +
'PACKAGE=' + PACKAGE + '\r\n' +
'ACTIVITY=' + ACTIVITY + '\r\n' +
'TARGET=' + TARGET);
// interpolate the activity name and package
replaceInFile(ACTIVITY_PATH, /__ACTIVITY__/, ACTIVITY);
replaceInFile(ACTIVITY_PATH, /__ID__/, PACKAGE);
replaceInFile(MANIFEST_PATH, /__ACTIVITY__/, ACTIVITY);
replaceInFile(MANIFEST_PATH, /__PACKAGE__/, PACKAGE);
cleanup();
// run project-specific create process
fork('cscript.exe ' + PROJECT_PATH + '\\cordova\\create.js');

View File

@@ -18,5 +18,9 @@
"repository": {
"type": "git",
"url": "http://git-wip-us.apache.org/repos/asf/incubator-cordova-android.git"
},
"dependencies":{
"coffee-script":"1.1.2",
"nodeunit":"0.5.3"
}
}

View File

@@ -1,44 +0,0 @@
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import java.io.IOException;
public class ApplicationInfo {
private static void parseAndroidManifest(String path) {
// System.out.println(path);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document dom;
try {
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(path);
// getting package information
Element manifest = dom.getDocumentElement();
String pakkage = manifest.getAttribute("package");
// getting activity name
String activity = ((Element)dom.getElementsByTagName("activity").item(0)).getAttribute("android:name");
System.out.println(String.format("%s/.%s", pakkage, activity.replace(".", "")));
} catch(ParserConfigurationException pce) {
pce.printStackTrace();
} catch(SAXException se) {
se.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
public static void main(String[] args) {
String path;
if(args.length > 0) {
path = args[0];
} else {
path = System.getProperty("user.dir") + "/../AndroidManifest.xml";
}
parseAndroidManifest(path);
}
}

View File

@@ -1,7 +0,0 @@
#!/bin/bash
set -e
CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd )
bash $CORDOVA_PATH/cordova BOOM

View File

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

Binary file not shown.

View File

@@ -1,7 +0,0 @@
#!/bin/bash
set -e
CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd )
bash $CORDOVA_PATH/cordova clean

View File

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

View File

@@ -1,91 +0,0 @@
#!/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 }}'`
if [ -z "$devices" ] ; then
echo "1"
else
echo "0"
fi
}
function emulate {
declare -a avd_list=($(android list avd | grep "Name:" | cut -f 2 -d ":" | xargs))
# we need to start adb-server
adb start-server 1>/dev/null
# 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
local avd_id="1000" #FIXME: hopefully user does not have 1000 AVDs
# User has no AVDs
if [ ${#avd_list[@]} == 0 ]
then
echo "You don't have any Android Virtual Devices. Please create at least one AVD."
echo "android"
fi
# User has only one AVD
if [ ${#avd_list[@]} == 1 ]
then
emulator -cpu-delay 0 -no-boot-anim -cache /tmp/cache -avd ${avd_list[0]} 1> /dev/null 2>&1 &
# User has more than 1 AVD
elif [ ${#avd_list[@]} -gt 1 ]
then
while [ -z ${avd_list[$avd_id]} ]
do
echo "Choose from one of the following Android Virtual Devices [0 to $((${#avd_list[@]}-1))]:"
for(( i = 0 ; i < ${#avd_list[@]} ; i++ ))
do
echo "$i) ${avd_list[$i]}"
done
echo -n "> "
read avd_id
done
emulator -cpu-delay 0 -no-boot-anim -cache /tmp/cache -avd ${avd_list[$avd_id]} 1> /dev/null 2>&1 &
fi
}
function clean {
ant clean
}
# has to be used independently and not in conjuction with other commands
function log {
adb logcat
}
function debug_install {
ant debug install
}
function debug {
ant debug
}
function launch {
local launch_str=$(java -jar $PROJECT_PATH/cordova/appinfo.jar $PROJECT_PATH/AndroidManifest.xml)
adb shell am start -n $launch_str
}
function BOOM {
clean
if [ $(check_devices) == 0 ] ; then
debug_install && launch
return
else
debug
echo "##################################################################"
echo "# Plug in your device or launch an emulator with cordova/emulate #"
echo "##################################################################"
fi
}
# TODO parse arguments
(cd $PROJECT_PATH && $1)

View File

@@ -1,15 +0,0 @@
@ECHO OFF
IF NOT DEFINED JAVA_HOME GOTO MISSING
FOR %%X in (java.exe ant.bat android.bat) do (
SET FOUND=%%~$PATH:X
IF NOT DEFINED FOUND GOTO MISSING
)
cscript %~dp0\cordova.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

View File

@@ -1,108 +0,0 @@
var ROOT = WScript.ScriptFullName.split('\\cordova\\cordova.js').join(''),
shell=WScript.CreateObject("WScript.Shell");
function exec(command) {
var oExec=shell.Exec(command);
var output = new String();
while(oExec.Status == 0) {
if(!oExec.StdOut.AtEndOfStream) {
var line = oExec.StdOut.ReadLine();
// XXX: Change to verbose mode
//WScript.StdOut.WriteLine(line);
output += line;
}
WScript.sleep(100);
}
return output;
}
function emulator_running() {
var local_devices = shell.Exec("%comspec% /c adb devices").StdOut.ReadAll();
if(local_devices.match(/emulator/)) {
return true;
}
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!");
return;
}
var oExec = shell.Exec("%comspec% /c android.bat list avd");
var avd_list = [];
var avd_id = -10;
while(!oExec.StdOut.AtEndOfStream) {
var output = oExec.StdOut.ReadLine();
if(output.match(/Name: (.)*/)) {
avd_list.push(output.replace(/ *Name:\s/, ""));
}
}
// user has no AVDs
if(avd_list.length == 0) {
WScript.Echo("You don't have any Android Virtual Devices. Please create at least one AVD.");
WScript.Echo("android");
WScript.Quit(1);
}
// user has only one AVD so we launch that one
if(avd_list.length == 1) {
shell.Run("emulator -cpu-delay 0 -no-boot-anim -cache %Temp%\cache -avd "+avd_list[0]);
}
// user has more than one avd so we ask them to choose
if(avd_list.length > 1) {
while(!avd_list[avd_id]) {
WScript.Echo("Choose from one of the following Android Virtual Devices [0 to "+(avd_list.length - 1)+"]:")
for(i = 0, j = avd_list.length ; i < j ; i++) {
WScript.Echo((i)+") "+avd_list[i]);
}
WScript.StdOut.Write("> ");
avd_id = new Number(WScript.StdIn.ReadLine());
}
shell.Run("emulator -cpu-delay 0 -no-boot-anim -cache %Temp%\\cache -avd "+avd_list[avd_id], 0, false);
}
}
function clean() {
exec("%comspec% /c ant.bat clean -f "+ROOT+"\\build.xml 2>&1");
}
function debug() {
exec("%comspec% /c ant.bat debug -f "+ROOT+"\\build.xml 2>&1");
}
function debug_install() {
exec("%comspec% /c ant.bat debug install -f "+ROOT+"\\build.xml 2>&1");
}
function log() {
WScript.Echo(exec("%comspec% /c adb.bat logcat"));
}
function launch() {
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() {
clean();
if(emulator_running()) {
debug_install();
launch();
} else {
debug();
WScript.Echo("##################################################################");
WScript.Echo("# Plug in your device or launch an emulator with cordova/emulate #");
WScript.Echo("##################################################################");
}
}
var args = WScript.Arguments;
if(args.count() != 1) {
WScript.StdErr.Write("An error has occured!\n");
WScript.Quit(1);
}
eval(args(0)+"()");

View File

@@ -1,7 +0,0 @@
#!/bin/bash
set -e
CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd )
bash $CORDOVA_PATH/cordova debug

View File

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

View File

@@ -1,7 +0,0 @@
#!/bin/bash
set -e
CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd )
bash $CORDOVA_PATH/cordova emulate

View File

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

View File

@@ -1,7 +0,0 @@
#!/bin/bash
set -e
PROJECT_PATH=$( cd "$( dirname "$0" )/.." && pwd )
bash $PROJECT_PATH/cordova/cordova log

View File

@@ -0,0 +1 @@
ok...

View File

@@ -0,0 +1,3 @@
this is local config for cordova stuff to be eventually moved to
config.xml ...we think. feedback to @davejohnson/@brianleroux
appreciated here!

View File

@@ -0,0 +1,58 @@
#! /bin/sh
# 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
# ./create [path package activity]
#
# load up the config
. ./.cordova/config
PACKAGE_AS_PATH=$(echo $PACKAGE | sed 's/\./\//g')
ACTIVITY_PATH=./src/$PACKAGE_AS_PATH/$ACTIVITY.java
MANIFEST_PATH=./AndroidManifest.xml
# create the project
android create project --target $TARGET --path . --package $PACKAGE --activity $ACTIVITY
# copy all the cordova scripts etc in there
cp -R ./cordova/templates/project/* .
# copy in cordova.js
cp ./.cordova/android/cordova-$VERSION.js ./assets/www
# copy in cordova.jar
cp ./.cordova/android/cordova-$VERSION.jar ./libs
# copy in res/xml
mkdir ./res/xml
cp ./.cordova/android/cordova.xml ./res/xml
cp ./.cordova/android/plugins.xml ./res/xml
# copy in default activity
cat ./cordova/templates/Activity.java > $ACTIVITY_PATH
# interpolate the acivity name and package
find "$ACTIVITY_PATH" | xargs grep '__ACTIVITY__' -sl | xargs -L1 sed -i -e "s/__ACTIVITY__/${ACTIVITY}/g"
find "$ACTIVITY_PATH" | xargs grep '__ID__' -sl | xargs -L1 sed -i -e "s/__ID__/${PACKAGE}/g"
find "$MANIFEST_PATH" | xargs grep '__ACTIVITY__' -sl | xargs -L1 sed -i -e "s/__ACTIVITY__/${ACTIVITY}/g"
find "$MANIFEST_PATH" | xargs grep '__PACKAGE__' -sl | xargs -L1 sed -i -e "s/__PACKAGE__/${PACKAGE}/g"

View File

@@ -0,0 +1,2 @@
echo "BALLS"
cscript cordova\create.js

69
bin/templates/project/cordova/create.js vendored Normal file
View File

@@ -0,0 +1,69 @@
var shell=WScript.CreateObject("WScript.Shell");
function exec(s, output) {
WScript.Echo('Executing ' + s);
var o=shell.Exec(s);
while (o.Status == 0) {
WScript.Sleep(100);
}
WScript.Echo("Command exited with code " + o.Status);
}
function read(filename) {
var fso=WScript.CreateObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile(filename, 1);
var s=f.ReadAll();
f.Close();
return s;
}
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));
}
// working dir
var PWD = WScript.ScriptFullName.split('\\cordova\\create.js').join('');
var fso=WScript.CreateObject("Scripting.FileSystemObject");
var f=fso.OpenTextFile(PWD + '\\.cordova\\config', 1);
while (!f.AtEndOfStream) {
var prop = f.ReadLine().split('=');
var line = 'var ' + prop[0] + '=' + "'" + prop[1] + "';";
eval(line); // hacky shit to load config but whatevs
}
var PACKAGE_AS_PATH=PACKAGE.replace(/\./g, '\\');
var ACTIVITY_PATH=PWD+'\\src\\'+PACKAGE_AS_PATH+'\\'+ACTIVITY+'.java';
var MANIFEST_PATH=PWD+'\\AndroidManifest.xml';
exec('android.bat create project --target ' + TARGET + ' --path ' + PWD + ' --package ' + PACKAGE + ' --activity ' + ACTIVITY);
// copy in activity and other android assets
exec('cmd /c xcopy ' + PWD + '\\cordova\\templates\\project\\* ' + PWD +' /Y /S');
// copy in cordova.js
exec('cmd /c copy ' + PWD + '\\.cordova\\android\\cordova-' + VERSION + '.js ' + PWD + '\\assets\\www /Y');
// copy in cordova.jar
exec('cmd /c copy ' + PWD + '\\.cordova\\android\\cordova-' + VERSION + '.jar ' + PWD + '\\libs /Y');
// copy in res/xml
exec('cmd /c md ' + PWD + '\\res\\xml');
exec('cmd /c copy ' + PWD + '\\.cordova\\android\\cordova.xml ' + PWD + '\\res\\xml /Y');
exec('cmd /c copy ' + PWD + '\\.cordova\\android\\plugins.xml ' + PWD + '\\res\\xml /Y');
// copy in default activity
exec('cmd /c copy ' + PWD + '\\cordova\\templates\\Activity.java ' + ACTIVITY_PATH + ' /Y');
// interpolate the activity name and package
replaceInFile(ACTIVITY_PATH, /__ACTIVITY__/, ACTIVITY);
replaceInFile(ACTIVITY_PATH, /__ID__/, PACKAGE);
replaceInFile(MANIFEST_PATH, /__ACTIVITY__/, ACTIVITY);
replaceInFile(MANIFEST_PATH, /__PACKAGE__/, PACKAGE);
WScript.Echo('Create completed successfully.');

View File

@@ -0,0 +1,27 @@
#! /bin/sh
# 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/config
# if there are no devices listed then emulate
ant clean
ant debug install
adb shell am start -n $PACKAGE/$PACKAGE.$ACTIVITY

View File

@@ -0,0 +1,31 @@
#! /bin/sh
# 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.
#
#
#Available Android Virtual Devices:
# Name: default
# Path: /Users/davejohnson/.android/avd/default.avd
# Target: Android 2.2 (API level 8)
# Skin: WVGA800
# Sdcard: 100M
# get the name of the first virtual device or use command line arg or use "default"
emulator -cpu-delay 0 -no-boot-anim -cache ./tmp/cache -avd default > /dev/null 2>&1 & # put the avd's chatty ass in the background

View File

@@ -0,0 +1,21 @@
#! /bin/sh
# 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.
#
#
adb logcat

View File

View File

@@ -23,7 +23,7 @@
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>PhoneGap</title>
<link rel="stylesheet" href="master.css" type="text/css" media="screen" title="no title">
<script type="text/javascript" charset="utf-8" src="cordova-1.9.0rc1.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-1.8.1.js"></script>
<script type="text/javascript" charset="utf-8" src="main.js"></script>
</head>

View File

Before

Width:  |  Height:  |  Size: 5.9 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

View File

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

View File

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

Before

Width:  |  Height:  |  Size: 7.5 KiB

After

Width:  |  Height:  |  Size: 7.5 KiB

View File

Before

Width:  |  Height:  |  Size: 7.5 KiB

After

Width:  |  Height:  |  Size: 7.5 KiB

44
bin/test Executable file
View File

@@ -0,0 +1,44 @@
#! /bin/sh
# 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.
#
#
set -e
VERSION=$(cat ./VERSION)
# get the latest mobile-spec
git clone git@github.com:callback/callback-test.git
# clobber test if it exists
if [ -e ./test ]
then
rm -rf ./test
fi
# generate a working proj
./bin/create ./test org.apache.cordova.test CordovaTest
# kill the default app and replace it w/ mobile-spec
rm -rf ./test/assets/www
mv ./callback-test ./test/assets/www
# copy in cordova.js since www dir was replaced above
cp ./framework/assets/www/cordova-$VERSION.js ./test/assets/www/cordova-$VERSION.js
# build it, launch it and start logging on stdout
cd ./test && ./cordova/debug && ./cordova/log

View File

@@ -16,18 +16,9 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
import org.apache.cordova.DroidGap;
import android.app.Activity;
import android.os.Bundle;
public class CordovaActivity extends DroidGap {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
}
}
exports['you are sane'] = (test) ->
test.expect 1
test.ok true, "this assertion should always pass"
test.done()

View File

@@ -16,25 +16,25 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
import android.graphics.Color;
import android.os.Bundle;
import org.apache.cordova.*;
util = require 'util'
exec = require('child_process').exec
path = require 'path'
public class backgroundcolor extends DroidGap {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
exports['default example project is generated'] = (test) ->
test.expect 1
exec './bin/create', (error, stdout, stderr) ->
test.ok true, "this assertion should pass" unless error?
test.done()
// Properties must be set before init() is called, since some are processed during init().
exports['default example project has a ./.cordova folder'] = (test) ->
test.expect 1
path.exists './example/.cordova', (exists) ->
test.ok exists, 'the cordova folder exists'
test.done()
// backgroundColor can also be set in cordova.xml, but you must use the number equivalent of the color. For example, Color.RED is
// <preference name="backgroundColor" value="-65536" />
super.setIntegerProperty("backgroundColor", Color.GREEN);
super.init();
super.loadUrl("file:///android_asset/www/backgroundcolor/index.html");
}
}
exports['default example project has a /cordova folder'] = (test) ->
test.expect 1
path.exists './example/cordova', (exists) ->
test.ok exists, 'the other cordova folder exists'
test.done()

View File

@@ -16,24 +16,3 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.test;
import android.os.Bundle;
import org.apache.cordova.*;
public class fullscreen extends DroidGap {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Properties must be set before init() is called, since some are processed during init().
// fullscreen can also be set in cordova.xml. For example,
// <preference name="fullscreen" value="true" />
super.setBooleanProperty("fullscreen", true);
super.init();
super.loadUrl("file:///android_asset/www/fullscreen/index.html");
}
}

0
bin/tests/test.coffee Normal file
View File

View File

@@ -1,135 +0,0 @@
var build_path = __dirname + '/../..',
project_path = '/tmp/example',
package_name = 'org.apache.cordova.example',
package_as_path = 'org/apache/cordova/example',
project_name = 'cordovaExample';
var path = require('path'),
fs = require('fs'),
util = require('util'),
assert = require('assert'),
spawn = require('child_process').spawn;
var version = fs.readFileSync(build_path + '/VERSION').toString().replace('\n', '');
assert(version !== undefined);
assert(version !== '');
var create_project = spawn(build_path + '/bin/create',
[project_path,
package_name,
project_name]);
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
spawn('rm', ['-rf', project_path], function(code) {
if(code != 0) {
console.log("Could not delete project directory");
}
});
});
create_project.on('exit', function(code) {
assert.equal(code, 0, 'Project did not get created');
// make sure the project was created
path.exists(project_path, function(exists) {
assert(exists, 'Project path does not exist');
});
// make sure the build directory was cleaned up
// path.exists(build_path + '/framework/libs', function(exists) {
// assert(!exists, 'libs directory did not get cleaned up');
// });
path.exists(build_path + util.format('/framework/assets/cordova-%s.js', version), function(exists) {
assert(!exists, 'javascript file did not get cleaned up');
});
path.exists(build_path + util.format('/framework/cordova-%s.jar', version), function(exists) {
assert(!exists, 'jar file did not get cleaned up');
});
// make sure AndroidManifest.xml was added
path.exists(util.format('%s/AndroidManifest.xml', project_path), function(exists) {
assert(exists, 'AndroidManifest.xml did not get created');
// TODO check that the activity name was properly substituted
});
// make sure main Activity was added
path.exists(util.format('%s/src/%s/%s.java', project_path, package_as_path, project_name), function(exists) {
assert(exists, 'Activity did not get created');
// TODO check that package name and activity name were substitued properly
});
// make sure plugins.xml was added
path.exists(util.format('%s/res/xml/plugins.xml', project_path), function(exists) {
assert(exists, 'plugins.xml did not get created');
});
// make sure cordova.xml was added
path.exists(util.format('%s/res/xml/cordova.xml', project_path), function(exists) {
assert(exists, 'plugins.xml did not get created');
});
// make sure cordova.jar was added
path.exists(util.format('%s/libs/cordova-%s.jar', project_path, version), function(exists) {
assert(exists, 'cordova.jar did not get added');
});
// make sure cordova.js was added
path.exists(util.format('%s/assets/www/cordova-%s.js', project_path, version), function(exists) {
assert(exists, 'cordova.js did not get added');
});
// make sure cordova master script was added
path.exists(util.format('%s/cordova/cordova', project_path), function(exists) {
assert(exists, 'cordova script did not get added');
});
// make sure debug script was added
path.exists(util.format('%s/cordova/debug', project_path), function(exists) {
assert(exists, 'debug script did not get added');
});
// make sure BOOM script was added
path.exists(util.format('%s/cordova/BOOM', project_path), function(exists) {
assert(exists, 'BOOM script did not get added');
});
// make sure log script was added
path.exists(util.format('%s/cordova/log', project_path), function(exists) {
assert(exists, 'log script did not get added');
});
// make sure clean script was added
path.exists(util.format('%s/cordova/clean', project_path), function(exists) {
assert(exists, 'clean script did not get added');
});
// make sure emulate script was added
path.exists(util.format('%s/cordova/emulate', project_path), function(exists) {
assert(exists, 'emulate script did not get added');
});
// make sure appinfo.jar script was added
path.exists(util.format('%s/cordova/appinfo.jar', project_path), function(exists) {
assert(exists, 'appinfo.jar script did not get added');
});
// check that project compiles && creates a cordovaExample-debug.apk
var compile_project = spawn('ant', ['debug'], {cwd: project_path});
compile_project.on('exit', function(code) {
assert.equal(code, 0, 'Cordova Android Project does not compile');
// make sure cordovaExample-debug.apk was created
path.exists(util.format('%s/bin/%s-debug.apk', project_path, project_name), function(exists) {
assert(exists, 'Package did not get created');
// if project compiles properly just AXE it
spawn('rm', ['-rf', project_path], function(code) {
assert.equal(code, 0, 'Could not remove project directory');
});
});
});
});

View File

@@ -1,143 +0,0 @@
var build_path = __dirname + '/../..'
project_path = process.env.Temp + '\\example',
package_name = 'org.apache.cordova.example',
package_as_path = 'org/apache/cordova/example',
project_name = 'cordovaExample';
var path = require('path'),
fs = require('fs'),
util = require('util'),
assert = require('assert'),
exec = require('child_process').exec,
spawn = require('child_process').spawn;
var version = fs.readFileSync(build_path + '/VERSION').toString().replace('\r\n', '');
assert(version !== undefined);
assert(version !== '');
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
exec('rd /s /q ' + project_path);
});
var create_project = spawn('cscript',
[build_path + '/bin/create.js',
project_path,
package_name,
project_name]
);
create_project.stderr.on('data', function (data) {
console.log('ps stderr: ' + data);
});
create_project.stderr.on('data', function(data) {
console.log(data.toString());
});
create_project.stdout.on('data', function(data) {
console.log(data.toString());
});
create_project.on('exit', function(code) {
assert.equal(code, 0, 'Project did not get created');
// make sure the project was created
path.exists(project_path, function(exists) {
assert(exists, 'Project path does not exist');
});
// make sure the build directory was cleaned up
// path.exists(build_path + '/framework/libs', function(exists) {
// assert(!exists, 'libs directory did not get cleaned up');
// });
path.exists(build_path + util.format('/framework/assets/cordova-%s.js', version), function(exists) {
assert(!exists, 'javascript file did not get cleaned up');
});
path.exists(build_path + util.format('/framework/cordova-%s.jar', version), function(exists) {
assert(!exists, 'jar file did not get cleaned up');
});
// make sure AndroidManifest.xml was added
path.exists(util.format('%s/AndroidManifest.xml', project_path), function(exists) {
assert(exists, 'AndroidManifest.xml did not get created');
// TODO check that the activity name was properly substituted
});
// make sure main Activity was added
path.exists(util.format('%s/src/%s/%s.java', project_path, package_as_path, project_name), function(exists) {
assert(exists, 'Activity did not get created');
// TODO check that package name and activity name were substitued properly
});
// make sure plugins.xml was added
path.exists(util.format('%s/res/xml/plugins.xml', project_path), function(exists) {
assert(exists, 'plugins.xml did not get created');
});
// make sure cordova.xml was added
path.exists(util.format('%s/res/xml/cordova.xml', project_path), function(exists) {
assert(exists, 'plugins.xml did not get created');
});
// make sure cordova.jar was added
path.exists(util.format('%s/libs/cordova-%s.jar', project_path, version), function(exists) {
assert(exists, 'cordova.jar did not get added');
});
// make sure cordova.js was added
path.exists(util.format('%s/assets/www/cordova-%s.js', project_path, version), function(exists) {
assert(exists, 'cordova.js did not get added');
});
// make sure cordova master script was added
path.exists(util.format('%s/cordova/cordova.bat', project_path), function(exists) {
assert(exists, 'cordova script did not get added');
});
// make sure debug script was added
path.exists(util.format('%s/cordova/debug.bat', project_path), function(exists) {
assert(exists, 'debug script did not get added');
});
// make sure BOOM script was added
path.exists(util.format('%s/cordova/BOOM.bat', project_path), function(exists) {
assert(exists, 'BOOM script did not get added');
});
// make sure log script was added
path.exists(util.format('%s/cordova/log.bat', project_path), function(exists) {
assert(exists, 'log script did not get added');
});
// make sure clean script was added
path.exists(util.format('%s/cordova/clean.bat', project_path), function(exists) {
assert(exists, 'clean script did not get added');
});
// make sure emulate script was added
path.exists(util.format('%s/cordova/emulate.bat', project_path), function(exists) {
assert(exists, 'emulate script did not get added');
});
// make sure appinfo.jar script was added
path.exists(util.format('%s/cordova/appinfo.jar', project_path), function(exists) {
assert(exists, 'appinfo.jar script did not get added');
});
// check that project compiles && creates a cordovaExample-debug.apk
// XXX: !@##!@# WINDOWS
exec('ant debug -f ' + project_path + "\\build.xml", function(error, stdout, stderr) {
assert(error == null, "Cordova Android Project does not compile");
path.exists(util.format('%s/bin/%s-debug.apk', project_path, project_name),
function(exists) {
assert(exists, 'Package did not get created');
// if project compiles properly just AXE it
exec('rd /s /q ' + project_path);
});
});
});

View File

@@ -1,6 +1,6 @@
// commit 25033fceac7c800623f1f16881b784d19eba69cc
// commit 722ce5820b6fc3e371245927e00c7f9745eb041a
// File generated at :: Thu Jun 21 2012 10:45:32 GMT-0700 (PDT)
// File generated at :: Tue Jun 12 2012 11:04:57 GMT-0700 (PDT)
/*
Licensed to the Apache Software Foundation (ASF) under one
@@ -190,9 +190,7 @@ var cordova = {
fireDocumentEvent: function(type, data) {
var evt = createEvent(type, data);
if (typeof documentEventHandlers[type] != 'undefined') {
setTimeout(function() {
documentEventHandlers[type].fire(evt);
}, 0);
documentEventHandlers[type].fire(evt);
} else {
document.dispatchEvent(evt);
}
@@ -200,9 +198,7 @@ var cordova = {
fireWindowEvent: function(type, data) {
var evt = createEvent(type,data);
if (typeof windowEventHandlers[type] != 'undefined') {
setTimeout(function() {
windowEventHandlers[type].fire(evt);
}, 0);
windowEventHandlers[type].fire(evt);
} else {
window.dispatchEvent(evt);
}
@@ -957,7 +953,8 @@ module.exports = function(success, fail, service, action, args) {
// If a result was returned
if (r.length > 0) {
var v = JSON.parse(r);
var v;
eval("v="+r+";");
// If status is OK, then return value back to caller
if (v.status === cordova.callbackStatus.OK) {
@@ -1289,7 +1286,7 @@ cameraExport.getPicture = function(successCallback, errorCallback, options) {
cameraExport.cleanup = function(successCallback, errorCallback) {
exec(successCallback, errorCallback, "Camera", "cleanup", []);
};
}
module.exports = cameraExport;
});
@@ -2609,8 +2606,7 @@ module.exports = FileSystem;
// file: lib/common/plugin/FileTransfer.js
define("cordova/plugin/FileTransfer", function(require, exports, module) {
var exec = require('cordova/exec'),
FileTransferError = require('cordova/plugin/FileTransferError');
var exec = require('cordova/exec');
/**
* FileTransfer uploads a file to a remote server.
@@ -2629,8 +2625,6 @@ var FileTransfer = function() {};
* @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
*/
FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, trustAllHosts) {
// sanity parameter checking
if (!filePath || !server) throw new Error("FileTransfer.upload requires filePath and server URL parameters at the minimum.");
// check for options
var fileKey = null;
var fileName = null;
@@ -2652,12 +2646,7 @@ FileTransfer.prototype.upload = function(filePath, server, successCallback, erro
}
}
var fail = function(e) {
var error = new FileTransferError(e.code, e.source, e.target, e.http_status);
errorCallback(error);
};
exec(successCallback, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode]);
exec(successCallback, errorCallback, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode]);
};
/**
@@ -2668,8 +2657,6 @@ FileTransfer.prototype.upload = function(filePath, server, successCallback, erro
* @param errorCallback {Function} Callback to be invoked upon error
*/
FileTransfer.prototype.download = function(source, target, successCallback, errorCallback) {
// sanity parameter checking
if (!source || !target) throw new Error("FileTransfer.download requires source URI and target URI parameters at the minimum.");
var win = function(result) {
var entry = null;
if (result.isDirectory) {
@@ -2684,12 +2671,6 @@ FileTransfer.prototype.download = function(source, target, successCallback, erro
entry.fullPath = result.fullPath;
successCallback(entry);
};
var fail = function(e) {
var error = new FileTransferError(e.code, e.source, e.target, e.http_status);
errorCallback(error);
};
exec(win, errorCallback, 'FileTransfer', 'download', [source, target]);
};
@@ -2703,11 +2684,8 @@ define("cordova/plugin/FileTransferError", function(require, exports, module) {
* FileTransferError
* @constructor
*/
var FileTransferError = function(code, source, target, status) {
var FileTransferError = function(code) {
this.code = code || null;
this.source = source || null;
this.target = target || null;
this.http_status = status || null;
};
FileTransferError.FILE_NOT_FOUND_ERR = 1;
@@ -2715,7 +2693,6 @@ FileTransferError.INVALID_URL_ERR = 2;
FileTransferError.CONNECTION_ERR = 3;
module.exports = FileTransferError;
});
// file: lib/common/plugin/FileUploadOptions.js
@@ -5495,9 +5472,6 @@ define("cordova/plugin/splashscreen", function(require, exports, module) {
var exec = require('cordova/exec');
var splashscreen = {
show:function() {
exec(null, null, "SplashScreen", "show", []);
},
hide:function() {
exec(null, null, "SplashScreen", "hide", []);
}

View File

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

View File

@@ -122,7 +122,7 @@
<!-- update project files to reference cordova-x.x.x.min.js -->
<replaceregexp match="cordova(.*)\.js" replace="cordova-${version}.js" byline="true">
<fileset file="assets/www/index.html" />
<fileset file="../bin/templates/project/assets/www/index.html" />
<fileset file="../bin/templates/project/cordova/templates/project/assets/www/index.html" />
</replaceregexp>
<!-- This is sketchy, but it works, ${dblQuote} does not -->

View File

@@ -30,7 +30,7 @@
<!-- <access origin=".*"/> Allow all domains, suggested development use only -->
<log level="DEBUG"/>
<preference name="useBrowserHistory" value="false" />
<preference name="classicRender" value="true" />
</cordova>

View File

@@ -18,7 +18,6 @@
*/
package com.phonegap.api;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.api.CordovaInterface;
import android.webkit.WebView;
@@ -31,7 +30,7 @@ import android.webkit.WebView;
*/
public class PluginManager extends org.apache.cordova.api.PluginManager {
public PluginManager(WebView app, CordovaInterface ctx) throws Exception {
super((CordovaWebView) app, ctx);
public PluginManager(WebView app, CordovaInterface ctx) {
super(app, ctx);
}
}

View File

@@ -26,6 +26,7 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
@@ -42,14 +43,14 @@ public class AccelListener extends Plugin implements SensorEventListener {
public static int STARTING = 1;
public static int RUNNING = 2;
public static int ERROR_FAILED_TO_START = 3;
private float x,y,z; // most recent acceleration values
private long timestamp; // time of most recent value
private int status; // status of listener
private float x,y,z; // most recent acceleration values
private long timestamp; // time of most recent value
private int status; // status of listener
private int accuracy = SensorManager.SENSOR_STATUS_UNRELIABLE;
private SensorManager sensorManager; // Sensor manager
private Sensor mSensor; // Acceleration sensor returned by sensor manager
private Sensor mSensor; // Acceleration sensor returned by sensor manager
private String callbackId; // Keeps track of the single "start" callback ID passed in from JS
@@ -68,21 +69,20 @@ public class AccelListener extends Plugin implements SensorEventListener {
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param ctx The context of the main Activity.
*/
public void setContext(CordovaInterface cordova) {
super.setContext(cordova);
this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE);
public void setContext(CordovaInterface ctx) {
super.setContext(ctx);
this.sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
}
/**
* 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 callbackId The callback id used when calling back into JavaScript.
* @return A PluginResult object with a status and message.
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.NO_RESULT;
@@ -123,9 +123,9 @@ public class AccelListener extends Plugin implements SensorEventListener {
//
/**
* Start listening for acceleration sensor.
*
* @return status of listener
*/
*
* @return status of listener
*/
private int start() {
// If already starting or running, then just return
if ((this.status == AccelListener.RUNNING) || (this.status == AccelListener.STARTING)) {
@@ -139,24 +139,24 @@ public class AccelListener extends Plugin implements SensorEventListener {
// If found, then register as listener
if ((list != null) && (list.size() > 0)) {
this.mSensor = list.get(0);
this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_UI);
this.setStatus(AccelListener.STARTING);
this.mSensor = list.get(0);
this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_UI);
this.setStatus(AccelListener.STARTING);
} else {
this.setStatus(AccelListener.ERROR_FAILED_TO_START);
this.fail(AccelListener.ERROR_FAILED_TO_START, "No sensors found to register accelerometer listening to.");
return this.status;
this.setStatus(AccelListener.ERROR_FAILED_TO_START);
this.fail(AccelListener.ERROR_FAILED_TO_START, "No sensors found to register accelerometer listening to.");
return this.status;
}
// Wait until running
long timeout = 2000;
while ((this.status == STARTING) && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (timeout == 0) {
this.setStatus(AccelListener.ERROR_FAILED_TO_START);
@@ -210,6 +210,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
if (this.status == AccelListener.STOPPED) {
return;
}
this.setStatus(AccelListener.RUNNING);
if (this.accuracy >= SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM) {
@@ -251,6 +252,7 @@ public class AccelListener extends Plugin implements SensorEventListener {
private void setStatus(int status) {
this.status = status;
}
private JSONObject getAccelerationJSON() {
JSONObject r = new JSONObject();
try {

View File

@@ -48,13 +48,6 @@ public class App extends Plugin {
if (action.equals("clearCache")) {
this.clearCache();
}
else if (action.equals("show")) { // TODO @bc - Not in master branch. When should this be called?
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
webView.postMessage("spinner", "stop");
}
});
}
else if (action.equals("loadUrl")) {
this.loadUrl(args.getString(0), args.optJSONObject(1));
}
@@ -67,12 +60,13 @@ public class App extends Plugin {
else if (action.equals("backHistory")) {
this.backHistory();
}
else if (action.equals("overrideButton")) {
this.overrideButton(args.getString(0), args.getBoolean(1));
}
else if (action.equals("overrideBackbutton")) {
this.overrideBackbutton(args.getBoolean(0));
}
else if (action.equals("isBackbuttonOverridden")) {
boolean b = this.isBackbuttonOverridden();
return new PluginResult(status, b);
}
else if (action.equals("exitApp")) {
this.exitApp();
}
@@ -90,7 +84,7 @@ public class App extends Plugin {
* Clear the resource cache.
*/
public void clearCache() {
this.webView.clearCache(true);
((DroidGap)this.ctx).clearCache();
}
/**
@@ -110,7 +104,7 @@ public class App extends Plugin {
HashMap<String, Object> params = new HashMap<String, Object>();
if (props != null) {
JSONArray keys = props.names();
for (int i = 0; i < keys.length(); i++) {
for (int i=0; i<keys.length(); i++) {
String key = keys.getString(i);
if (key.equals("wait")) {
wait = props.getInt(key);
@@ -150,22 +144,21 @@ public class App extends Plugin {
e.printStackTrace();
}
}
this.webView.showWebPage(url, openExternal, clearHistory, params);
((DroidGap)this.ctx).showWebPage(url, openExternal, clearHistory, params);
}
/**
* Cancel loadUrl before it has been loaded (Only works on a CordovaInterface class)
* Cancel loadUrl before it has been loaded.
*/
@Deprecated
public void cancelLoadUrl() {
this.cordova.cancelLoadUrl();
((DroidGap)this.ctx).cancelLoadUrl();
}
/**
* Clear page history for the app.
*/
public void clearHistory() {
this.webView.clearHistory();
((DroidGap)this.ctx).clearHistory();
}
/**
@@ -173,7 +166,7 @@ public class App extends Plugin {
* This is the same as pressing the backbutton on Android device.
*/
public void backHistory() {
this.webView.backHistory();
((DroidGap)this.ctx).backHistory();
}
/**
@@ -183,27 +176,23 @@ public class App extends Plugin {
* @param override T=override, F=cancel override
*/
public void overrideBackbutton(boolean override) {
LOG.i("App", "WARNING: Back Button Default Behaviour will be overridden. The backbutton event will be fired!");
webView.bindButton(override);
LOG.i("DroidGap", "WARNING: Back Button Default Behaviour will be overridden. The backbutton event will be fired!");
((DroidGap)this.ctx).bound = override;
}
/**
* Override the default behavior of the Android volume buttons.
* If overridden, when the volume button is pressed, the "volume[up|down]button" JavaScript event will be fired.
* Return whether the Android back button is overridden by the user.
*
* @param button volumeup, volumedown
* @param override T=override, F=cancel override
* @return boolean
*/
public void overrideButton(String button, boolean override) {
LOG.i("DroidGap", "WARNING: Volume Button Default Behaviour will be overridden. The volume event will be fired!");
webView.bindButton(button, override);
public boolean isBackbuttonOverridden() {
return ((DroidGap)this.ctx).bound;
}
/**
* Exit the Android application.
*/
public void exitApp() {
this.webView.postMessage("exit", null);
((DroidGap)this.ctx).endActivity();
}
}

View File

@@ -26,6 +26,7 @@ import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.HashMap;
/**
@@ -42,19 +43,20 @@ import java.util.HashMap;
public class AudioHandler extends Plugin {
public static String TAG = "AudioHandler";
HashMap<String, AudioPlayer> players; // Audio player object
HashMap<String,AudioPlayer> players; // Audio player object
ArrayList<AudioPlayer> pausedForPhone; // Audio players that were paused when phone call came in
/**
* Constructor.
*/
public AudioHandler() {
this.players = new HashMap<String, AudioPlayer>();
this.players = new HashMap<String,AudioPlayer>();
this.pausedForPhone = new ArrayList<AudioPlayer>();
}
/**
* 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.
@@ -109,6 +111,7 @@ public class AudioHandler extends Plugin {
/**
* Identifies if action to be executed returns a value and should be run synchronously.
*
* @param action The action to execute
* @return T=returns value
*/
@@ -137,9 +140,8 @@ public class AudioHandler extends Plugin {
*
* @param id The message id
* @param data The message data
* @return Object to stop propagation or null
*/
public Object onMessage(String id, Object data) {
public void onMessage(String id, Object data) {
// If phone message
if (id.equals("telephone")) {
@@ -165,7 +167,6 @@ public class AudioHandler extends Plugin {
this.pausedForPhone.clear();
}
}
return null;
}
//--------------------------------------------------------------------------
@@ -174,6 +175,7 @@ public class AudioHandler extends Plugin {
/**
* Release the audio player instance to save memory.
*
* @param id The id of the audio player
*/
private boolean release(String id) {
@@ -188,6 +190,7 @@ public class AudioHandler extends Plugin {
/**
* Start recording and save the specified file.
*
* @param id The id of the audio player
* @param file The name of the file
*/
@@ -203,6 +206,7 @@ public class AudioHandler extends Plugin {
/**
* Stop recording and save to the file specified when recording started.
*
* @param id The id of the audio player
*/
public void stopRecordingAudio(String id) {
@@ -215,6 +219,7 @@ public class AudioHandler extends Plugin {
/**
* Start or resume playing audio file.
*
* @param id The id of the audio player
* @param file The name of the audio file.
*/
@@ -229,6 +234,8 @@ public class AudioHandler extends Plugin {
/**
* Seek to a location.
*
*
* @param id The id of the audio player
* @param miliseconds int: number of milliseconds to skip 1000 = 1 second
*/
@@ -241,6 +248,7 @@ public class AudioHandler extends Plugin {
/**
* Pause playing.
*
* @param id The id of the audio player
*/
public void pausePlayingAudio(String id) {
@@ -252,6 +260,7 @@ public class AudioHandler extends Plugin {
/**
* Stop playing the audio file.
*
* @param id The id of the audio player
*/
public void stopPlayingAudio(String id) {
@@ -265,19 +274,21 @@ public class AudioHandler extends Plugin {
/**
* Get current position of playback.
*
* @param id The id of the audio player
* @return position in msec
*/
public float getCurrentPositionAudio(String id) {
AudioPlayer audio = this.players.get(id);
if (audio != null) {
return (audio.getCurrentPosition() / 1000.0f);
return(audio.getCurrentPosition()/1000.0f);
}
return -1;
}
/**
* Get the duration of the audio file.
*
* @param id The id of the audio player
* @param file The name of the audio file.
* @return The duration in msec.
@@ -287,14 +298,14 @@ public class AudioHandler extends Plugin {
// Get audio file
AudioPlayer audio = this.players.get(id);
if (audio != null) {
return (audio.getDuration(file));
return(audio.getDuration(file));
}
// If not already open, then open the file
else {
audio = new AudioPlayer(this, id);
this.players.put(id, audio);
return (audio.getDuration(file));
return(audio.getDuration(file));
}
}
@@ -303,9 +314,8 @@ public class AudioHandler extends Plugin {
*
* @param output 1=earpiece, 2=speaker
*/
@SuppressWarnings("deprecation")
public void setAudioOutputDevice(int output) {
AudioManager audiMgr = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);
AudioManager audiMgr = (AudioManager) this.ctx.getSystemService(Context.AUDIO_SERVICE);
if (output == 2) {
audiMgr.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_SPEAKER, AudioManager.ROUTE_ALL);
}
@@ -322,9 +332,8 @@ public class AudioHandler extends Plugin {
*
* @return 1=earpiece, 2=speaker
*/
@SuppressWarnings("deprecation")
public int getAudioOutputDevice() {
AudioManager audiMgr = (AudioManager) this.cordova.getActivity().getSystemService(Context.AUDIO_SERVICE);
AudioManager audiMgr = (AudioManager) this.ctx.getSystemService(Context.AUDIO_SERVICE);
if (audiMgr.getRouting(AudioManager.MODE_NORMAL) == AudioManager.ROUTE_EARPIECE) {
return 1;
}

View File

@@ -37,8 +37,8 @@ import java.io.IOException;
* Only one file can be played or recorded per class instance.
*
* Local audio files must reside in one of two places:
* android_asset: file name must start with /android_asset/sound.mp3
* sdcard: file name is just sound.mp3
* android_asset: file name must start with /android_asset/sound.mp3
* sdcard: file name is just sound.mp3
*/
public class AudioPlayer implements OnCompletionListener, OnPreparedListener, OnErrorListener {
@@ -63,24 +63,24 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
private static int MEDIA_ERR_NETWORK = 2;
private static int MEDIA_ERR_DECODE = 3;
private static int MEDIA_ERR_NONE_SUPPORTED = 4;
private AudioHandler handler; // The AudioHandler object
private String id; // The id of this player (used to identify Media object in JavaScript)
private int state = MEDIA_NONE; // State of recording or playback
private String audioFile = null; // File name to play or record to
private float duration = -1; // Duration of audio
private MediaRecorder recorder = null; // Audio recording object
private String tempFile = null; // Temporary recording file name
private MediaPlayer mPlayer = null; // Audio player object
private boolean prepareOnly = false;
private AudioHandler handler; // The AudioHandler object
private String id; // The id of this player (used to identify Media object in JavaScript)
private int state = MEDIA_NONE; // State of recording or playback
private String audioFile = null; // File name to play or record to
private float duration = -1; // Duration of audio
private MediaRecorder recorder = null; // Audio recording object
private String tempFile = null; // Temporary recording file name
private MediaPlayer mPlayer = null; // Audio player object
private boolean prepareOnly = false;
/**
* Constructor.
*
* @param handler The audio handler object
* @param id The id of this audio player
*
* @param handler The audio handler object
* @param id The id of this audio player
*/
public AudioPlayer(AudioHandler handler, String id) {
this.handler = handler;
@@ -88,7 +88,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
this.tempFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmprecording.mp3";
} else {
this.tempFile = "/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/tmprecording.mp3";
this.tempFile = "/data/data/" + handler.ctx.getPackageName() + "/cache/tmprecording.mp3";
}
}
@@ -96,6 +96,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
* Destroy player and stop audio playing or recording.
*/
public void destroy() {
// Stop any play or record
if (this.mPlayer != null) {
if ((this.state == MEDIA_RUNNING) || (this.state == MEDIA_PAUSED)) {
@@ -114,14 +115,15 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
/**
* Start recording the specified file.
*
* @param file The name of the file
*
* @param file The name of the file
*/
public void startRecording(String file) {
if (this.mPlayer != null) {
Log.d(LOG_TAG, "AudioPlayer Error: Can't record in play mode.");
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
}
// Make sure we're not already recording
else if (this.recorder == null) {
this.audioFile = file;
@@ -160,7 +162,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
f.renameTo(new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + file));
} else {
f.renameTo(new File("/data/data/" + handler.cordova.getActivity().getPackageName() + "/cache/" + file));
f.renameTo(new File("/data/data/" + handler.ctx.getPackageName() + "/cache/" + file));
}
}
@@ -185,13 +187,13 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
/**
* Start or resume playing audio file.
*
* @param file The name of the audio file.
*
* @param file The name of the audio file.
*/
public void startPlaying(String file) {
if (this.recorder != null) {
Log.d(LOG_TAG, "AudioPlayer Error: Can't play in record mode.");
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});");
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
}
// If this is a new request to play audio, or stopped
@@ -220,7 +222,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
else {
if (file.startsWith("/android_asset/")) {
String f = file.substring(15);
android.content.res.AssetFileDescriptor fd = this.handler.cordova.getActivity().getAssets().openFd(f);
android.content.res.AssetFileDescriptor fd = this.handler.ctx.getBaseContext().getAssets().openFd(f);
this.mPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
}
else {
@@ -240,9 +242,10 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
// Get duration
this.duration = getDurationInSeconds();
}
} catch (Exception e) {
}
catch (Exception e) {
e.printStackTrace();
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});");
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
}
}
@@ -255,8 +258,8 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
this.setState(MEDIA_RUNNING);
}
else {
Log.d(LOG_TAG, "AudioPlayer Error: startPlaying() called during invalid state: " + this.state);
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_ABORTED + "});");
Log.d(LOG_TAG, "AudioPlayer Error: startPlaying() called during invalid state: "+this.state);
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_ABORTED+"});");
}
}
}
@@ -268,7 +271,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
if (this.mPlayer != null) {
this.mPlayer.seekTo(milliseconds);
Log.d(LOG_TAG, "Send a onStatus update for the new seek");
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_POSITION + ", " + milliseconds / 1000.0f + ");");
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_POSITION+", "+milliseconds/1000.0f+");");
}
}
@@ -283,8 +286,8 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
this.setState(MEDIA_PAUSED);
}
else {
Log.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: " + this.state);
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_NONE_ACTIVE + "});");
Log.d(LOG_TAG, "AudioPlayer Error: pausePlaying() called during invalid state: "+this.state);
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_NONE_ACTIVE+"});");
}
}
@@ -297,15 +300,15 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
this.setState(MEDIA_STOPPED);
}
else {
Log.d(LOG_TAG, "AudioPlayer Error: stopPlaying() called during invalid state: " + this.state);
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_ERROR + ", { \"code\":" + MEDIA_ERR_NONE_ACTIVE + "});");
Log.d(LOG_TAG, "AudioPlayer Error: stopPlaying() called during invalid state: "+this.state);
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_ERROR+", { \"code\":"+MEDIA_ERR_NONE_ACTIVE+"});");
}
}
/**
* Callback to be invoked when playback of a media source has completed.
*
* @param mPlayer The MediaPlayer that reached the end of the file
*
* @param mPlayer The MediaPlayer that reached the end of the file
*/
public void onCompletion(MediaPlayer mPlayer) {
this.setState(MEDIA_STOPPED);
@@ -313,13 +316,13 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
/**
* Get current position of playback.
*
* @return position in msec or -1 if not playing
*
* @return position in msec or -1 if not playing
*/
public long getCurrentPosition() {
if ((this.state == MEDIA_RUNNING) || (this.state == MEDIA_PAUSED)) {
int curPos = this.mPlayer.getCurrentPosition();
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_POSITION + ", " + curPos / 1000.0f + ");");
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_POSITION+", "+curPos/1000.0f+");");
return curPos;
}
else {
@@ -330,9 +333,9 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
/**
* Determine if playback file is streaming or local.
* It is streaming if file name starts with "http://"
*
* @param file The file name
* @return T=streaming, F=local
*
* @param file The file name
* @return T=streaming, F=local
*/
public boolean isStreaming(String file) {
if (file.contains("http://") || file.contains("https://")) {
@@ -343,19 +346,19 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
}
}
/**
* Get the duration of the audio file.
*
* @param file The name of the audio file.
* @return The duration in msec.
* -1=can't be determined
* -2=not allowed
*/
/**
* Get the duration of the audio file.
*
* @param file The name of the audio file.
* @return The duration in msec.
* -1=can't be determined
* -2=not allowed
*/
public float getDuration(String file) {
// Can't get duration of recording
if (this.recorder != null) {
return (-2); // not allowed
return(-2); // not allowed
}
// If audio file already loaded and started, then return duration
@@ -375,9 +378,9 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
}
/**
* Callback to be invoked when the media source is ready for playback.
*
* @param mPlayer The MediaPlayer that is ready for playback
* Callback to be invoked when the media source is ready for playback.
*
* @param mPlayer The MediaPlayer that is ready for playback
*/
public void onPrepared(MediaPlayer mPlayer) {
// Listen for playback completion
@@ -398,13 +401,13 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
this.prepareOnly = false;
// Send status notification to JavaScript
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_DURATION + "," + this.duration + ");");
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_DURATION+","+this.duration+");");
}
/**
* By default Android returns the length of audio in mills but we want seconds
*
*
* @return length of clip in seconds
*/
private float getDurationInSeconds() {
@@ -414,31 +417,31 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
/**
* Callback to be invoked when there has been an error during an asynchronous operation
* (other errors will throw exceptions at method call time).
*
* @param mPlayer the MediaPlayer the error pertains to
* @param arg1 the type of error that has occurred: (MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_SERVER_DIED)
* @param arg2 an extra code, specific to the error.
*
* @param mPlayer the MediaPlayer the error pertains to
* @param arg1 the type of error that has occurred: (MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_SERVER_DIED)
* @param arg2 an extra code, specific to the error.
*/
public boolean onError(MediaPlayer mPlayer, int arg1, int arg2) {
Log.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2 + ")");
Log.d(LOG_TAG, "AudioPlayer.onError(" + arg1 + ", " + arg2+")");
// TODO: Not sure if this needs to be sent?
this.mPlayer.stop();
this.mPlayer.release();
// Send error notification to JavaScript
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', { \"code\":" + arg1 + "});");
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', { \"code\":"+arg1+"});");
return false;
}
/**
* Set the state and send it to JavaScript.
*
*
* @param state
*/
private void setState(int state) {
if (this.state != state) {
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', " + MEDIA_STATE + ", " + state + ");");
this.handler.sendJavascript("cordova.require('cordova/plugin/Media').onStatus('" + this.id + "', "+MEDIA_STATE+", "+state+");");
}
this.state = state;
@@ -446,7 +449,7 @@ public class AudioPlayer implements OnCompletionListener, OnPreparedListener, On
/**
* Get the audio state.
*
*
* @return int
*/
public int getState() {

View File

@@ -24,6 +24,7 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -64,7 +65,7 @@ public class BatteryListener extends Plugin {
this.batteryCallbackId = callbackId;
// We need to listen to power events to update battery status
IntentFilter intentFilter = new IntentFilter();
IntentFilter intentFilter = new IntentFilter() ;
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
if (this.receiver == null) {
this.receiver = new BroadcastReceiver() {
@@ -73,7 +74,7 @@ public class BatteryListener extends Plugin {
updateBatteryInfo(intent);
}
};
cordova.getActivity().registerReceiver(this.receiver, intentFilter);
ctx.registerReceiver(this.receiver, intentFilter);
}
// Don't return any result now, since status results will be sent when events come in from broadcast receiver
@@ -105,7 +106,7 @@ public class BatteryListener extends Plugin {
private void removeBatteryListener() {
if (this.receiver != null) {
try {
this.cordova.getActivity().unregisterReceiver(this.receiver);
this.ctx.unregisterReceiver(this.receiver);
this.receiver = null;
} catch (Exception e) {
Log.e(LOG_TAG, "Error unregistering battery receiver: " + e.getMessage(), e);

View File

@@ -53,7 +53,6 @@ import java.util.LinkedList;
*/
public class CallbackServer implements Runnable {
@SuppressWarnings("unused")
private static final String LOG_TAG = "CallbackServer";
/**
@@ -95,7 +94,7 @@ public class CallbackServer implements Runnable {
* Constructor.
*/
public CallbackServer() {
//Log.d(LOG_TAG, "CallbackServer()");
//System.out.println("CallbackServer()");
this.active = false;
this.empty = true;
this.port = 0;
@@ -104,7 +103,7 @@ public class CallbackServer implements Runnable {
/**
* Init callback server and start XHR if running local app.
*
*
* If Cordova app is loaded from file://, then we can use XHR
* otherwise we have to use polling due to cross-domain security restrictions.
*
@@ -144,6 +143,7 @@ public class CallbackServer implements Runnable {
/**
* Return if polling is being used instead of XHR.
*
* @return
*/
public boolean usePolling() {
@@ -152,6 +152,7 @@ public class CallbackServer implements Runnable {
/**
* Get the port that this server is running on.
*
* @return
*/
public int getPort() {
@@ -160,6 +161,7 @@ public class CallbackServer implements Runnable {
/**
* Get the security token that this server requires when calling getJavascript().
*
* @return
*/
public String getToken() {
@@ -170,7 +172,7 @@ public class CallbackServer implements Runnable {
* Start the server on a new thread.
*/
public void startServer() {
//Log.d(LOG_TAG, "CallbackServer.startServer()");
//System.out.println("CallbackServer.startServer()");
this.active = false;
// Start server on new thread
@@ -191,7 +193,7 @@ public class CallbackServer implements Runnable {
}
/**
* Start running the server.
* Start running the server.
* This is called automatically when the server thread is started.
*/
public void run() {
@@ -202,90 +204,90 @@ public class CallbackServer implements Runnable {
String request;
ServerSocket waitSocket = new ServerSocket(0);
this.port = waitSocket.getLocalPort();
//Log.d(LOG_TAG, "CallbackServer -- using port " +this.port);
//System.out.println("CallbackServer -- using port " +this.port);
this.token = java.util.UUID.randomUUID().toString();
//Log.d(LOG_TAG, "CallbackServer -- using token "+this.token);
//System.out.println("CallbackServer -- using token "+this.token);
while (this.active) {
//Log.d(LOG_TAG, "CallbackServer: Waiting for data on socket");
Socket connection = waitSocket.accept();
BufferedReader xhrReader = new BufferedReader(new InputStreamReader(connection.getInputStream()), 40);
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
request = xhrReader.readLine();
String response = "";
//Log.d(LOG_TAG, "CallbackServerRequest="+request);
if (this.active && (request != null)) {
if (request.contains("GET")) {
while (this.active) {
//System.out.println("CallbackServer: Waiting for data on socket");
Socket connection = waitSocket.accept();
BufferedReader xhrReader = new BufferedReader(new InputStreamReader(connection.getInputStream()),40);
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
request = xhrReader.readLine();
String response = "";
//System.out.println("CallbackServerRequest="+request);
if (this.active && (request != null)) {
if (request.contains("GET")) {
// Get requested file
String[] requestParts = request.split(" ");
// Get requested file
String[] requestParts = request.split(" ");
// Must have security token
if ((requestParts.length == 3) && (requestParts[1].substring(1).equals(this.token))) {
//Log.d(LOG_TAG, "CallbackServer -- Processing GET request");
// Must have security token
if ((requestParts.length == 3) && (requestParts[1].substring(1).equals(this.token))) {
//System.out.println("CallbackServer -- Processing GET request");
// Wait until there is some data to send, or send empty data every 10 sec
// to prevent XHR timeout on the client
synchronized (this) {
while (this.empty) {
try {
this.wait(10000); // prevent timeout from happening
//Log.d(LOG_TAG, "CallbackServer>>> break <<<");
break;
} catch (Exception e) {
}
}
}
// Wait until there is some data to send, or send empty data every 10 sec
// to prevent XHR timeout on the client
synchronized (this) {
while (this.empty) {
try {
this.wait(10000); // prevent timeout from happening
//System.out.println("CallbackServer>>> break <<<");
break;
}
catch (Exception e) { }
}
}
// If server is still running
if (this.active) {
// If server is still running
if (this.active) {
// If no data, then send 404 back to client before it times out
if (this.empty) {
//Log.d(LOG_TAG, "CallbackServer -- sending data 0");
response = "HTTP/1.1 404 NO DATA\r\n\r\n "; // need to send content otherwise some Android devices fail, so send space
}
else {
//Log.d(LOG_TAG, "CallbackServer -- sending item");
response = "HTTP/1.1 200 OK\r\n\r\n";
String js = this.getJavascript();
if (js != null) {
response += encode(js, "UTF-8");
}
}
}
else {
response = "HTTP/1.1 503 Service Unavailable\r\n\r\n ";
}
}
else {
response = "HTTP/1.1 403 Forbidden\r\n\r\n ";
}
}
else {
response = "HTTP/1.1 400 Bad Request\r\n\r\n ";
}
//Log.d(LOG_TAG, "CallbackServer: response="+response);
//Log.d(LOG_TAG, "CallbackServer: closing output");
output.writeBytes(response);
output.flush();
}
output.close();
xhrReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
this.active = false;
//Log.d(LOG_TAG, "CallbackServer.startServer() - EXIT");
// If no data, then send 404 back to client before it times out
if (this.empty) {
//System.out.println("CallbackServer -- sending data 0");
response = "HTTP/1.1 404 NO DATA\r\n\r\n "; // need to send content otherwise some Android devices fail, so send space
}
else {
//System.out.println("CallbackServer -- sending item");
response = "HTTP/1.1 200 OK\r\n\r\n";
String js = this.getJavascript();
if (js != null) {
response += encode(js, "UTF-8");
}
}
}
else {
response = "HTTP/1.1 503 Service Unavailable\r\n\r\n ";
}
}
else {
response = "HTTP/1.1 403 Forbidden\r\n\r\n ";
}
}
else {
response = "HTTP/1.1 400 Bad Request\r\n\r\n ";
}
//System.out.println("CallbackServer: response="+response);
//System.out.println("CallbackServer: closing output");
output.writeBytes(response);
output.flush();
}
output.close();
xhrReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
this.active = false;
//System.out.println("CallbackServer.startServer() - EXIT");
}
/**
* Stop server.
* Stop server.
* This stops the thread that the server is running on.
*/
public void stopServer() {
//Log.d(LOG_TAG, "CallbackServer.stopServer()");
//System.out.println("CallbackServer.stopServer()");
if (this.active) {
this.active = false;
@@ -305,11 +307,11 @@ public class CallbackServer implements Runnable {
/**
* Get the number of JavaScript statements.
*
*
* @return int
*/
public int getSize() {
synchronized (this) {
synchronized(this) {
int size = this.javascript.size();
return size;
}
@@ -317,11 +319,11 @@ public class CallbackServer implements Runnable {
/**
* Get the next JavaScript statement and remove from list.
*
*
* @return String
*/
public String getJavascript() {
synchronized (this) {
synchronized(this) {
if (this.javascript.size() == 0) {
return null;
}
@@ -335,7 +337,7 @@ public class CallbackServer implements Runnable {
/**
* Add a JavaScript statement to the list.
*
*
* @param statement
*/
public void sendJavascript(String statement) {

View File

@@ -20,14 +20,12 @@ package org.apache.cordova;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64;
//import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
@@ -36,25 +34,20 @@ import org.json.JSONException;
import android.app.Activity;
import android.content.ContentValues;
//import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
/**
* This class launches the camera view, allows the user to take a picture, closes the camera view,
* and returns the captured image. When the camera view is closed, the screen displayed before
* the camera view was shown is redisplayed.
*/
public class CameraLauncher extends Plugin implements MediaScannerConnectionClient {
public class CameraLauncher extends Plugin {
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)
@@ -81,15 +74,9 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
private Uri imageUri; // Uri of captured image
private int encodingType; // Type of encoding to use
private int mediaType; // What type of media to retrieve
private boolean saveToPhotoAlbum; // Should the picture be saved to the device's photo album
public String callbackId;
private int numPics;
private MediaScannerConnection conn; // Used to update gallery app with newly-written files
//This should never be null!
//private CordovaInterface cordova;
/**
* Constructor.
@@ -97,14 +84,6 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
public CameraLauncher() {
}
// public void setContext(CordovaInterface mCtx) {
// super.setContext(mCtx);
// if (CordovaInterface.class.isInstance(mCtx))
// cordova = (CordovaInterface) mCtx;
// else
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
// }
/**
* Executes the request and returns PluginResult.
*
@@ -122,7 +101,6 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
if (action.equals("takePicture")) {
int srcType = CAMERA;
int destType = FILE_URI;
this.saveToPhotoAlbum = false;
this.targetHeight = 0;
this.targetWidth = 0;
this.encodingType = JPEG;
@@ -136,7 +114,6 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
this.targetHeight = args.getInt(4);
this.encodingType = args.getInt(5);
this.mediaType = args.getInt(6);
this.saveToPhotoAlbum = args.getBoolean(9);
if (srcType == CAMERA) {
this.takePicture(destType, encodingType);
@@ -175,7 +152,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
*/
public void takePicture(int returnType, int encodingType) {
// Save the number of images currently on disk for later
this.numPics = queryImgDB(whichContentStore()).getCount();
this.numPics = queryImgDB().getCount();
// Display camera
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
@@ -186,11 +163,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
this.imageUri = Uri.fromFile(photo);
if (this.cordova != null) {
this.cordova.startActivityForResult((Plugin) this, intent, (CAMERA + 1) * 16 + returnType + 1);
}
// else
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
this.ctx.startActivityForResult((Plugin) this, intent, (CAMERA+1)*16 + returnType+1);
}
/**
@@ -202,9 +175,9 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
private File createCaptureFile(int encodingType) {
File photo = null;
if (encodingType == JPEG) {
photo = new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), ".Pic.jpg");
photo = new File(DirectoryManager.getTempDirectoryPath(ctx.getContext()), "Pic.jpg");
} else if (encodingType == PNG) {
photo = new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), ".Pic.png");
photo = new File(DirectoryManager.getTempDirectoryPath(ctx.getContext()), "Pic.png");
} else {
throw new IllegalArgumentException("Invalid Encoding Type: " + encodingType);
}
@@ -238,10 +211,8 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (this.cordova != null) {
this.cordova.startActivityForResult((Plugin) this, Intent.createChooser(intent,
new String(title)), (srcType + 1) * 16 + returnType + 1);
}
this.ctx.startActivityForResult((Plugin) this, Intent.createChooser(intent,
new String(title)), (srcType+1)*16 + returnType + 1);
}
/**
@@ -275,8 +246,8 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
// kept and Bitmap.SCALE_TO_FIT specified when scaling, but this
// would result in whitespace in the new image.
else {
double newRatio = newWidth / (double) newHeight;
double origRatio = origWidth / (double) origHeight;
double newRatio = newWidth / (double)newHeight;
double origRatio = origWidth / (double)origHeight;
if (origRatio > newRatio) {
newHeight = (newWidth * origHeight) / origWidth;
@@ -287,7 +258,6 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
Bitmap retval = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
bitmap.recycle();
System.gc();
return retval;
}
@@ -302,104 +272,83 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Get src and dest types from request code
int srcType = (requestCode / 16) - 1;
int srcType = (requestCode/16) - 1;
int destType = (requestCode % 16) - 1;
int rotate = 0;
int rotate = 0;
// Create an ExifHelper to save the exif data that is lost during compression
ExifHelper exif = new ExifHelper();
try {
if (this.encodingType == JPEG) {
exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx.getContext()) + "/Pic.jpg");
exif.readExifData();
}
} catch (IOException e) {
e.printStackTrace();
}
// Create an ExifHelper to save the exif data that is lost during compression
ExifHelper exif = new ExifHelper();
try {
if (this.encodingType == JPEG) {
exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/.Pic.jpg");
exif.readExifData();
}
} catch (IOException e) {
e.printStackTrace();
}
// If CAMERA
if (srcType == CAMERA) {
// If image available
if (resultCode == Activity.RESULT_OK) {
try {
Bitmap bitmap = null;
// Read in bitmap of captured image
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri);
} catch (FileNotFoundException e) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getContentResolver();
bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
}
bitmap = scaleBitmap(bitmap);
// If sending base64 image back
if (destType == DATA_URL) {
bitmap = scaleBitmap(getBitmapFromResult(intent));
this.processPicture(bitmap);
checkForDuplicateImage(DATA_URL);
}
// If sending filename back
else if (destType == FILE_URI) {
Uri uri;
if (!this.saveToPhotoAlbum) {
uri = Uri.fromFile(new File("/data/data/" + this.cordova.getActivity().getPackageName() + "/", (new File(FileUtils.stripFileProtocol(this.imageUri.toString()))).getName()));
} else {
// Create entry in media store for image
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
else if (destType == FILE_URI){
// Create entry in media store for image
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = null;
try {
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.failPicture("Error capturing image - no media storage found.");
return;
}
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.failPicture("Error capturing image - no media storage found.");
return;
}
}
// If all this is true we shouldn't compress the image.
if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100) {
FileInputStream fis = new FileInputStream(FileUtils.stripFileProtocol(imageUri.toString()));
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
byte[] buffer = new byte[4096];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
fis.close();
// Add compressed version of captured image to returned media store Uri
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
} else {
bitmap = scaleBitmap(getBitmapFromResult(intent));
// Add compressed version of captured image to returned media store Uri
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Restore exif data to file
if (this.encodingType == JPEG) {
String exifPath;
if (this.saveToPhotoAlbum) {
exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
} else {
exifPath = uri.getPath();
}
exif.createOutFile(exifPath);
exif.writeExifData();
}
// Restore exif data to file
if (this.encodingType == JPEG) {
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
exif.writeExifData();
}
// Send Uri back to JavaScript for viewing image
this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
}
this.cleanup(FILE_URI, this.imageUri, bitmap);
bitmap.recycle();
bitmap = null;
System.gc();
checkForDuplicateImage(FILE_URI);
} catch (IOException e) {
e.printStackTrace();
this.failPicture("Error capturing image.");
@@ -421,7 +370,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
if (resultCode == Activity.RESULT_OK) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.cordova.getActivity().getContentResolver();
android.content.ContentResolver resolver = this.ctx.getContentResolver();
// If you ask for video or all media type you will automatically get back a file URI
// and there will be no attempt to resize any returned data
@@ -433,21 +382,21 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
if (destType == DATA_URL) {
try {
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
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();
}
if (rotate != 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotate);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
bitmap = scaleBitmap(bitmap);
String[] cols = { MediaStore.Images.Media.ORIENTATION };
Cursor cursor = this.ctx.getContentResolver().query(intent.getData(),
cols,
null, null, null);
if (cursor != null) {
cursor.moveToPosition(0);
rotate = cursor.getInt(0);
cursor.close();
}
if (rotate != 0) {
Matrix matrix = new Matrix();
matrix.setRotate(rotate);
bitmap = bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
bitmap = scaleBitmap(bitmap);
this.processPicture(bitmap);
bitmap.recycle();
bitmap = null;
@@ -466,14 +415,14 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
bitmap = scaleBitmap(bitmap);
String fileName = DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
String fileName = DirectoryManager.getTempDirectoryPath(ctx.getContext()) + "/resize.jpg";
OutputStream os = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
os.close();
// Restore exif data to file
if (this.encodingType == JPEG) {
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
exif.writeExifData();
}
@@ -504,48 +453,19 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
}
}
private Bitmap getBitmapFromResult(Intent intent)
throws IOException, FileNotFoundException {
Bitmap bitmap = null;
try {
bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getActivity().getContentResolver(), imageUri);
} catch (FileNotFoundException e) {
Uri uri = intent.getData();
android.content.ContentResolver resolver = this.ctx.getActivity().getContentResolver();
bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
}
return bitmap;
}
/**
* Creates a cursor that can be used to determine how many images we have.
*
* @return a cursor
*/
private Cursor queryImgDB(Uri contentStore) {
return this.cordova.getActivity().getContentResolver().query(
contentStore,
private Cursor queryImgDB() {
return this.ctx.getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
null,
null,
null);
}
/**
* Cleans up after picture taking. Checking for duplicates and that kind of stuff.
*/
private void cleanup(int imageType, Uri oldImage, Bitmap bitmap) {
bitmap.recycle();
// Clean up initial camera-written image file.
(new File(FileUtils.stripFileProtocol(oldImage.toString()))).delete();
checkForDuplicateImage(imageType);
// Scan for the gallery to update pic refs in gallery
this.scanForGallery();
System.gc();
}
/**
* Used to find out if we are in a situation where the Camera Intent adds to images
@@ -556,8 +476,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
*/
private void checkForDuplicateImage(int type) {
int diff = 1;
Uri contentStore = whichContentStore();
Cursor cursor = queryImgDB(contentStore);
Cursor cursor = queryImgDB();
int currentNumOfImages = cursor.getCount();
if (type == FILE_URI) {
@@ -568,20 +487,8 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
if ((currentNumOfImages - numPics) == diff) {
cursor.moveToLast();
int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
Uri uri = Uri.parse(contentStore + "/" + id);
this.cordova.getActivity().getContentResolver().delete(uri, null, null);
}
}
/**
* Determine if we are storing the images in internal or external storage
* @return Uri
*/
private Uri whichContentStore() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else {
return android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + id);
this.ctx.getContentResolver().delete(uri, null, null);
}
}
@@ -594,7 +501,7 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
ByteArrayOutputStream jpeg_data = new ByteArrayOutputStream();
try {
if (bitmap.compress(CompressFormat.JPEG, mQuality, jpeg_data)) {
byte[] code = jpeg_data.toByteArray();
byte[] code = jpeg_data.toByteArray();
byte[] output = Base64.encodeBase64(code);
String js_out = new String(output);
this.success(new PluginResult(PluginResult.Status.OK, js_out), this.callbackId);
@@ -602,7 +509,8 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
output = null;
code = null;
}
} catch (Exception e) {
}
catch(Exception e) {
this.failPicture("Error compressing image.");
}
jpeg_data = null;
@@ -616,24 +524,4 @@ public class CameraLauncher extends Plugin implements MediaScannerConnectionClie
public void failPicture(String err) {
this.error(new PluginResult(PluginResult.Status.ERROR, err), this.callbackId);
}
private void scanForGallery() {
if(this.conn!=null) this.conn.disconnect();
this.conn = new MediaScannerConnection(this.ctx.getActivity().getApplicationContext(), this);
conn.connect();
}
public void onMediaScannerConnected() {
try{
this.conn.scanFile(this.imageUri.toString(), "image/*");
} catch (java.lang.IllegalStateException e){
e.printStackTrace();
LOG.d(LOG_TAG, "Can;t scan file in MediaScanner aftering taking picture");
}
}
public void onScanCompleted(String path, Uri uri) {
this.conn.disconnect();
}
}

View File

@@ -19,7 +19,6 @@
package org.apache.cordova;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
@@ -33,18 +32,17 @@ import org.json.JSONObject;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
public class Capture extends Plugin {
private static final String VIDEO_3GPP = "video/3gpp";
private static final String VIDEO_MP4 = "video/mp4";
private static final String VIDEO_MP4 = "video/mp4";
private static final String AUDIO_3GPP = "audio/3gpp";
private static final String IMAGE_JPEG = "image/jpeg";
@@ -54,8 +52,8 @@ public class Capture extends Plugin {
private static final String LOG_TAG = "Capture";
private static final int CAPTURE_INTERNAL_ERR = 0;
// private static final int CAPTURE_APPLICATION_BUSY = 1;
// private static final int CAPTURE_INVALID_ARGUMENT = 2;
private static final int CAPTURE_APPLICATION_BUSY = 1;
private static final int CAPTURE_INVALID_ARGUMENT = 2;
private static final int CAPTURE_NO_MEDIA_FILES = 3;
private static final int CAPTURE_NOT_SUPPORTED = 20;
@@ -64,17 +62,6 @@ public class Capture extends Plugin {
private double duration; // optional duration parameter for video recording
private JSONArray results; // The array of results to be returned to the user
private Uri imageUri; // Uri of captured image
private int numPics; // Number of pictures before capture activity
//private CordovaInterface cordova;
// public void setContext(Context mCtx)
// {
// if (CordovaInterface.class.isInstance(mCtx))
// cordova = (CordovaInterface) mCtx;
// else
// LOG.d(LOG_TAG, "ERROR: You must use the CordovaInterface for this to work correctly. Please implement it in your activity");
// }
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
@@ -145,7 +132,8 @@ public class Capture extends Plugin {
else if (mimeType.equals(VIDEO_3GPP) || mimeType.equals(VIDEO_MP4)) {
obj = getAudioVideoData(filePath, obj, true);
}
} catch (JSONException e) {
}
catch (JSONException e) {
Log.d(LOG_TAG, "Error: setting media file data object");
}
return obj;
@@ -160,11 +148,10 @@ public class Capture extends Plugin {
* @throws JSONException
*/
private JSONObject getImageData(String filePath, JSONObject obj) throws JSONException {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(FileUtils.stripFileProtocol(filePath), options);
obj.put("height", options.outHeight);
obj.put("width", options.outWidth);
Bitmap bitmap = BitmapFactory.decodeFile(FileUtils.stripFileProtocol(filePath));
obj.put("height", bitmap.getHeight());
obj.put("width", bitmap.getWidth());
bitmap.recycle();
return obj;
}
@@ -182,12 +169,13 @@ public class Capture extends Plugin {
try {
player.setDataSource(filePath);
player.prepare();
obj.put("duration", player.getDuration() / 1000);
obj.put("duration", player.getDuration()/1000);
if (video) {
obj.put("height", player.getVideoHeight());
obj.put("width", player.getVideoWidth());
}
} catch (IOException e) {
}
catch (IOException e) {
Log.d(LOG_TAG, "Error: loading video file");
}
return obj;
@@ -199,24 +187,21 @@ public class Capture extends Plugin {
private void captureAudio() {
Intent intent = new Intent(android.provider.MediaStore.Audio.Media.RECORD_SOUND_ACTION);
this.cordova.startActivityForResult((Plugin) this, intent, CAPTURE_AUDIO);
this.ctx.startActivityForResult((Plugin) this, intent, CAPTURE_AUDIO);
}
/**
* Sets up an intent to capture images. Result handled by onActivityResult()
*/
private void captureImage() {
// Save the number of images currently on disk for later
this.numPics = queryImgDB(whichContentStore()).getCount();
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Specify file so that large image is captured and returned
File photo = new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()), "Capture.jpg");
File photo = new File(DirectoryManager.getTempDirectoryPath(ctx.getContext()), "Capture.jpg");
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
this.imageUri = Uri.fromFile(photo);
this.cordova.startActivityForResult((Plugin) this, intent, CAPTURE_IMAGE);
this.ctx.startActivityForResult((Plugin) this, intent, CAPTURE_IMAGE);
}
/**
@@ -227,7 +212,7 @@ public class Capture extends Plugin {
// Introduced in API 8
//intent.putExtra(android.provider.MediaStore.EXTRA_DURATION_LIMIT, duration);
this.cordova.startActivityForResult((Plugin) this, intent, CAPTURE_VIDEO);
this.ctx.startActivityForResult((Plugin) this, intent, CAPTURE_VIDEO);
}
/**
@@ -263,39 +248,48 @@ public class Capture extends Plugin {
// It crashes in the emulator and on my phone with a null pointer exception
// To work around it I had to grab the code from CameraLauncher.java
try {
// Create an ExifHelper to save the exif data that is lost during compression
ExifHelper exif = new ExifHelper();
exif.createInFile(DirectoryManager.getTempDirectoryPath(ctx.getContext()) + "/Capture.jpg");
exif.readExifData();
// Read in bitmap of captured image
Bitmap bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri);
// Create entry in media store for image
// (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
ContentValues values = new ContentValues();
values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, IMAGE_JPEG);
Uri uri = null;
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException e) {
LOG.d(LOG_TAG, "Can't write to external media storage.");
try {
uri = this.cordova.getActivity().getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
uri = this.ctx.getContentResolver().insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
} catch (UnsupportedOperationException ex) {
LOG.d(LOG_TAG, "Can't write to internal media storage.");
this.fail(createErrorObject(CAPTURE_INTERNAL_ERR, "Error capturing image - no media storage found."));
return;
}
}
FileInputStream fis = new FileInputStream(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()) + "/Capture.jpg");
OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
byte[] buffer = new byte[4096];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
// Add compressed version of captured image to returned media store Uri
OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();
fis.close();
bitmap.recycle();
bitmap = null;
System.gc();
// Restore exif data to file
exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.ctx));
exif.writeExifData();
// Add image to results
results.put(createMediaFile(uri));
checkForDuplicateImage();
if (results.length() >= limit) {
// Send Uri back to JavaScript for viewing image
this.success(new PluginResult(PluginResult.Status.OK, results), this.callbackId);
@@ -353,14 +347,15 @@ public class Capture extends Plugin {
* @return a JSONObject that represents a File
* @throws IOException
*/
private JSONObject createMediaFile(Uri data) {
File fp = new File(FileUtils.getRealPathFromURI(data, this.cordova));
private JSONObject createMediaFile(Uri data){
File fp = new File(FileUtils.getRealPathFromURI(data, this.ctx));
JSONObject obj = new JSONObject();
try {
// File properties
obj.put("name", fp.getName());
obj.put("fullPath", "file://" + fp.getAbsolutePath());
// Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files
// are reported as video/3gpp. I'm doing this hacky check of the URI to see if it
// is stored in the audio or video content store.
@@ -403,49 +398,4 @@ public class Capture extends Plugin {
public void fail(JSONObject err) {
this.error(new PluginResult(PluginResult.Status.ERROR, err), this.callbackId);
}
/**
* Creates a cursor that can be used to determine how many images we have.
*
* @return a cursor
*/
private Cursor queryImgDB(Uri contentStore) {
return this.cordova.getActivity().getContentResolver().query(
contentStore,
new String[] { MediaStore.Images.Media._ID },
null,
null,
null);
}
/**
* Used to find out if we are in a situation where the Camera Intent adds to images
* to the content store.
*/
private void checkForDuplicateImage() {
Uri contentStore = whichContentStore();
Cursor cursor = queryImgDB(contentStore);
int currentNumOfImages = cursor.getCount();
// delete the duplicate file if the difference is 2
if ((currentNumOfImages - numPics) == 2) {
cursor.moveToLast();
int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID))) - 1;
Uri uri = Uri.parse(contentStore + "/" + id);
this.cordova.getActivity().getContentResolver().delete(uri, null, null);
}
}
/**
* Determine if we are storing the images in internal or external storage
* @return Uri
*/
private Uri whichContentStore() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else {
return android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
}
}
}

View File

@@ -27,6 +27,7 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
@@ -67,11 +68,11 @@ public class CompassListener extends Plugin implements SensorEventListener {
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param ctx The context of the main Activity.
*/
public void setContext(CordovaInterface cordova) {
super.setContext(cordova);
this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE);
public void setContext(CordovaInterface ctx) {
super.setContext(ctx);
this.sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
}
/**
@@ -183,7 +184,6 @@ public class CompassListener extends Plugin implements SensorEventListener {
}
// Get compass sensor from sensor manager
@SuppressWarnings("deprecation")
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
// If found, then register as listener
@@ -212,6 +212,7 @@ public class CompassListener extends Plugin implements SensorEventListener {
this.setStatus(CompassListener.STOPPED);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}

View File

@@ -22,7 +22,6 @@ import android.content.Context;
import android.util.Log;
import android.webkit.WebView;
import org.apache.cordova.api.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@@ -37,7 +36,7 @@ import org.json.JSONObject;
public abstract class ContactAccessor {
protected final String LOG_TAG = "ContactsAccessor";
protected CordovaInterface mApp;
protected Context mApp;
protected WebView mView;
/**
@@ -76,7 +75,7 @@ public abstract class ContactAccessor {
map.put("urls", true);
map.put("photos", true);
map.put("categories", true);
}
}
else {
for (int i=0; i<fields.length(); i++) {
key = fields.getString(i);
@@ -122,7 +121,7 @@ public abstract class ContactAccessor {
}
}
}
}
}
catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
@@ -148,7 +147,7 @@ public abstract class ContactAccessor {
value = null;
}
}
}
}
catch (JSONException e) {
Log.d(LOG_TAG, "Could not get = " + e.getMessage());
}
@@ -177,8 +176,8 @@ public abstract class ContactAccessor {
*/
public abstract boolean remove(String id);
/**
* A class that represents the where clause to be used in the database query
/**
* A class that represents the where clause to be used in the database query
*/
class WhereOptions {
private String where;

File diff suppressed because it is too large Load Diff

View File

@@ -69,7 +69,7 @@ public class ContactManager extends Plugin {
* older phones.
*/
if (this.contactAccessor == null) {
this.contactAccessor = new ContactAccessorSdk5(this.webView, this.cordova);
this.contactAccessor = new ContactAccessorSdk5(this.webView, this.ctx.getContext());
}
try {

View File

@@ -17,18 +17,16 @@
under the License.
*/
package org.apache.cordova;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.LOG;
import org.json.JSONArray;
import org.json.JSONException;
//import android.app.Activity;
import android.app.AlertDialog;
//import android.content.Context;
import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;
//import android.view.View;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
@@ -43,38 +41,18 @@ import android.widget.EditText;
*/
public class CordovaChromeClient extends WebChromeClient {
private String TAG = "CordovaLog";
private long MAX_QUOTA = 100 * 1024 * 1024;
private CordovaInterface cordova;
private CordovaWebView appView;
private DroidGap ctx;
/**
* Constructor.
*
* @param cordova
*/
public CordovaChromeClient(CordovaInterface cordova) {
this.cordova = cordova;
}
/**
* Constructor.
*
* @param ctx
* @param app
*/
public CordovaChromeClient(CordovaInterface ctx, CordovaWebView app) {
this.cordova = ctx;
this.appView = app;
}
/**
* Constructor.
*
* @param view
*/
public void setWebView(CordovaWebView view) {
this.appView = view;
public CordovaChromeClient(Context ctx) {
this.ctx = (DroidGap) ctx;
}
/**
@@ -87,35 +65,35 @@ public class CordovaChromeClient extends WebChromeClient {
*/
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this.cordova.getActivity());
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
dlg.setTitle("Alert");
//Don't let alerts break the back button
dlg.setCancelable(true);
dlg.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
dlg.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.confirm();
}
});
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.confirm();
}
});
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
//DO NOTHING
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK)
if(keyCode == KeyEvent.KEYCODE_BACK)
{
result.confirm();
return false;
}
else
return true;
}
});
}
});
dlg.create();
dlg.show();
return true;
@@ -131,40 +109,40 @@ public class CordovaChromeClient extends WebChromeClient {
*/
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder dlg = new AlertDialog.Builder(this.cordova.getActivity());
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
dlg.setTitle("Confirm");
dlg.setCancelable(true);
dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
dlg.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.cancel();
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
result.cancel();
}
});
dlg.setOnKeyListener(new DialogInterface.OnKeyListener() {
//DO NOTHING
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK)
if(keyCode == KeyEvent.KEYCODE_BACK)
{
result.cancel();
return false;
}
else
return true;
}
});
}
});
dlg.create();
dlg.show();
return true;
@@ -190,11 +168,11 @@ 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://") || url.indexOf(this.ctx.baseUrl) == 0 || ctx.isUrlWhiteListed(url)) {
reqOk = true;
}
// Calling PluginManager.exec() to call a native service using
// Calling PluginManager.exec() to call a native service using
// prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true]));
if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) {
JSONArray array;
@@ -204,66 +182,72 @@ public class CordovaChromeClient extends WebChromeClient {
String action = array.getString(1);
String callbackId = array.getString(2);
boolean async = array.getBoolean(3);
String r = this.appView.pluginManager.exec(service, action, callbackId, message, async);
String r = ctx.pluginManager.exec(service, action, callbackId, message, async);
result.confirm(r);
} catch (JSONException e) {
e.printStackTrace();
}
}
// Polling for JavaScript messages
// Polling for JavaScript messages
else if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) {
String r = this.appView.callbackServer.getJavascript();
String r = ctx.callbackServer.getJavascript();
result.confirm(r);
}
// Do NO-OP so older code doesn't display dialog
else if (defaultValue != null && defaultValue.equals("gap_init:")) {
result.confirm("OK");
}
// Calling into CallbackServer
else if (reqOk && defaultValue != null && defaultValue.equals("gap_callbackServer:")) {
String r = "";
if (message.equals("usePolling")) {
r = "" + this.appView.callbackServer.usePolling();
r = ""+ ctx.callbackServer.usePolling();
}
else if (message.equals("restartServer")) {
this.appView.callbackServer.restartServer();
ctx.callbackServer.restartServer();
}
else if (message.equals("getPort")) {
r = Integer.toString(this.appView.callbackServer.getPort());
r = Integer.toString(ctx.callbackServer.getPort());
}
else if (message.equals("getToken")) {
r = this.appView.callbackServer.getToken();
r = ctx.callbackServer.getToken();
}
result.confirm(r);
}
// Cordova JS has initialized, so show webview
// (This solves white flash seen when rendering HTML)
else if (reqOk && defaultValue != null && defaultValue.equals("gap_init:")) {
if (ctx.splashscreen != 0) {
ctx.root.setBackgroundResource(0);
}
ctx.appView.setVisibility(View.VISIBLE);
ctx.spinnerStop();
result.confirm("OK");
}
// Show dialog
else {
final JsPromptResult res = result;
AlertDialog.Builder dlg = new AlertDialog.Builder(this.cordova.getActivity());
AlertDialog.Builder dlg = new AlertDialog.Builder(this.ctx);
dlg.setMessage(message);
final EditText input = new EditText(this.cordova.getActivity());
final EditText input = new EditText(this.ctx);
if (defaultValue != null) {
input.setText(defaultValue);
}
dlg.setView(input);
dlg.setCancelable(false);
dlg.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String usertext = input.getText().toString();
res.confirm(usertext);
}
});
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String usertext = input.getText().toString();
res.confirm(usertext);
}
});
dlg.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
res.cancel();
}
});
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
res.cancel();
}
});
dlg.create();
dlg.show();
}
@@ -286,7 +270,7 @@ public class CordovaChromeClient extends WebChromeClient {
{
LOG.d(TAG, "DroidGap: onExceededDatabaseQuota estimatedSize: %d currentQuota: %d totalUsedQuota: %d", estimatedSize, currentQuota, totalUsedQuota);
if (estimatedSize < MAX_QUOTA)
if( estimatedSize < MAX_QUOTA)
{
//increase for 1Mb
long newQuota = estimatedSize;
@@ -302,7 +286,6 @@ public class CordovaChromeClient extends WebChromeClient {
}
// console.log in api level 7: http://developer.android.com/guide/developing/debug-tasks.html
@SuppressWarnings("deprecation")
@Override
public void onConsoleMessage(String message, int lineNumber, String sourceID)
{
@@ -313,7 +296,7 @@ public class CordovaChromeClient extends WebChromeClient {
@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage)
{
if (consoleMessage.message() != null)
if(consoleMessage.message() != null)
LOG.d(TAG, consoleMessage.message());
return super.onConsoleMessage(consoleMessage);
}
@@ -329,4 +312,6 @@ public class CordovaChromeClient extends WebChromeClient {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
}

View File

@@ -1,774 +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;
import java.io.IOException;
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.api.CordovaInterface;
import org.apache.cordova.api.LOG;
import org.apache.cordova.api.PluginManager;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.Intent;
import android.content.res.XmlResourceParser;
import android.net.Uri;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebSettings.LayoutAlgorithm;
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;
public CallbackServer callbackServer;
/** Actvities and other important classes **/
private CordovaInterface cordova;
CordovaWebViewClient viewClient;
@SuppressWarnings("unused")
private CordovaChromeClient chromeClient;
//This is for the polyfil history
private String url;
String baseUrl;
private Stack<String> urls = new Stack<String>();
boolean useBrowserHistory = false;
// Flag to track that a loadUrl timeout occurred
int loadUrlTimeout = 0;
private boolean bound;
private boolean volumedownBound;
private boolean volumeupBound;
/**
* Constructor.
*
* @param context
*/
public CordovaWebView(Context context) {
super(context);
if (CordovaInterface.class.isInstance(context))
{
this.cordova = (CordovaInterface) context;
}
else
{
Log.d(TAG, "Your activity must implement CordovaInterface to work");
}
this.loadConfiguration();
this.setup();
}
/**
* Constructor.
*
* @param context
* @param attrs
*/
public CordovaWebView(Context context, AttributeSet attrs) {
super(context, attrs);
if (CordovaInterface.class.isInstance(context))
{
this.cordova = (CordovaInterface) context;
}
else
{
Log.d(TAG, "Your activity must implement CordovaInterface to work");
}
this.setWebChromeClient(new CordovaChromeClient(this.cordova, this));
this.setWebViewClient(new CordovaWebViewClient(this.cordova, this));
this.loadConfiguration();
this.setup();
}
/**
* Constructor.
*
* @param context
* @param attrs
* @param defStyle
*
*/
public CordovaWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
if (CordovaInterface.class.isInstance(context))
{
this.cordova = (CordovaInterface) context;
}
else
{
Log.d(TAG, "Your activity must implement CordovaInterface to work");
}
this.setWebChromeClient(new CordovaChromeClient(this.cordova, this));
this.setWebViewClient(new CordovaWebViewClient(this.cordova, this));
this.loadConfiguration();
this.setup();
}
/**
* Constructor.
*
* @param context
* @param attrs
* @param defStyle
* @param privateBrowsing
*/
public CordovaWebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) {
super(context, attrs, defStyle, privateBrowsing);
if (CordovaInterface.class.isInstance(context))
{
this.cordova = (CordovaInterface) context;
}
else
{
Log.d(TAG, "Your activity must implement CordovaInterface to work");
}
this.setWebChromeClient(new CordovaChromeClient(this.cordova));
this.setWebViewClient(new CordovaWebViewClient(this.cordova));
this.loadConfiguration();
this.setup();
}
/**
* Initialize webview.
*/
@SuppressWarnings("deprecation")
private void setup() {
this.setInitialScale(0);
this.setVerticalScrollBarEnabled(false);
this.requestFocusFromTouch();
// Enable JavaScript
WebSettings settings = this.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
//Set the nav dump for HTC
settings.setNavDump(true);
// Enable database
settings.setDatabaseEnabled(true);
String databasePath = this.cordova.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
settings.setDatabasePath(databasePath);
// Enable DOM storage
settings.setDomStorageEnabled(true);
// Enable built-in geolocation
settings.setGeolocationEnabled(true);
//Start up the plugin manager
try {
this.pluginManager = new PluginManager(this, this.cordova);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Set the WebViewClient.
*
* @param client
*/
public void setWebViewClient(CordovaWebViewClient client) {
this.viewClient = client;
super.setWebViewClient(client);
}
/**
* Set the WebChromeClient.
*
* @param client
*/
public void setWebChromeClient(CordovaChromeClient client) {
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;
}
/**
* Load the url into the webview.
*
* @param url
*/
@Override
public void loadUrl(String url) {
if (url.equals("about:blank") || url.startsWith("javascript:")) {
this.loadUrlNow(url);
}
else {
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)) {
this.loadUrlIntoView(url);
}
// Otherwise use the URL specified in the activity's extras bundle
else {
this.loadUrlIntoView(initUrl);
}
}
}
/**
* Load the url into the webview after waiting for period of time.
* This is used to display the splashscreen for certain amount of time.
*
* @param url
* @param time The number of ms to wait before loading webview
*/
public void loadUrl(final String url, int time) {
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)) {
this.loadUrlIntoView(url, time);
}
// Otherwise use the URL specified in the activity's extras bundle
else {
this.loadUrlIntoView(initUrl);
}
}
/**
* Load the url into the webview.
*
* @param url
*/
public void loadUrlIntoView(final String url) {
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();
if (!this.useBrowserHistory) {
this.urls.push(url);
}
}
// Create a timeout timer for loadUrl
final CordovaWebView me = this;
final int currentLoadUrlTimeout = me.loadUrlTimeout;
final int loadUrlTimeoutValue = Integer.parseInt(this.getProperty("loadUrlTimeoutValue", "20000"));
// Timeout error method
final Runnable loadError = new Runnable() {
public void run() {
me.stopLoading();
LOG.e(TAG, "CordovaWebView: TIMEOUT ERROR!");
if (viewClient != null) {
viewClient.onReceivedError(me, -6, "The connection to the server was unsuccessful.", url);
}
}
};
// Timeout timer method
final Runnable timeoutCheck = new Runnable() {
public void run() {
try {
synchronized (this) {
wait(loadUrlTimeoutValue);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
// If timeout, then stop loading and handle error
if (me.loadUrlTimeout == currentLoadUrlTimeout) {
me.cordova.getActivity().runOnUiThread(loadError);
}
}
};
// Load url
this.cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
Thread thread = new Thread(timeoutCheck);
thread.start();
me.loadUrlNow(url);
}
});
}
/**
* Load URL in webview.
*
* @param url
*/
private void loadUrlNow(String url) {
LOG.d(TAG, ">>> loadUrlNow()");
super.loadUrl(url);
}
/**
* Load the url into the webview after waiting for period of time.
* This is used to display the splashscreen for certain amount of time.
*
* @param url
* @param time The number of ms to wait before loading webview
*/
public void loadUrlIntoView(final String url, final int time) {
// 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 first page, then show splashscreen
else {
LOG.d(TAG, "DroidGap.loadUrl(%s, %d)", url, time);
// Send message to show splashscreen now if desired
this.postMessage("splashscreen", "show");
}
// Load url
this.loadUrlIntoView(url);
}
/**
* Send JavaScript statement back to JavaScript.
* (This is a convenience method)
*
* @param message
*/
public void sendJavascript(String statement) {
if (this.callbackServer != null) {
this.callbackServer.sendJavascript(statement);
}
}
/**
* Send a message to all plugins.
*
* @param id The message id
* @param data The message data
*/
public void postMessage(String id, Object data) {
if (this.pluginManager != null) {
this.pluginManager.postMessage(id, data);
}
}
/**
* 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)
*
* @return true if we went back, false if we are already at top
*/
public boolean backHistory() {
// 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()) {
super.goBack();
return true;
}
// If our managed history has prev url
if (this.urls.size() > 1) {
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.
*
* NOTE: If openExternal is false, only URLs listed in whitelist can be loaded.
*
* @param url The url to load.
* @param openExternal Load url in browser instead of Cordova webview.
* @param clearHistory Clear the history stack, so new page becomes top of history
* @param params DroidGap parameters for new app
*/
public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) {
LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory);
// If clearing history
if (clearHistory) {
this.clearHistory();
}
// If loading into our webview
if (!openExternal) {
// Make sure url is in whitelist
if (url.startsWith("file://") || url.indexOf(this.baseUrl) == 0 || 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);
}
// Load in default viewer if not
else {
LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL=" + url + ")");
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url " + url, e);
}
}
}
// Load in default view intent
else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
cordova.getActivity().startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url " + url, e);
}
}
}
/**
* Load Cordova configuration from res/xml/cordova.xml.
* 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("cordova", "xml", this.cordova.getActivity().getPackageName());
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);
// 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 ("true".equals(this.getProperty("useBrowserHistory", "true"))) {
this.useBrowserHistory = true;
}
else {
this.useBrowserHistory = false;
}
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);
}
}
/**
* Get string property for activity.
*
* @param name
* @param defaultValue
* @return
*/
public String getProperty(String name, String defaultValue) {
Bundle bundle = this.cordova.getActivity().getIntent().getExtras();
if (bundle == null) {
return defaultValue;
}
Object p = bundle.get(name);
if (p == null) {
return defaultValue;
}
return p.toString();
}
/*
* onKeyDown
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyDownCodes.contains(keyCode))
{
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
// only override default behaviour is event bound
LOG.d(TAG, "Down Key Hit");
this.loadUrl("javascript:cordova.fireDocumentEvent('volumedownbutton');");
return true;
}
// If volumeup key
else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
LOG.d(TAG, "Up Key Hit");
this.loadUrl("javascript:cordova.fireDocumentEvent('volumeupbutton');");
return true;
}
else
{
//Do some other stuff!
}
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event)
{
Log.d(TAG, "KeyDown has been triggered on the view");
// 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;
} 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;
}
}
}
// Legacy
else if (keyCode == KeyEvent.KEYCODE_MENU) {
this.loadUrl("javascript:cordova.fireDocumentEvent('menubutton');");
return super.onKeyUp(keyCode, event);
}
// If search key
else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
this.loadUrl("javascript:cordova.fireDocumentEvent('searchbutton');");
return true;
}
else if(keyUpCodes.contains(keyCode))
{
//What the hell should this do?
}
Log.d(TAG, "KeyUp has been triggered on the view");
return false;
}
public void bindButton(boolean override)
{
this.bound = override;
}
public void bindButton(String button, boolean override) {
// TODO Auto-generated method stub
if (button.compareTo("volumeup")==0) {
keyDownCodes.add(KeyEvent.KEYCODE_VOLUME_UP);
}
else if (button.compareTo("volumedown")==0) {
keyDownCodes.add(KeyEvent.KEYCODE_VOLUME_DOWN);
}
}
public void bindButton(int keyCode, boolean keyDown, boolean override) {
if(keyDown)
{
keyDownCodes.add(keyCode);
}
else
{
keyUpCodes.add(keyCode);
}
}
}

View File

@@ -18,29 +18,18 @@
*/
package org.apache.cordova;
import java.util.Hashtable;
import org.apache.cordova.api.CordovaInterface;
import java.io.IOException;
import java.io.InputStream;
import org.apache.cordova.api.LOG;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.view.View;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@@ -50,40 +39,16 @@ import android.webkit.WebViewClient;
public class CordovaWebViewClient extends WebViewClient {
private static final String TAG = "Cordova";
CordovaInterface cordova;
CordovaWebView appView;
DroidGap ctx;
private boolean doClearHistory = false;
/** The authorization tokens. */
private Hashtable<String, AuthenticationToken> authenticationTokens = new Hashtable<String, AuthenticationToken>();
/**
* Constructor.
*
* @param cordova
* @param ctx
*/
public CordovaWebViewClient(CordovaInterface cordova) {
this.cordova = cordova;
}
/**
* Constructor.
*
* @param cordova
* @param view
*/
public CordovaWebViewClient(CordovaInterface cordova, CordovaWebView view) {
this.cordova = cordova;
this.appView = view;
}
/**
* Constructor.
*
* @param view
*/
public void setWebView(CordovaWebView view) {
this.appView = view;
public CordovaWebViewClient(DroidGap ctx) {
this.ctx = ctx;
}
/**
@@ -98,7 +63,7 @@ public class CordovaWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// First give any plugins the chance to handle the url themselves
if ((this.appView.pluginManager != null) && this.appView.pluginManager.onOverrideUrlLoading(url)) {
if ((this.ctx.pluginManager != null) && this.ctx.pluginManager.onOverrideUrlLoading(url)) {
}
// If dialing phone (tel:5551212)
@@ -106,9 +71,9 @@ public class CordovaWebViewClient extends WebViewClient {
try {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse(url));
this.cordova.getActivity().startActivity(intent);
ctx.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error dialing " + url + ": " + e.toString());
LOG.e(TAG, "Error dialing "+url+": "+ e.toString());
}
}
@@ -117,9 +82,9 @@ public class CordovaWebViewClient extends WebViewClient {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.cordova.getActivity().startActivity(intent);
ctx.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error showing map " + url + ": " + e.toString());
LOG.e(TAG, "Error showing map "+url+": "+ e.toString());
}
}
@@ -128,9 +93,9 @@ public class CordovaWebViewClient extends WebViewClient {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.cordova.getActivity().startActivity(intent);
ctx.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error sending email " + url + ": " + e.toString());
LOG.e(TAG, "Error sending email "+url+": "+ e.toString());
}
}
@@ -157,12 +122,12 @@ public class CordovaWebViewClient extends WebViewClient {
}
}
}
intent.setData(Uri.parse("sms:" + address));
intent.setData(Uri.parse("sms:"+address));
intent.putExtra("address", address);
intent.setType("vnd.android-dir/mms-sms");
this.cordova.getActivity().startActivity(intent);
ctx.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error sending sms " + url + ":" + e.toString());
LOG.e(TAG, "Error sending sms "+url+":"+ e.toString());
}
}
@@ -171,12 +136,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.indexOf(this.appView.baseUrl) == 0 || this.appView.isUrlWhiteListed(url)) {
//This will fix iFrames
if (appView.useBrowserHistory)
return false;
else
this.appView.loadUrl(url);
if (url.startsWith("file://") || url.indexOf(this.ctx.baseUrl) == 0 || ctx.isUrlWhiteListed(url)) {
this.ctx.loadUrl(url);
}
// If not our application, let default viewer handle
@@ -184,9 +145,9 @@ public class CordovaWebViewClient extends WebViewClient {
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
this.cordova.getActivity().startActivity(intent);
ctx.startActivity(intent);
} catch (android.content.ActivityNotFoundException e) {
LOG.e(TAG, "Error loading url " + url, e);
LOG.e(TAG, "Error loading url "+url, e);
}
}
}
@@ -198,55 +159,37 @@ public class CordovaWebViewClient extends WebViewClient {
* The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination
*
* @param view
* the view
* @param handler
* the handler
* @param host
* the host
* @param realm
* the realm
*/
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,
String realm) {
// Get the authentication token
AuthenticationToken token = this.getAuthenticationToken(host, realm);
if (token != null) {
// get the authentication token
AuthenticationToken token = ctx.getAuthenticationToken(host,realm);
if(token != null) {
handler.proceed(token.getUserName(), token.getPassword());
}
}
/**
* 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;
}
// Create callback server and plugin manager
if (this.appView.callbackServer == null) {
this.appView.callbackServer = new CallbackServer();
this.appView.callbackServer.init(url);
}
else {
this.appView.callbackServer.reinit(url);
}
// Broadcast message that page has loaded
this.appView.postMessage("onPageStarted", url);
view.clearHistory();
this.doClearHistory = true;
}
/**
* 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.
@@ -254,7 +197,6 @@ public class CordovaWebViewClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
LOG.d(TAG, "onPageFinished(" + url + ")");
/**
* Because of a timing issue we need to clear this history in onPageFinished as well as
@@ -268,28 +210,29 @@ public class CordovaWebViewClient extends WebViewClient {
}
// Clear timeout flag
this.appView.loadUrlTimeout++;
this.ctx.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);
ctx.appView.loadUrl("javascript:try{ cordova.require('cordova/channel').onNativeReady.fire();}catch(e){_nativeReady = true;}");
this.ctx.postMessage("onNativeReady", null);
}
// Broadcast message that page has loaded
this.appView.postMessage("onPageFinished", url);
// Make app visible after 2 sec in case there was a JS error and Cordova JS never initialized correctly
if (this.appView.getVisibility() == View.INVISIBLE) {
if (ctx.appView.getVisibility() == View.INVISIBLE) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(2000);
cordova.getActivity().runOnUiThread(new Runnable() {
ctx.runOnUiThread(new Runnable() {
public void run() {
appView.postMessage("spinner", "stop");
if (ctx.splashscreen != 0) {
ctx.root.setBackgroundResource(0);
}
ctx.appView.setVisibility(View.VISIBLE);
ctx.spinnerStop();
}
});
} catch (InterruptedException e) {
@@ -299,12 +242,13 @@ public class CordovaWebViewClient extends WebViewClient {
t.start();
}
// Shutdown if blank loaded
if (url.equals("about:blank")) {
if (this.appView.callbackServer != null) {
this.appView.callbackServer.destroy();
if (this.ctx.callbackServer != null) {
this.ctx.callbackServer.destroy();
}
appView.postMessage("exit", null);
this.ctx.endActivity();
}
}
@@ -319,39 +263,22 @@ public class CordovaWebViewClient extends WebViewClient {
*/
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
LOG.d(TAG, "CordovaWebViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
LOG.d(TAG, "DroidGap: GapViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl);
// Clear timeout flag
this.appView.loadUrlTimeout++;
this.ctx.loadUrlTimeout++;
// Stop "app loading" spinner if showing
this.ctx.spinnerStop();
// Handle error
JSONObject data = new JSONObject();
try {
data.put("errorCode", errorCode);
data.put("description", description);
data.put("url", failingUrl);
} catch (JSONException e) {
e.printStackTrace();
}
this.appView.postMessage("onReceivedError", data);
this.ctx.onReceivedError(errorCode, description, failingUrl);
}
/**
* 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.
*/
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
final String packageName = this.cordova.getActivity().getPackageName();
final PackageManager pm = this.cordova.getActivity().getPackageManager();
final String packageName = this.ctx.getPackageName();
final PackageManager pm = this.ctx.getPackageManager();
ApplicationInfo appInfo;
try {
appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
@@ -369,133 +296,14 @@ 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);
if (!this.ctx.peekAtUrlStack().equals(url)) {
this.ctx.pushUrl(url);
}
}
/**
* Sets the authentication token.
*
* @param authenticationToken
* @param host
* @param realm
*/
public void setAuthenticationToken(AuthenticationToken authenticationToken, String host, String realm) {
if (host == null) {
host = "";
}
if (realm == null) {
realm = "";
}
this.authenticationTokens.put(host.concat(realm), authenticationToken);
}
/**
* 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) {
return this.authenticationTokens.remove(host.concat(realm));
}
/**
* 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) {
AuthenticationToken token = null;
token = this.authenticationTokens.get(host.concat(realm));
if (token == null) {
// try with just the host
token = this.authenticationTokens.get(host);
// Try the realm
if (token == null) {
token = this.authenticationTokens.get(realm);
}
// if no host found, just query for default
if (token == null) {
token = this.authenticationTokens.get("");
}
}
return token;
}
/**
* Clear all authentication tokens.
*/
public void clearAuthenticationTokens() {
this.authenticationTokens.clear();
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if(url.contains("?") || url.contains("#")){
return generateWebResourceResponse(url);
} else {
return super.shouldInterceptRequest(view, url);
}
}
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";
}
try {
AssetManager assets = cordova.getActivity().getAssets();
Uri uri = Uri.parse(niceUrl);
InputStream stream = assets.open(uri.getPath(), AssetManager.ACCESS_STREAMING);
WebResourceResponse response = new WebResourceResponse(mimetype, "UTF-8", stream);
return response;
} catch (IOException e) {
LOG.e("generateWebResourceResponse", e.getMessage(), e);
}
}
return null;
}
}

View File

@@ -38,7 +38,7 @@ import android.telephony.TelephonyManager;
public class Device extends Plugin {
public static final String TAG = "Device";
public static String cordovaVersion = "1.9.0rc1"; // Cordova version
public static String cordovaVersion = "1.8.1"; // Cordova version
public static String platform = "Android"; // Device OS
public static String uuid; // Device UUID
@@ -54,10 +54,10 @@ public class Device extends Plugin {
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param ctx The context of the main Activity.
*/
public void setContext(CordovaInterface cordova) {
super.setContext(cordova);
public void setContext(CordovaInterface ctx) {
super.setContext(ctx);
Device.uuid = getUuid();
this.initTelephonyReceiver();
}
@@ -110,7 +110,7 @@ public class Device extends Plugin {
* Unregister receiver.
*/
public void onDestroy() {
this.cordova.getActivity().unregisterReceiver(this.telephonyReceiver);
this.ctx.unregisterReceiver(this.telephonyReceiver);
}
//--------------------------------------------------------------------------
@@ -123,9 +123,9 @@ public class Device extends Plugin {
* DroidGap.onMessage("telephone", "ringing" | "offhook" | "idle")
*/
private void initTelephonyReceiver() {
IntentFilter intentFilter = new IntentFilter();
IntentFilter intentFilter = new IntentFilter() ;
intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
//final CordovaInterface mycordova = this.cordova;
final CordovaInterface myctx = this.ctx;
this.telephonyReceiver = new BroadcastReceiver() {
@Override
@@ -137,15 +137,15 @@ public class Device extends Plugin {
String extraData = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (extraData.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
LOG.i(TAG, "Telephone RINGING");
webView.postMessage("telephone", "ringing");
myctx.postMessage("telephone", "ringing");
}
else if (extraData.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
LOG.i(TAG, "Telephone OFFHOOK");
webView.postMessage("telephone", "offhook");
myctx.postMessage("telephone", "offhook");
}
else if (extraData.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
LOG.i(TAG, "Telephone IDLE");
webView.postMessage("telephone", "idle");
myctx.postMessage("telephone", "idle");
}
}
}
@@ -153,7 +153,7 @@ public class Device extends Plugin {
};
// Register the receiver
this.cordova.getActivity().registerReceiver(this.telephonyReceiver, intentFilter);
this.ctx.registerReceiver(this.telephonyReceiver, intentFilter);
}
/**
@@ -171,7 +171,7 @@ public class Device extends Plugin {
* @return
*/
public String getUuid() {
String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
String uuid = Settings.Secure.getString(this.ctx.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
return uuid;
}
@@ -205,14 +205,15 @@ public class Device extends Plugin {
}
public String getSDKVersion() {
@SuppressWarnings("deprecation")
String sdkversion = android.os.Build.VERSION.SDK;
return sdkversion;
}
public String getTimeZoneID() {
TimeZone tz = TimeZone.getDefault();
return (tz.getID());
TimeZone tz = TimeZone.getDefault();
return(tz.getID());
}
}

View File

@@ -32,11 +32,11 @@ import android.os.StatFs;
*/
public class DirectoryManager {
@SuppressWarnings("unused")
private static final String LOG_TAG = "DirectoryManager";
/**
* Determine if a file or directory exists.
*
* @param name The name of the file to check.
* @return T=exists, F=not found
*/
@@ -50,7 +50,7 @@ public class DirectoryManager {
status = newPath.exists();
}
// If no SD card
else {
else{
status = false;
}
return status;
@@ -58,7 +58,7 @@ public class DirectoryManager {
/**
* Get the free disk space
*
*
* @return Size in KB or -1 if not available
*/
protected static long getFreeDiskSpace(boolean checkInternal) {
@@ -82,7 +82,7 @@ public class DirectoryManager {
/**
* Given a path return the number of free KB
*
*
* @param path to the file system
* @return free space in KB
*/
@@ -90,12 +90,12 @@ public class DirectoryManager {
StatFs stat = new StatFs(path);
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize / 1024;
return availableBlocks*blockSize/1024;
}
/**
* Determine if SD card exists.
*
*
* @return T=exists, F=not found
*/
protected static boolean testSaveLocationExists() {
@@ -127,7 +127,7 @@ public class DirectoryManager {
newPath = new File(file2);
}
else {
newPath = new File(file1 + "/" + file2);
newPath = new File(file1+"/"+file2);
}
return newPath;
}

File diff suppressed because it is too large Load Diff

View File

@@ -51,6 +51,7 @@ import android.net.Uri;
import android.util.Log;
import android.webkit.CookieManager;
public class FileTransfer extends Plugin {
private static final String LOG_TAG = "FileTransfer";
@@ -75,7 +76,8 @@ public class FileTransfer extends Plugin {
try {
source = args.getString(0);
target = args.getString(1);
} catch (JSONException e) {
}
catch (JSONException e) {
Log.d(LOG_TAG, "Missing source or target");
return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Missing source or target");
}
@@ -219,11 +221,9 @@ public class FileTransfer extends Plugin {
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");
// Should set this up as an option
if (chunkedMode) {
@@ -231,7 +231,7 @@ public class FileTransfer extends Plugin {
}
else
{
int stringLength = extraBytes.length + midParams.length() + tailParams.length() + fileNameBytes.length;
int stringLength = extraParams.length() + midParams.length() + tailParams.length() + fileName.getBytes("UTF-8").length;
Log.d(LOG_TAG, "String Length: " + stringLength);
int fixedLength = (int) fileInputStream.getChannel().size() + stringLength;
Log.d(LOG_TAG, "Content Length: " + fixedLength);
@@ -240,9 +240,9 @@ public class FileTransfer extends Plugin {
dos = new DataOutputStream( conn.getOutputStream() );
//We don't want to change encoding, we just want this to write for all Unicode.
dos.write(extraBytes);
dos.write(fileNameBytes);
dos.writeBytes(extraParams);
//We don't want to chagne encoding, we just want this to write for all Unicode.
dos.write(fileName.getBytes("UTF-8"));
dos.writeBytes(midParams);
// create a buffer of maximum size
@@ -353,11 +353,11 @@ public class FileTransfer extends Plugin {
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
String authType) throws CertificateException {
}
} };
@@ -419,7 +419,7 @@ public class FileTransfer extends Plugin {
*/
private String getArgument(JSONArray args, int position, String defaultString) {
String arg = defaultString;
if (args.length() >= position) {
if(args.length() >= position) {
arg = args.optString(position);
if (arg == null || "null".equals(arg)) {
arg = defaultString;
@@ -428,6 +428,7 @@ public class FileTransfer extends Plugin {
return arg;
}
/**
* Downloads a file form a given URL and saves it to the specified directory.
*
@@ -446,7 +447,7 @@ public class FileTransfer extends Plugin {
file.getParentFile().mkdirs();
// connect to server
if (webView.isUrlWhiteListed(source))
if(this.ctx.isUrlWhiteListed(source))
{
URL url = new URL(source);
connection = (HttpURLConnection) url.openConnection();
@@ -463,24 +464,20 @@ public class FileTransfer extends Plugin {
Log.d(LOG_TAG, "Download file: " + url);
connection.connect();
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
Log.d(LOG_TAG, "Download file:" + url);
FileOutputStream outputStream = new FileOutputStream(file);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
// write bytes to file
while ( (bytesRead = inputStream.read(buffer)) > 0 ) {
outputStream.write(buffer,0, bytesRead);
}
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.close();
// write bytes to file
while ((bytesRead = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
Log.d(LOG_TAG, "Saved file: " + target);
Log.d(LOG_TAG, "Saved file: " + target);
// create FileEntry object
FileUtils fileUtil = new FileUtils();
@@ -524,7 +521,7 @@ public class FileTransfer extends Plugin {
private InputStream getPathFromUri(String path) throws FileNotFoundException {
if (path.startsWith("content:")) {
Uri uri = Uri.parse(path);
return cordova.getActivity().getContentResolver().openInputStream(uri);
return ctx.getContentResolver().openInputStream(uri);
}
else if (path.startsWith("file://")) {
int question = path.indexOf("?");

View File

@@ -37,21 +37,18 @@ 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;
/**
* This class provides SD card file and directory services to JavaScript.
* Only files on the SD card can be accessed.
*/
public class FileUtils extends Plugin {
@SuppressWarnings("unused")
private static final String LOG_TAG = "FileUtils";
private static final String _DATA = "_data"; // The column name where the file path is stored
@@ -132,7 +129,7 @@ public class FileUtils extends Plugin {
else if (action.equals("requestFileSystem")) {
long size = args.optLong(1);
if (size != 0) {
if (size > (DirectoryManager.getFreeDiskSpace(true) * 1024)) {
if (size > (DirectoryManager.getFreeDiskSpace(true)*1024)) {
return new PluginResult(PluginResult.Status.ERROR, FileUtils.QUOTA_EXCEEDED_ERR);
}
}
@@ -223,9 +220,9 @@ public class FileUtils extends Plugin {
*/
private void notifyDelete(String filePath) {
String newFilePath = stripFileProtocol(filePath);
int result = this.cordova.getActivity().getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.Images.Media.DATA + " = ?",
new String[] { newFilePath });
int result = this.ctx.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
MediaStore.Images.Media.DATA + " = ?",
new String[] {newFilePath});
}
/**
@@ -238,7 +235,6 @@ public class FileUtils extends Plugin {
* @throws IOException if the user can't read the file
* @throws JSONException
*/
@SuppressWarnings("deprecation")
private JSONObject resolveLocalFileSystemURI(String url) throws IOException, JSONException {
String decoded = URLDecoder.decode(url, "UTF-8");
@@ -246,7 +242,7 @@ public class FileUtils extends Plugin {
// Handle the special case where you get an Android content:// uri.
if (decoded.startsWith("content:")) {
Cursor cursor = this.cordova.getActivity().managedQuery(Uri.parse(decoded), new String[] { MediaStore.Images.Media.DATA }, null, null, null);
Cursor cursor = this.ctx.managedQuery(Uri.parse(decoded), new String[] { MediaStore.Images.Media.DATA }, null, null, null);
// Note: MediaStore.Images/Audio/Video.Media.DATA is always "_data"
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
@@ -297,7 +293,7 @@ public class FileUtils extends Plugin {
if (fp.isDirectory()) {
File[] files = fp.listFiles();
for (int i = 0; i < files.length; i++) {
for (int i=0; i<files.length; i++) {
entries.put(getEntry(files[i]));
}
}
@@ -323,6 +319,7 @@ public class FileUtils extends Plugin {
fileName = stripFileProtocol(fileName);
newParent = stripFileProtocol(newParent);
// Check for invalid file name
if (newName != null && newName.contains(":")) {
throw new EncodingException("Bad file name");
@@ -379,7 +376,7 @@ public class FileUtils extends Plugin {
File destFile = null;
// I know this looks weird but it is to work around a JSON bug.
if ("null".equals(newName) || "".equals(newName)) {
if ("null".equals(newName) || "".equals(newName) ) {
newName = null;
}
@@ -401,7 +398,7 @@ public class FileUtils extends Plugin {
* @throws InvalidModificationException
* @throws JSONException
*/
private JSONObject copyFile(File srcFile, File destFile) throws IOException, InvalidModificationException, JSONException {
private JSONObject copyFile(File srcFile, File destFile) throws IOException, InvalidModificationException, JSONException {
// 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");
@@ -479,7 +476,7 @@ public class FileUtils extends Plugin {
// This weird test is to determine if we are copying or moving a directory into itself.
// Copy /sdcard/myDir to /sdcard/myDir-backup is okay but
// Copy /sdcard/myDir to /sdcard/myDir/backup should thow an INVALID_MODIFICATION_ERR
if (dest.startsWith(src) && dest.indexOf(File.separator, src.length() - 1) != -1) {
if (dest.startsWith(src) && dest.indexOf(File.separator, src.length()-1) != -1) {
return true;
}
@@ -728,9 +725,9 @@ public class FileUtils extends Plugin {
private boolean atRootDirectory(String filePath) {
filePath = stripFileProtocol(filePath);
if (filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + cordova.getActivity().getPackageName() + "/cache") ||
if (filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + ctx.getPackageName() + "/cache") ||
filePath.equals(Environment.getExternalStorageDirectory().getAbsolutePath()) ||
filePath.equals("/data/data/" + cordova.getActivity().getPackageName())) {
filePath.equals("/data/data/" + ctx.getPackageName())) {
return true;
}
return false;
@@ -794,7 +791,7 @@ public class FileUtils extends Plugin {
throw new FileNotFoundException("File: " + filePath + " does not exist.");
}
JSONObject metadata = new JSONObject();
JSONObject metadata = new JSONObject();
metadata.put("size", file.length());
metadata.put("type", getMimeType(filePath));
metadata.put("name", file.getName());
@@ -819,16 +816,16 @@ public class FileUtils extends Plugin {
fs.put("name", "temporary");
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
fp = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Android/data/" + cordova.getActivity().getPackageName() + "/cache/");
"/Android/data/" + ctx.getPackageName() + "/cache/");
// Create the cache dir if it doesn't exist.
fp.mkdirs();
fs.put("root", getEntry(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/Android/data/" + cordova.getActivity().getPackageName() + "/cache/"));
"/Android/data/" + ctx.getPackageName() + "/cache/"));
} else {
fp = new File("/data/data/" + cordova.getActivity().getPackageName() + "/cache/");
fp = new File("/data/data/" + ctx.getPackageName() + "/cache/");
// Create the cache dir if it doesn't exist.
fp.mkdirs();
fs.put("root", getEntry("/data/data/" + cordova.getActivity().getPackageName() + "/cache/"));
fs.put("root", getEntry("/data/data/" + ctx.getPackageName() + "/cache/"));
}
}
else if (type == PERSISTENT) {
@@ -836,7 +833,7 @@ public class FileUtils extends Plugin {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
fs.put("root", getEntry(Environment.getExternalStorageDirectory()));
} else {
fs.put("root", getEntry("/data/data/" + cordova.getActivity().getPackageName()));
fs.put("root", getEntry("/data/data/" + ctx.getPackageName()));
}
}
else {
@@ -943,7 +940,7 @@ public class FileUtils extends Plugin {
String contentType = null;
if (filename.startsWith("content:")) {
Uri fileUri = Uri.parse(filename);
contentType = this.cordova.getActivity().getContentResolver().getType(fileUri);
contentType = this.ctx.getContentResolver().getType(fileUri);
}
else {
contentType = getMimeType(filename);
@@ -962,7 +959,7 @@ public class FileUtils extends Plugin {
*/
public static String getMimeType(String filename) {
MimeTypeMap map = MimeTypeMap.getSingleton();
return map.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(filename));
return map.getMimeTypeFromExtension(map.getFileExtensionFromUrl(filename));
}
/**
@@ -983,7 +980,7 @@ public class FileUtils extends Plugin {
append = true;
}
byte[] rawData = data.getBytes();
byte [] rawData = data.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
FileOutputStream out = new FileOutputStream(filename, append);
byte buff[] = new byte[rawData.length];
@@ -1008,9 +1005,9 @@ public class FileUtils extends Plugin {
RandomAccessFile raf = new RandomAccessFile(filename, "rw");
if (raf.length() >= size) {
FileChannel channel = raf.getChannel();
channel.truncate(size);
return size;
FileChannel channel = raf.getChannel();
channel.truncate(size);
return size;
}
return raf.length();
@@ -1026,7 +1023,7 @@ public class FileUtils extends Plugin {
private InputStream getPathFromUri(String path) throws FileNotFoundException {
if (path.startsWith("content")) {
Uri uri = Uri.parse(path);
return cordova.getActivity().getContentResolver().openInputStream(uri);
return ctx.getContentResolver().openInputStream(uri);
}
else {
path = stripFileProtocol(path);
@@ -1038,13 +1035,12 @@ public class FileUtils extends Plugin {
* 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 applicaiton context
* @param ctx the current applicaiton context
* @return the full path to the file
*/
@SuppressWarnings("deprecation")
protected static String getRealPathFromURI(Uri contentUri, CordovaInterface cordova) {
protected static String getRealPathFromURI(Uri contentUri, CordovaInterface ctx) {
String[] proj = { _DATA };
Cursor cursor = cordova.getActivity().managedQuery(contentUri, proj, null, null, null);
Cursor cursor = ctx.managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(_DATA);
cursor.moveToFirst();
return cursor.getString(column_index);

View File

@@ -55,7 +55,7 @@ public class GeoBroker extends Plugin {
*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
if (this.locationManager == null) {
this.locationManager = (LocationManager) this.cordova.getActivity().getSystemService(Context.LOCATION_SERVICE);
this.locationManager = (LocationManager) this.ctx.getSystemService(Context.LOCATION_SERVICE);
this.networkListener = new NetworkListener(this.locationManager, this);
this.gpsListener = new GPSListener(this.locationManager, this);
}
@@ -141,47 +141,46 @@ public class GeoBroker extends Plugin {
o.put("latitude", loc.getLatitude());
o.put("longitude", loc.getLongitude());
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("accuracy", loc.getAccuracy());
o.put("heading", (loc.hasBearing() ? (loc.hasSpeed() ? loc.getBearing() : null) : null));
o.put("speed", loc.getSpeed());
o.put("timestamp", loc.getTime());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return o;
}
}
public void win(Location loc, String callbackId) {
PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(loc));
this.success(result, callbackId);
}
/**
* Location failed. Send error back to JavaScript.
*
* @param code The error code
* @param msg The error message
* @throws JSONException
*/
public void fail(int code, String msg, String callbackId) {
JSONObject obj = new JSONObject();
String backup = null;
try {
obj.put("code", code);
obj.put("message", msg);
} catch (JSONException e) {
obj = null;
backup = "{'code':" + code + ",'message':'" + msg.replaceAll("'", "\'") + "'}";
}
PluginResult result;
if (obj != null) {
result = new PluginResult(PluginResult.Status.ERROR, obj);
} else {
result = new PluginResult(PluginResult.Status.ERROR, backup);
}
public void win(Location loc, String callbackId) {
PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(loc));
this.success(result, callbackId);
}
/**
* Location failed. Send error back to JavaScript.
*
* @param code The error code
* @param msg The error message
* @throws JSONException
*/
public void fail(int code, String msg, String callbackId) {
JSONObject obj = new JSONObject();
String backup = null;
try {
obj.put("code", code);
obj.put("message", msg);
} catch (JSONException e) {
obj = null;
backup = "{'code':" + code + ",'message':'" + msg.replaceAll("'", "\'") + "'}";
}
PluginResult result;
if (obj != null) {
result = new PluginResult(PluginResult.Status.ERROR, obj);
} else {
result = new PluginResult(PluginResult.Status.ERROR, backup);
}
this.error(result, callbackId);
}
this.error(result, callbackId);
}
}

View File

@@ -34,16 +34,10 @@ public class HttpHandler {
HttpEntity entity = getHttpEntity(url);
try {
writeToDisk(entity, file);
} catch (Exception e) {
e.printStackTrace();
return false;
}
} catch (Exception e) { e.printStackTrace(); return false; }
try {
entity.consumeContent();
} catch (Exception e) {
e.printStackTrace();
return false;
}
} catch (Exception e) { e.printStackTrace(); return false; }
return true;
}
@@ -52,7 +46,7 @@ public class HttpHandler {
* get the http entity at a given url
*/
{
HttpEntity entity = null;
HttpEntity entity=null;
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
@@ -67,18 +61,18 @@ public class HttpHandler {
* writes a HTTP entity to the specified filename and location on disk
*/
{
//int i = 0;
String FilePath = "/sdcard/" + file;
int i=0;
String FilePath="/sdcard/" + file;
InputStream in = entity.getContent();
byte buff[] = new byte[1024];
FileOutputStream out =
new FileOutputStream(FilePath);
do {
FileOutputStream out=
new FileOutputStream(FilePath);
do {
int numread = in.read(buff);
if (numread <= 0)
break;
out.write(buff, 0, numread);
//i++;
i++;
} while (true);
out.flush();
out.close();

View File

@@ -17,11 +17,9 @@
under the License.
*/
package org.apache.cordova;
import org.apache.cordova.api.LOG;
import android.content.Context;
//import android.view.View.MeasureSpec;
import android.widget.LinearLayout;
/**
@@ -77,7 +75,7 @@ public class LinearLayoutSoftKeyboardDetect extends LinearLayout {
LOG.d(TAG, "Ignore this event");
}
// Account for orientation change and ignore this event/Fire orientation change
else if (screenHeight == width)
else if(screenHeight == width)
{
int tmp_var = screenHeight;
screenHeight = screenWidth;
@@ -87,14 +85,14 @@ public class LinearLayoutSoftKeyboardDetect extends LinearLayout {
// If the height as gotten bigger then we will assume the soft keyboard has
// gone away.
else if (height > oldHeight) {
if (app != null)
app.appView.sendJavascript("cordova.fireDocumentEvent('hidekeyboard');");
if(app != null)
app.sendJavascript("cordova.fireDocumentEvent('hidekeyboard');");
}
// If the height as gotten smaller then we will assume the soft keyboard has
// If the height as gotten smaller then we will assume the soft keyboard has
// been displayed.
else if (height < oldHeight) {
if (app != null)
app.appView.sendJavascript("cordova.fireDocumentEvent('showkeyboard');");
if(app != null)
app.sendJavascript("cordova.fireDocumentEvent('showkeyboard');");
}
// Update the old height for the next event

View File

@@ -23,6 +23,7 @@ import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -76,7 +77,7 @@ public class NetworkManager extends Plugin {
/**
* Constructor.
*/
public NetworkManager() {
public NetworkManager() {
this.receiver = null;
}
@@ -84,25 +85,24 @@ public class NetworkManager extends Plugin {
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param ctx The context of the main Activity.
*/
public void setContext(CordovaInterface cordova) {
super.setContext(cordova);
this.sockMan = (ConnectivityManager) cordova.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
public void setContext(CordovaInterface ctx) {
super.setContext(ctx);
this.sockMan = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
this.connectionCallbackId = null;
// We need to listen to connectivity events to update navigator.connection
IntentFilter intentFilter = new IntentFilter();
IntentFilter intentFilter = new IntentFilter() ;
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
if (this.receiver == null) {
this.receiver = new BroadcastReceiver() {
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
updateConnectionInfo((NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO));
}
};
cordova.getActivity().registerReceiver(this.receiver, intentFilter);
ctx.registerReceiver(this.receiver, intentFilter);
}
}
@@ -146,7 +146,7 @@ public class NetworkManager extends Plugin {
public void onDestroy() {
if (this.receiver != null) {
try {
this.cordova.getActivity().unregisterReceiver(this.receiver);
this.ctx.unregisterReceiver(this.receiver);
} catch (Exception e) {
Log.e(LOG_TAG, "Error unregistering network receiver: " + e.getMessage(), e);
}
@@ -157,6 +157,7 @@ public class NetworkManager extends Plugin {
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Updates the JavaScript side whenever the connection changes
*
@@ -199,7 +200,7 @@ public class NetworkManager extends Plugin {
this.success(result, this.connectionCallbackId);
// Send to all plugins
webView.postMessage("networkconnection", type);
this.ctx.postMessage("networkconnection", type);
}
/**
@@ -223,7 +224,7 @@ public class NetworkManager extends Plugin {
return TYPE_2G;
}
else if (type.toLowerCase().startsWith(CDMA) ||
type.toLowerCase().equals(UMTS) ||
type.toLowerCase().equals(UMTS) ||
type.toLowerCase().equals(ONEXRTT) ||
type.toLowerCase().equals(EHRPD) ||
type.toLowerCase().equals(HSUPA) ||

View File

@@ -37,330 +37,330 @@ import android.os.Vibrator;
*/
public class Notification extends Plugin {
public int confirmResult = -1;
public ProgressDialog spinnerDialog = null;
public ProgressDialog progressDialog = null;
public int confirmResult = -1;
public ProgressDialog spinnerDialog = null;
public ProgressDialog progressDialog = null;
/**
* Constructor.
*/
public Notification() {
/**
* Constructor.
*/
public Notification() {
}
/**
* 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 PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("beep")) {
this.beep(args.getLong(0));
}
else if (action.equals("vibrate")) {
this.vibrate(args.getLong(0));
}
else if (action.equals("alert")) {
this.alert(args.getString(0),args.getString(1),args.getString(2), callbackId);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
else if (action.equals("confirm")) {
this.confirm(args.getString(0),args.getString(1),args.getString(2), callbackId);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
else if (action.equals("activityStart")) {
this.activityStart(args.getString(0),args.getString(1));
}
else if (action.equals("activityStop")) {
this.activityStop();
}
else if (action.equals("progressStart")) {
this.progressStart(args.getString(0),args.getString(1));
}
else if (action.equals("progressValue")) {
this.progressValue(args.getInt(0));
}
else if (action.equals("progressStop")) {
this.progressStop();
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
/**
* 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 PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("beep")) {
this.beep(args.getLong(0));
}
else if (action.equals("vibrate")) {
this.vibrate(args.getLong(0));
}
else if (action.equals("alert")) {
this.alert(args.getString(0), args.getString(1), args.getString(2), callbackId);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
else if (action.equals("confirm")) {
this.confirm(args.getString(0), args.getString(1), args.getString(2), callbackId);
PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
r.setKeepCallback(true);
return r;
}
else if (action.equals("activityStart")) {
this.activityStart(args.getString(0), args.getString(1));
}
else if (action.equals("activityStop")) {
this.activityStop();
}
else if (action.equals("progressStart")) {
this.progressStart(args.getString(0), args.getString(1));
}
else if (action.equals("progressValue")) {
this.progressValue(args.getInt(0));
}
else if (action.equals("progressStop")) {
this.progressStop();
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
/**
* 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("alert")) {
return true;
}
/**
* 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("alert")) {
return true;
}
else if (action.equals("confirm")) {
return true;
}
else if (action.equals("activityStart")) {
return true;
}
else if (action.equals("activityStop")) {
return true;
}
else if (action.equals("progressStart")) {
return true;
}
else if (action.equals("progressValue")) {
return true;
}
else if (action.equals("progressStop")) {
return true;
}
else {
return false;
}
else if (action.equals("confirm")) {
return true;
}
else if (action.equals("activityStart")) {
return true;
}
else if (action.equals("activityStop")) {
return true;
}
else if (action.equals("progressStart")) {
return true;
}
else if (action.equals("progressValue")) {
return true;
}
else if (action.equals("progressStop")) {
return true;
}
else {
return false;
}
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Beep plays the default notification ringtone.
*
* @param count Number of times to play notification
*/
public void beep(long count) {
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone notification = RingtoneManager.getRingtone(this.cordova.getActivity().getBaseContext(), ringtone);
/**
* Beep plays the default notification ringtone.
*
* @param count Number of times to play notification
*/
public void beep(long count) {
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone notification = RingtoneManager.getRingtone(this.ctx.getContext(), ringtone);
// If phone is not set to silent mode
if (notification != null) {
for (long i = 0; i < count; ++i) {
notification.play();
long timeout = 5000;
while (notification.isPlaying() && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
// If phone is not set to silent mode
if (notification != null) {
for (long i = 0; i < count; ++i) {
notification.play();
long timeout = 5000;
while (notification.isPlaying() && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
}
}
/**
* Vibrates the device for the specified amount of time.
*
* @param time Time to vibrate in ms.
*/
public void vibrate(long time) {
/**
* Vibrates the device for the specified amount of time.
*
* @param time Time to vibrate in ms.
*/
public void vibrate(long time){
// Start the vibration, 0 defaults to half a second.
if (time == 0) {
time = 500;
}
Vibrator vibrator = (Vibrator) this.cordova.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
if (time == 0) {
time = 500;
}
Vibrator vibrator = (Vibrator) this.ctx.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(time);
}
}
/**
* Builds and shows a native Android alert with given Strings
* @param message The message the alert should display
* @param title The title of the alert
* @param buttonLabel The label of the button
* @param callbackId The callback id
*/
public synchronized void alert(final String message, final String title, final String buttonLabel, final String callbackId) {
/**
* Builds and shows a native Android alert with given Strings
* @param message The message the alert should display
* @param title The title of the alert
* @param buttonLabel The label of the button
* @param callbackId The callback id
*/
public synchronized void alert(final String message, final String title, final String buttonLabel, final String callbackId) {
final CordovaInterface cordova = this.cordova;
final Notification notification = this;
final CordovaInterface ctx = this.ctx;
final Notification notification = this;
Runnable runnable = new Runnable() {
public void run() {
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(cordova.getActivity());
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
dlg.setPositiveButton(buttonLabel,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 0), callbackId);
}
});
dlg.create();
dlg.show();
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx.getContext());
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
dlg.setPositiveButton(buttonLabel,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 0), callbackId);
}
});
dlg.create();
dlg.show();
};
};
this.ctx.runOnUiThread(runnable);
}
/**
* Builds and shows a native Android confirm dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The index of the button pressed will be returned to the JavaScript callback identified by callbackId.
*
* @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 callbackId The callback id
*/
public synchronized void confirm(final String message, final String title, String buttonLabels, final String callbackId) {
/**
* Builds and shows a native Android confirm dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The index of the button pressed will be returned to the JavaScript callback identified by callbackId.
*
* @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 callbackId The callback id
*/
public synchronized void confirm(final String message, final String title, String buttonLabels, final String callbackId) {
final CordovaInterface cordova = this.cordova;
final Notification notification = this;
final String[] fButtons = buttonLabels.split(",");
final CordovaInterface ctx = this.ctx;
final Notification notification = this;
final String[] fButtons = buttonLabels.split(",");
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(cordova.getActivity());
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = new AlertDialog.Builder(ctx.getContext());
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(false);
// First button
if (fButtons.length > 0) {
dlg.setNegativeButton(fButtons[0],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 1), callbackId);
}
});
}
// Second button
if (fButtons.length > 1) {
dlg.setNeutralButton(fButtons[1],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 2), callbackId);
}
});
}
// Third button
if (fButtons.length > 2) {
dlg.setPositiveButton(fButtons[2],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 3), callbackId);
}
}
);
}
dlg.create();
dlg.show();
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Show the spinner.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void activityStart(final String title, final String message) {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
final Notification notification = this;
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
notification.spinnerDialog = ProgressDialog.show(cordova.getActivity(), title, message, true, true,
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.spinnerDialog = null;
}
});
// First button
if (fButtons.length > 0) {
dlg.setNegativeButton(fButtons[0],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 1), callbackId);
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Stop spinner.
*/
public synchronized void activityStop() {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
});
}
}
/**
* Show the progress dialog.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void progressStart(final String title, final String message) {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
final Notification notification = this;
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
notification.progressDialog = new ProgressDialog(cordova.getActivity());
notification.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
notification.progressDialog.setTitle(title);
notification.progressDialog.setMessage(message);
notification.progressDialog.setCancelable(true);
notification.progressDialog.setMax(100);
notification.progressDialog.setProgress(0);
notification.progressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.progressDialog = null;
}
});
notification.progressDialog.show();
// Second button
if (fButtons.length > 1) {
dlg.setNeutralButton(fButtons[1],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 2), callbackId);
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Set value of progress bar.
*
* @param value 0-100
*/
public synchronized void progressValue(int value) {
if (this.progressDialog != null) {
this.progressDialog.setProgress(value);
});
}
}
/**
* Stop progress dialog.
*/
public synchronized void progressStop() {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
// Third button
if (fButtons.length > 2) {
dlg.setPositiveButton(fButtons[2],
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
notification.success(new PluginResult(PluginResult.Status.OK, 3), callbackId);
}
}
);
}
dlg.create();
dlg.show();
};
};
this.ctx.runOnUiThread(runnable);
}
/**
* Show the spinner.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void activityStart(final String title, final String message) {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
final Notification notification = this;
final CordovaInterface ctx = this.ctx;
Runnable runnable = new Runnable() {
public void run() {
notification.spinnerDialog = ProgressDialog.show(ctx.getContext(), title , message, true, true,
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.spinnerDialog = null;
}
});
}
};
this.ctx.runOnUiThread(runnable);
}
/**
* Stop spinner.
*/
public synchronized void activityStop() {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
}
/**
* Show the progress dialog.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void progressStart(final String title, final String message) {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
final Notification notification = this;
final CordovaInterface ctx = this.ctx;
Runnable runnable = new Runnable() {
public void run() {
notification.progressDialog = new ProgressDialog(ctx.getContext());
notification.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
notification.progressDialog.setTitle(title);
notification.progressDialog.setMessage(message);
notification.progressDialog.setCancelable(true);
notification.progressDialog.setMax(100);
notification.progressDialog.setProgress(0);
notification.progressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.progressDialog = null;
}
});
notification.progressDialog.show();
}
};
this.ctx.runOnUiThread(runnable);
}
/**
* Set value of progress bar.
*
* @param value 0-100
*/
public synchronized void progressValue(int value) {
if (this.progressDialog != null) {
this.progressDialog.setProgress(value);
}
}
/**
* Stop progress dialog.
*/
public synchronized void progressStop() {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
}
}

View File

@@ -16,22 +16,19 @@
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova;
package org.apache.cordova.test;
// represents the <preference> element from the W3C config.xml spec
// see http://www.w3.org/TR/widgets/#the-preference-element-and-its-attributes
public class PreferenceNode {
public String name;
public String value;
public boolean readonly;
import org.openqa.selenium.android.library.ViewAdapter;
import org.openqa.selenium.android.library.ViewFactory;
import org.apache.cordova.CordovaWebView;
import android.app.Activity;
import android.webkit.WebView;
public class CordovaViewFactory implements ViewFactory {
public ViewAdapter createNewView(Activity arg0) {
// TODO Auto-generated method stub
return new ViewAdapter("org.apache.cordova.CordovaWebView", new CordovaWebView(arg0));
// constructor
public PreferenceNode(String name, String value, boolean readonly) {
this.name = name;
this.value = value;
this.readonly = readonly;
}
}

View File

@@ -0,0 +1,62 @@
/*
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.HashSet;
import org.apache.cordova.PreferenceNode;
public class PreferenceSet {
private HashSet<PreferenceNode> innerSet;
public PreferenceSet() {
this.innerSet = new HashSet<PreferenceNode>();
}
public void add(PreferenceNode node) {
this.innerSet.add(node);
}
public int size() {
return this.innerSet.size();
}
public void clear() {
this.innerSet.clear();
}
public String pref(String prefName) {
for (PreferenceNode n : innerSet)
if (prefName.equals(n.name))
return n.value;
return null;
}
public boolean prefMatches(String prefName, String prefValue) {
String value = pref(prefName);
if (value == null) {
return false;
} else {
return value.equals(prefValue);
}
}
}

View File

@@ -31,9 +31,7 @@ public class SplashScreen extends Plugin {
String result = "";
if (action.equals("hide")) {
this.webView.postMessage("splashscreen", "hide");
} else if (action.equals("show")){
this.webView.postMessage("splashscreen", "show");
((DroidGap)this.ctx).removeSplashScreen();
}
else {
status = PluginResult.Status.INVALID_ACTION;

View File

@@ -141,7 +141,7 @@ public class Storage extends Plugin {
// If no database path, generate from application package
if (this.path == null) {
this.path = this.cordova.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
this.path = this.ctx.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
}
this.dbName = this.path + File.pathSeparator + db + ".db";

View File

@@ -25,6 +25,7 @@ import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
@@ -46,16 +47,16 @@ public class TempListener extends Plugin implements SensorEventListener {
* Sets the context of the Command. This can then be used to do things like
* get file paths associated with the Activity.
*
* @param cordova The context of the main Activity.
* @param ctx The context of the main Activity.
*/
public void setContext(CordovaInterface cordova) {
super.setContext(cordova);
this.sensorManager = (SensorManager) cordova.getActivity().getSystemService(Context.SENSOR_SERVICE);
public void setContext(CordovaInterface ctx) {
super.setContext(ctx);
this.sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
}
/**
* 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.
@@ -86,8 +87,7 @@ public class TempListener extends Plugin implements SensorEventListener {
// LOCAL METHODS
//--------------------------------------------------------------------------
public void start() {
@SuppressWarnings("deprecation")
public void start() {
List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_TEMPERATURE);
if (list.size() > 0) {
this.mSensor = list.get(0);

View File

@@ -18,8 +18,18 @@
*/
package org.apache.cordova.api;
import android.app.Activity;
import java.util.HashMap;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
/**
* The Cordova activity abstract class that is extended by DroidGap.
@@ -27,41 +37,108 @@ import android.content.Intent;
*/
public interface CordovaInterface {
/**
* @deprecated
* Add services to res/xml/plugins.xml instead.
*
* Add a class that implements a service.
*
* @param serviceType
* @param className
*/
@Deprecated
abstract public void addService(String serviceType, String className);
/**
* Send JavaScript statement back to JavaScript.
*
* @param message
*/
abstract public void sendJavascript(String statement);
/**
* Launch an activity for which you would like a result when it finished. When this activity exits,
* your onActivityResult() method will be called.
*
* @param command The command object
* @param intent The intent to start
* @param requestCode The request code that is passed to callback to identify the activity
* @param command The command object
* @param intent The intent to start
* @param requestCode The request code that is passed to callback to identify the activity
*/
abstract public void startActivityForResult(IPlugin command, Intent intent, int requestCode);
/**
* Launch an activity for which you would not like a result when it finished.
*
* @param intent The intent to start
*/
abstract public void startActivity(Intent intent);
/**
* Set the plugin to be called when a sub-activity exits.
*
* @param plugin The plugin on which onActivityResult is to be called
* @param plugin The plugin on which onActivityResult is to be called
*/
abstract public void setActivityResultCallback(IPlugin plugin);
/**
* Get the Android activity.
* Load the specified URL in the Cordova webview.
*
* @return
* @param url The URL to load.
*/
public abstract Activity getActivity();
@Deprecated
public abstract void cancelLoadUrl();
abstract public void loadUrl(String url);
/**
* Called when a message is sent to plugin.
* Send a message to all plugins.
*
* @param id The message id
* @param data The message data
* @return Object or null
*/
public Object onMessage(String id, Object data);
abstract public void postMessage(String id, Object data);
public abstract Resources getResources();
public abstract String getPackageName();
public abstract Object getSystemService(String service);
public abstract Context getContext();
public abstract Context getBaseContext();
public abstract Intent registerReceiver(BroadcastReceiver receiver,
IntentFilter intentFilter);
public abstract ContentResolver getContentResolver();
public abstract void unregisterReceiver(BroadcastReceiver receiver);
public abstract Cursor managedQuery(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder);
public abstract void runOnUiThread(Runnable runnable);
public abstract AssetManager getAssets();
public abstract void clearCache();
public abstract void clearHistory();
public abstract boolean backHistory();
//public abstract void addWhiteListEntry(String origin, boolean subdomains);
public abstract void bindBackButton(boolean override);
public abstract boolean isBackButtonBound();
public abstract void cancelLoadUrl();
public abstract void showWebPage(String url, boolean openExternal,
boolean clearHistory, HashMap<String, Object> params);
public abstract Context getApplicationContext();
public abstract boolean isUrlWhiteListed(String source);
}

View File

@@ -18,11 +18,9 @@
*/
package org.apache.cordova.api;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
//import android.content.Context;
import android.content.Intent;
import android.webkit.WebView;
/**
* Plugin interface must be implemented by any plugin classes.
@@ -52,18 +50,18 @@ public interface IPlugin {
/**
* 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.
*/
void setContext(CordovaInterface ctx);
/**
* Sets the main View of the application, this is the WebView within which
* Sets the main View of the application, this is the WebView within which
* a Cordova app runs.
*
*
* @param webView The Cordova WebView
*/
void setView(CordovaWebView webView);
void setView(WebView webView);
/**
* Called when the system is about to start resuming a previous activity.
@@ -94,9 +92,8 @@ public interface IPlugin {
*
* @param id The message id
* @param data The message data
* @return Object to stop propagation or null
*/
public Object onMessage(String id, Object data);
public void onMessage(String id, Object data);
/**
* Called when an activity you launched exits, giving you the requestCode you started it with,

View File

@@ -18,10 +18,11 @@
*/
package org.apache.cordova.api;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Intent;
import android.webkit.WebView;
/**
* Plugin interface must be implemented by any plugin classes.
@@ -31,13 +32,12 @@ import android.content.Intent;
public abstract class Plugin implements IPlugin {
public String id;
public CordovaWebView webView; // WebView object
public CordovaInterface ctx; // CordovaActivity object
public CordovaInterface cordova;
public WebView webView; // WebView object
public CordovaInterface ctx; // CordovaActivity object
/**
* 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.
@@ -62,23 +62,22 @@ public abstract class Plugin implements IPlugin {
* @param ctx The context of the main Activity.
*/
public void setContext(CordovaInterface ctx) {
this.cordova = ctx;
this.ctx = cordova;
this.ctx = ctx;
}
/**
* Sets the main View of the application, this is the WebView within which
* 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) {
public void setView(WebView webView) {
this.webView = webView;
}
/**
* Called when the system is about to start resuming a previous activity.
*
* Called when the system is about to start resuming a previous activity.
*
* @param multitasking Flag indicating if multitasking is turned on for app
*/
public void onPause(boolean multitasking) {
@@ -109,10 +108,8 @@ public abstract class Plugin implements IPlugin {
*
* @param id The message id
* @param data The message data
* @return Object to stop propagation or null
*/
public Object onMessage(String id, Object data) {
return null;
public void onMessage(String id, Object data) {
}
/**
@@ -144,7 +141,7 @@ public abstract class Plugin implements IPlugin {
* @param statement
*/
public void sendJavascript(String statement) {
this.webView.sendJavascript(statement);
this.ctx.sendJavascript(statement);
}
/**
@@ -158,7 +155,7 @@ public abstract class Plugin implements IPlugin {
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void success(PluginResult pluginResult, String callbackId) {
this.webView.sendJavascript(pluginResult.toSuccessCallbackString(callbackId));
this.ctx.sendJavascript(pluginResult.toSuccessCallbackString(callbackId));
}
/**
@@ -168,7 +165,7 @@ public abstract class Plugin implements IPlugin {
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void success(JSONObject message, String callbackId) {
this.webView.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId));
this.ctx.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId));
}
/**
@@ -178,7 +175,7 @@ public abstract class Plugin implements IPlugin {
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void success(String message, String callbackId) {
this.webView.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId));
this.ctx.sendJavascript(new PluginResult(PluginResult.Status.OK, message).toSuccessCallbackString(callbackId));
}
/**
@@ -188,7 +185,7 @@ public abstract class Plugin implements IPlugin {
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void error(PluginResult pluginResult, String callbackId) {
this.webView.sendJavascript(pluginResult.toErrorCallbackString(callbackId));
this.ctx.sendJavascript(pluginResult.toErrorCallbackString(callbackId));
}
/**
@@ -198,7 +195,7 @@ public abstract class Plugin implements IPlugin {
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void error(JSONObject message, String callbackId) {
this.webView.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId));
this.ctx.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId));
}
/**
@@ -208,6 +205,6 @@ public abstract class Plugin implements IPlugin {
* @param callbackId The callback id used when calling back into JavaScript.
*/
public void error(String message, String callbackId) {
this.webView.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId));
this.ctx.sendJavascript(new PluginResult(PluginResult.Status.ERROR, message).toErrorCallbackString(callbackId));
}
}

View File

@@ -18,10 +18,7 @@
*/
package org.apache.cordova.api;
import org.apache.cordova.CordovaWebView;
//import android.content.Context;
//import android.webkit.WebView;
import android.webkit.WebView;
/**
* This class represents a service entry object.
@@ -69,12 +66,12 @@ public class PluginEntry {
*
* @return The plugin object
*/
public IPlugin createPlugin(CordovaWebView webView, CordovaInterface ctx) {
@SuppressWarnings("unchecked")
public IPlugin createPlugin(WebView webView, CordovaInterface ctx) {
if (this.plugin != null) {
return this.plugin;
}
try {
@SuppressWarnings("rawtypes")
Class c = getClassByName(this.pluginClass);
if (isCordovaPlugin(c)) {
this.plugin = (IPlugin) c.newInstance();
@@ -96,7 +93,7 @@ public class PluginEntry {
* @return
* @throws ClassNotFoundException
*/
@SuppressWarnings("rawtypes")
@SuppressWarnings("unchecked")
private Class getClassByName(final String clazz) throws ClassNotFoundException {
Class c = null;
if (clazz != null) {
@@ -112,7 +109,7 @@ public class PluginEntry {
* @param c The class to check the interfaces of.
* @return Boolean indicating if the class implements org.apache.cordova.api.Plugin
*/
@SuppressWarnings("rawtypes")
@SuppressWarnings("unchecked")
private boolean isCordovaPlugin(Class c) {
if (c != null) {
return org.apache.cordova.api.Plugin.class.isAssignableFrom(c) || org.apache.cordova.api.IPlugin.class.isAssignableFrom(c);

View File

@@ -23,13 +23,13 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
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.webkit.WebView;
/**
* PluginManager is exposed to JavaScript in the Cordova WebView.
@@ -44,7 +44,7 @@ public class PluginManager {
private final HashMap<String, PluginEntry> entries = new HashMap<String, PluginEntry>();
private final CordovaInterface ctx;
private final CordovaWebView app;
private final WebView app;
// Flag to track first time through
private boolean firstRun;
@@ -59,7 +59,7 @@ public class PluginManager {
* @param app
* @param ctx
*/
public PluginManager(CordovaWebView app, CordovaInterface ctx) {
public PluginManager(WebView app, CordovaInterface ctx) {
this.ctx = ctx;
this.app = app;
this.firstRun = true;
@@ -72,9 +72,9 @@ public class PluginManager {
LOG.d(TAG, "init()");
// If first time, then load plugins from plugins.xml file
if (this.firstRun) {
if (firstRun) {
this.loadPlugins();
this.firstRun = false;
firstRun = false;
}
// Stop plugins on current HTML page and discard plugin objects
@@ -92,11 +92,11 @@ public class PluginManager {
* Load plugins from res/xml/plugins.xml
*/
public void loadPlugins() {
int id = this.ctx.getActivity().getResources().getIdentifier("plugins", "xml", this.ctx.getActivity().getPackageName());
int id = ctx.getResources().getIdentifier("plugins", "xml", ctx.getPackageName());
if (id == 0) {
this.pluginConfigurationMissing();
pluginConfigurationMissing();
}
XmlResourceParser xml = this.ctx.getActivity().getResources().getXml(id);
XmlResourceParser xml = ctx.getResources().getXml(id);
int eventType = -1;
String service = "", pluginClass = "";
boolean onload = false;
@@ -167,13 +167,14 @@ public class PluginManager {
*
* @return JSON encoded string with a response message and status.
*/
@SuppressWarnings("unchecked")
public String exec(final String service, final String action, final String callbackId, final String jsonArgs, final boolean async) {
PluginResult cr = null;
boolean runAsync = async;
try {
final JSONArray args = new JSONArray(jsonArgs);
final IPlugin plugin = this.getPlugin(service);
//final CordovaInterface ctx = this.ctx;
final CordovaInterface ctx = this.ctx;
if (plugin != null) {
runAsync = async && !plugin.isSynch(action);
if (runAsync) {
@@ -191,16 +192,16 @@ public class PluginManager {
// Check the success (OK, NO_RESULT & !KEEP_CALLBACK)
else if ((status == PluginResult.Status.OK.ordinal()) || (status == PluginResult.Status.NO_RESULT.ordinal())) {
app.sendJavascript(cr.toSuccessCallbackString(callbackId));
ctx.sendJavascript(cr.toSuccessCallbackString(callbackId));
}
// If error
else {
app.sendJavascript(cr.toErrorCallbackString(callbackId));
ctx.sendJavascript(cr.toErrorCallbackString(callbackId));
}
} catch (Exception e) {
PluginResult cr = new PluginResult(PluginResult.Status.ERROR, e.getMessage());
app.sendJavascript(cr.toErrorCallbackString(callbackId));
ctx.sendJavascript(cr.toErrorCallbackString(callbackId));
}
}
});
@@ -225,7 +226,7 @@ public class PluginManager {
if (cr == null) {
cr = new PluginResult(PluginResult.Status.CLASS_NOT_FOUND_EXCEPTION);
}
app.sendJavascript(cr.toErrorCallbackString(callbackId));
ctx.sendJavascript(cr.toErrorCallbackString(callbackId));
}
return (cr != null ? cr.getJSONString() : "{ status: 0, message: 'all good' }");
}
@@ -239,7 +240,7 @@ public class PluginManager {
* @return IPlugin or null
*/
private IPlugin getPlugin(String service) {
PluginEntry entry = this.entries.get(service);
PluginEntry entry = entries.get(service);
if (entry == null) {
return null;
}
@@ -314,22 +315,13 @@ public class PluginManager {
*
* @param id The message id
* @param data The message data
* @return
*/
public Object postMessage(String id, Object data) {
Object obj = this.ctx.onMessage(id, data);
if (obj != null) {
return obj;
}
public void postMessage(String id, Object data) {
for (PluginEntry entry : this.entries.values()) {
if (entry.plugin != null) {
obj = entry.plugin.onMessage(id, data);
if (obj != null) {
return obj;
}
entry.plugin.onMessage(id, data);
}
}
return null;
}
/**

View File

@@ -25,13 +25,12 @@ public class PluginResult {
private final int status;
private final String message;
private boolean keepCallback = false;
public PluginResult(Status status) {
this.status = status.ordinal();
this.message = "'" + PluginResult.StatusMessages[this.status] + "'";
}
public PluginResult(Status status, String message) {
this.status = status.ordinal();
this.message = JSONObject.quote(message);
@@ -61,11 +60,11 @@ public class PluginResult {
this.status = status.ordinal();
this.message = ""+b;
}
public void setKeepCallback(boolean b) {
this.keepCallback = b;
}
public int getStatus() {
return status;
}
@@ -73,23 +72,23 @@ public class PluginResult {
public String getMessage() {
return message;
}
public boolean getKeepCallback() {
return this.keepCallback;
}
public String getJSONString() {
return "{\"status\":" + this.status + ",\"message\":" + this.message + ",\"keepCallback\":" + this.keepCallback + "}";
}
public String toSuccessCallbackString(String callbackId) {
return "cordova.callbackSuccess('"+callbackId+"',"+this.getJSONString()+");";
}
public String toErrorCallbackString(String callbackId) {
return "cordova.callbackError('"+callbackId+"', " + this.getJSONString()+ ");";
}
public static String[] StatusMessages = new String[] {
"No result",
"OK",
@@ -102,7 +101,7 @@ public class PluginResult {
"JSON error",
"Error"
};
public enum Status {
NO_RESULT,
OK,

View File

@@ -1,29 +0,0 @@
# Cordova Upgrade Guide #
This document is for people who need to upgrade their Cordova versions from an older version to a current version of Cordova.
- To upgrade to 1.8.0, please go from 1.7.0
- To upgrade from 1.7.0, please go from 1.6.0
## Upgrade to 1.8.0 from 1.7.0 ##
1. Remove cordova-1.7.0.jar from the libs directory in your project
2. Add cordova-1.8.0.jar to the libs directory in your project
3. If you are using Eclipse, please refresh your eclipse project and do a clean
4. Copy the new cordova-1.7.0.js into your project
5. Update your HTML to sue the new cordova-1.7.0.js file
6. Update the res/xml/plugins.xml to be the same as the one found in framework/res/xml/plugins.xml
## Upgrade to 1.7.0 from 1.6.0 ##
1. Remove cordova-1.6.0.jar from the libs directory in your project
2. Add cordova-1.6.0.jar to the libs directory in your project
3. If you are using Eclipse, please refresh your eclipse project and do a clean
4. Copy the new cordova-1.6.0.js into your project
5. Update your HTML to sue the new cordova-1.6.0.js file
6. Update the res/xml/plugins.xml to be the same as the one found in framework/res/xml/plugins.xml

View File

@@ -1,53 +0,0 @@
# How to use Cordova as a component #
Beginning in Cordova 1.8, with the assistance of the CordovaActivity, you can use Cordova as a component in your Android applications. This component is known in Android
as the CordovaWebView, and new Cordova-based applications from 1.8 and greater will be using the CordovaWebView as its main view, whether the legacy DroidGap approach is
used or not.
The pre-requisites are the same as the pre-requisites for Android application development. It is assumed that you are familiar with Android Development. If not, please
look at the Getting Started guide to developing an Cordova Application and start there before continuing with this approach. Since this is not the main method that people use
to run applications, the instructions are currently manual. In the future, we may try to further automate the project generation.
## Pre-requisites ##
1. **Cordova 1.8** or greater downloaded
2. Android SDK updated with 15
## Guide to using CordovaWebView in an Android Project ##
1. Use bin/create to fetch the commons-codec-1.6.jar
2. Go into framework and run ant jar to build the cordova jar (currently cordova-1.8.jar at the time of writing)
3. Copy the cordova jar into your Android project libs directory
4. Edit your main.xml to look similar the following. The layout_height, layout_width and ID can be modified to suit your application:
` <org.apache.cordova.CordovaWebView$
android:id="@+id/tutorialView"$
android:layout_width="match_parent"$
android:layout_height="match_parent" />$
`
5. Modify your activity so that it implements the CordovaInterface. It is recommended that you implement the methods that are included. You may wish to copy the methods from framework/src/org/apache/cordova/DroidGap.java, or you may wish to implement your own methods. Below is a fragment of code from a basic application that uses the interface:
`
public class CordovaViewTestActivity extends Activity implements CordovaInterface {$
CordovaWebView phoneGap;$
$
/** Called when the activity is first created. */$
@Override$
public void onCreate(Bundle savedInstanceState) {$
super.onCreate(savedInstanceState);$
setContentView(R.layout.main);$
$
phoneGap = (CordovaWebView) findViewById(R.id.phoneGapView);$
$
phoneGap.loadUrl("file:///android_asset/www/index.html");$
}$
`
6. Copy the HTML and Javascript used to the assets directory of your Android project
7. Copy cordova.xml and plugins.xml from framework/res/xml to the framework/res/xml in your project

0
test/.classpath Normal file → Executable file
View File

2
test/.project Normal file → Executable file
View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>PhoneGapViewTestActivity</name>
<name>CordovaTest</name>
<comment></comment>
<projects>
</projects>

View File

@@ -20,20 +20,20 @@
<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">
<supports-screens
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true"
android:resizeable="true"
android:anyDensity="true"
/>
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true"
android:resizeable="true"
android:anyDensity="true"
/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
@@ -44,66 +44,21 @@
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-sdk android:minSdkVersion="7" />
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="org.apache.cordova.test" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<uses-library android:name="android.test.runner" />
<activity
android:windowSoftInputMode="adjustPan"
android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden"
android:name=".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" >
<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=".CordovaDriverAction" >
<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=".CordovaActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.SAMPLE_CODE" />
</intent-filter>
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:debuggable="true">
<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.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="splashscreen" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
android:configChanges="orientation|keyboardHidden">
</activity>
<activity android:name="timeout" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
@@ -144,14 +99,7 @@
<activity android:name="xhr" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
</activity>
<activity android:name="basicauth" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
</activity>
<activity android:name="fullscreen" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
</activity>
<activity android:name="backgroundcolor" android:label="@string/app_name"
android:configChanges="orientation|keyboardHidden">
</activity>
</application>
<uses-sdk android:minSdkVersion="5" />
</manifest>

View File

@@ -1,30 +1,23 @@
# Android Native Tests #
## Android Native Tests ##
These tests are designed to verify Android native features and other Android specific features.
## Initial Setup ##
Before running the tests, they need to be set up.
0. Copy cordova-x.y.z.jar into libs directory
1. Copy the version of cordova-x.y.z.js into assets/www directory
2. Edit assets/www/cordova.js to reference the correct version
3. Copy cordova-x.y.z.jar into libs directory
To run from command line:
0. Build by entering `ant debug install`
0. Run tests by clicking on "CordovaTest" icon on device
4. Build by entering "ant debug install"
5. Run tests by clicking on "CordovaTest" icon on device
To run from Eclipse:
0. Import Android project into Eclipse
0. Ensure Project properties "Java Build Path" includes the lib/cordova-x.y.z.jar
0. Create run configuration if not already created
0. Run tests
4. Import Android project into Eclipse
5. Ensure Project properties "Java Build Path" includes the lib/cordova-x.y.z.jar
6. Create run configuration if not already created
7. Run tests
## Automatic Runs ##
Once you have installed the test, you can launch and run the tests
automatically with the below command:
adb shell am instrument -w org.apache.cordova.test/android.test.InstrumentationTestRunner
(Optionally, you can also run in Eclipse)

View File

@@ -1,41 +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.
-->
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Cordova Tests</title>
<link rel="stylesheet" href="../master.css" type="text/css" media="screen" title="no title">
<script type="text/javascript" charset="utf-8" src="../cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="../main.js"></script>
</head>
<body onload="init();" id="stage" class="theme">
<h1>Background Color Test</h1>
<div id="info">
<h4>Platform: <span id="platform"> &nbsp;</span>, Version: <span id="version">&nbsp;</span></h4>
<h4>UUID: <span id="uuid"> &nbsp;</span>, Name: <span id="name">&nbsp;</span></h4>
<h4>Width: <span id="width"> &nbsp;</span>, Height: <span id="height">&nbsp;
</span>, Color Depth: <span id="colorDepth"></span></h4>
</div>
<div id="info">
Before this page was show, you should have seen the background flash green.</br>
</div>
</body>
</html>

View File

@@ -1,42 +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.
-->
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=320; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Cordova Tests</title>
<link rel="stylesheet" href="../master.css" type="text/css" media="screen" title="no title">
<script type="text/javascript" charset="utf-8" src="../cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="../main.js"></script>
</head>
<body onload="init();" id="stage" class="theme">
<h1>Basic Auth</h1>
<div id="info">
<h4>Platform: <span id="platform"> &nbsp;</span>, Version: <span id="version">&nbsp;</span></h4>
<h4>UUID: <span id="uuid"> &nbsp;</span>, Name: <span id="name">&nbsp;</span></h4>
<h4>Width: <span id="width"> &nbsp;</span>, Height: <span id="height">&nbsp;
</span>, Color Depth: <span id="colorDepth"></span></h4>
</div>
<div id="info">
Loading link below should be successful and show page indicating username=test & password=test. <br>
</div>
<a href="http://browserspy.dk/password-ok.php" class="btn large">Test password</a>
</body>
</html>

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