You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by de...@apache.org on 2012/02/08 21:14:02 UTC
[9/19] CB-226 Rename to Cordova.
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/notification/BeepAction.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/notification/BeepAction.java b/framework/ext/src/com/phonegap/notification/BeepAction.java
deleted file mode 100644
index 0cf6447..0000000
--- a/framework/ext/src/com/phonegap/notification/BeepAction.java
+++ /dev/null
@@ -1,160 +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 com.phonegap.notification;
-
-import java.io.IOException;
-
-import javax.microedition.media.Control;
-import javax.microedition.media.Manager;
-import javax.microedition.media.MediaException;
-import javax.microedition.media.Player;
-import javax.microedition.media.control.ToneControl;
-import javax.microedition.media.control.VolumeControl;
-
-import net.rim.device.api.media.control.AudioPathControl;
-import net.rim.device.api.notification.NotificationsManager;
-import net.rim.device.api.system.Alert;
-
-import com.phonegap.PhoneGapExtension;
-import com.phonegap.api.PluginResult;
-import com.phonegap.json4j.JSONArray;
-import com.phonegap.json4j.JSONException;
-import com.phonegap.util.Logger;
-
-/**
- * Beep Action plays a device tone.
- */
-public class BeepAction {
-
- private static final int BEEP_VOLUME = 100;
- private static final byte NOTE = 76; // E5
- private static final byte D = 16; // quarter note
- private static final byte tempo = 30; // 120 bpm
-
- private static final byte[] TONE_SEQUENCE_START = {
- ToneControl.VERSION, 1,
- ToneControl.TEMPO, tempo
- };
-
- private static final byte[] TONE = {
- NOTE,D, ToneControl.SILENCE,D/2
- };
-
- /**
- * Beeps the device for a given number of times. By default, it will beep
- * once. If the user explicitly sets the beep count to zero, it will play
- * the applications notification profile. The application profile playback
- * sequence is controlled by the user.
- *
- * @param args JSONArray formatted as [ count ]
- * count: specifies the number of times to beep the device (default: 1).
- * @return A CommandResult object with the success or failure
- * state for beeping the device.
- */
- public static PluginResult execute(JSONArray args) {
- PluginResult result = null;
-
- if (Alert.isAudioSupported()) {
-
- try {
- int repeatCount = 1;
- if (args.length() > 0 && !args.isNull(0)) {
- repeatCount = args.getInt(0);
- }
-
- // play tone n times
- if (repeatCount > 0) {
- playTone(repeatCount);
- }
- // FIXME: unsupported on other platforms
- // send notification event to application profile
- else {
- NotificationsManager.triggerImmediateEvent(
- PhoneGapExtension.getAppID(), 0, null, null);
- }
- }
- catch (JSONException e) {
- Logger.log(BeepAction.class.getName() + ": " + e);
- result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
- }
- catch (Exception e) {
- Logger.log(BeepAction.class.getName() + ": " + e);
- result = new PluginResult(PluginResult.Status.IO_EXCEPTION, e.getMessage());
- }
-
- result = new PluginResult(PluginResult.Status.OK);
- }
- else {
- result = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION, "Audio not supported");
- }
-
- return result;
- }
-
- /**
- * Plays a tone the specified number of times on the device audio system.
- * @param repeatCount number of times to play tone
- */
- private static void playTone(int repeatCount) throws MediaException, IOException {
-
- // get tone player
- Player p = Manager.createPlayer(Manager.TONE_DEVICE_LOCATOR);
- p.realize();
-
- // set tone sequence
- ToneControl tc = (ToneControl)p.getControl("ToneControl");
- tc.setSequence(getToneSequence(repeatCount));
-
- // crank up the volume
- VolumeControl vc = (VolumeControl)p.getControl("VolumeControl");
- vc.setLevel(BEEP_VOLUME);
-
- // route audio to speaker phone
- p.prefetch();
- Control[] c = p.getControls();
- for(int i=c.length-1; i>=0; --i) {
- if(c[i] instanceof AudioPathControl) {
- AudioPathControl apc = (AudioPathControl)c[i];
- apc.setAudioPath(AudioPathControl.AUDIO_PATH_HANDSFREE);
- break;
- }
- }
-
- // play
- p.start();
- }
-
- /**
- * Creates a tone sequence to play.
- * @param repeatCount number of times to play tone
- * @return tone sequence
- */
- private static byte[] getToneSequence(int repeatCount) {
- // we have to build the sequence dynamically because
- // ToneControl.REPEAT, repeatCount, TONE, DURATION
- // doesn't seem to work
- byte[] sequence = new byte[TONE_SEQUENCE_START.length + TONE.length * repeatCount];
- System.arraycopy(TONE_SEQUENCE_START, 0, sequence, 0, TONE_SEQUENCE_START.length);
- for (int i = 0; i < repeatCount; i++) {
- System.arraycopy(TONE, 0, sequence, (TONE_SEQUENCE_START.length+TONE.length*i), TONE.length);
- }
-
- return sequence;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/notification/ConfirmAction.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/notification/ConfirmAction.java b/framework/ext/src/com/phonegap/notification/ConfirmAction.java
deleted file mode 100644
index c061c11..0000000
--- a/framework/ext/src/com/phonegap/notification/ConfirmAction.java
+++ /dev/null
@@ -1,85 +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 com.phonegap.notification;
-
-import net.rim.device.api.ui.UiApplication;
-
-import com.phonegap.api.PluginResult;
-import com.phonegap.json4j.JSONArray;
-import com.phonegap.json4j.JSONException;
-import com.phonegap.util.Logger;
-
-/**
- * Displays a confirmation dialog with customizable title, message, and button
- * fields.
- */
-public class ConfirmAction {
-
- private static final String DEFAULT_MESSAGE = "";
- private static final String DEFAULT_TITLE = "Confirm";
- private static final String DEFAULT_BUTTONS = "OK,Cancel";
-
- /**
- * Displays a custom confirmation dialog.
- *
- * @param args JSONArray formatted as [ message, title, buttonLabels ]
- * message: the message to display in the dialog body (default: "").
- * title: the title to display at the top of the dialog (default: "Confirm").
- * buttonLabel: the button text (default: "OK,Cancel").
- * @return A PluginResult object with index of dialog button pressed (1,2,3...).
- */
- public static PluginResult execute(JSONArray args) {
-
- PluginResult result = null;
-
- try {
- String message = DEFAULT_MESSAGE;
- String title = DEFAULT_TITLE;
- String buttonLabels = DEFAULT_BUTTONS;
- if (args.length() > 0 && !args.isNull(0))
- message = args.getString(0);
- if (args.length() > 1 && !args.isNull(1))
- title = args.getString(1);
- if (args.length() > 2 && !args.isNull(2))
- buttonLabels = args.getString(2);
-
- // construct the dialog
- final ConfirmDialog dialog = new ConfirmDialog(message, title, buttonLabels);
-
- // ask the event dispatch thread to show it
- Runnable runnable = new Runnable() {
- public void run() {
- UiApplication ui = UiApplication.getUiApplication();
- ui.pushModalScreen(dialog);
- }
- };
- Logger.log(ConfirmAction.class.getName() + ": showing confirm dialog: '" + title + "'");
- UiApplication.getUiApplication().invokeAndWait(runnable);
-
- // add +1 to the button index to match the JavaScript API (which starts at 1)
- int button = dialog.getSelectedValue() + 1;
- result = new PluginResult(PluginResult.Status.OK, Integer.toString(button));
- }
- catch (JSONException e) {
- result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, "JSONException: " + e.getMessage());
- }
-
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/notification/ConfirmDialog.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/notification/ConfirmDialog.java b/framework/ext/src/com/phonegap/notification/ConfirmDialog.java
deleted file mode 100644
index 4a22fb8..0000000
--- a/framework/ext/src/com/phonegap/notification/ConfirmDialog.java
+++ /dev/null
@@ -1,100 +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 com.phonegap.notification;
-
-import com.phonegap.ui.SpacerField;
-import com.phonegap.util.StringUtils;
-
-import net.rim.device.api.ui.Field;
-import net.rim.device.api.ui.FieldChangeListener;
-import net.rim.device.api.ui.component.ButtonField;
-import net.rim.device.api.ui.component.LabelField;
-import net.rim.device.api.ui.component.SeparatorField;
-import net.rim.device.api.ui.container.PopupScreen;
-import net.rim.device.api.ui.container.VerticalFieldManager;
-
-/**
- * Creates a dialog box in which the title, message, and button labels are all
- * customizable.
- */
-public final class ConfirmDialog extends PopupScreen implements FieldChangeListener {
-
- private ButtonField[] buttons; // the button fields
- private int selectedValue = -1; // the selected button
-
- /**
- * Construct a confirmation dialog, with customizable title and button text.
- *
- * @param {String} message Message to print in the body of the alert
- * @param {String} title Title of the alert dialog (default: 'Confirm')
- * @param {String} buttonLabels Labels of the buttons (default: 'OK,Cancel')
- */
- public ConfirmDialog(String message, String title, String buttonLabels) {
- super(new VerticalFieldManager());
-
- // title
- add(new LabelField(title));
-
- // separator
- add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
-
- // message
- add(new SpacerField(0, 20));
- add(new LabelField(message, FIELD_HCENTER | FIELD_VCENTER));
- add(new SpacerField(0, 20));
-
- // parse the button labels
- String[] labels = StringUtils.split(buttonLabels, ",");
- buttons = new ButtonField[labels.length];
-
- // add buttons
- for (int i = 0; i < labels.length; i++) {
- buttons[i] = new ButtonField(labels[i], ButtonField.CONSUME_CLICK | FIELD_HCENTER);
- buttons[i].setChangeListener(this);
- add(new SpacerField(0, 5));
- add(buttons[i]);
- }
- }
-
- /**
- * Returns the index of the button pressed.
- *
- * @return The index of the button pressed (0,1,2...).
- */
- public int getSelectedValue() {
- return this.selectedValue;
- }
-
- /**
- * Invoked when a button is pressed.
- */
- public void fieldChanged(Field field, int context) {
-
- // figure out which button was pressed
- for (int i = 0; i < buttons.length; i++) {
- if (buttons[i] == field) {
- this.selectedValue = i;
- break;
- }
- }
-
- // close the dialog
- close();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/notification/Notification.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/notification/Notification.java b/framework/ext/src/com/phonegap/notification/Notification.java
deleted file mode 100644
index 8118e91..0000000
--- a/framework/ext/src/com/phonegap/notification/Notification.java
+++ /dev/null
@@ -1,135 +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 com.phonegap.notification;
-
-import net.rim.device.api.notification.NotificationsConstants;
-import net.rim.device.api.notification.NotificationsManager;
-
-import com.phonegap.PhoneGapExtension;
-import com.phonegap.api.Plugin;
-import com.phonegap.api.PluginResult;
-import com.phonegap.json4j.JSONArray;
-
-/**
- * PhoneGap Notification plugin.
- *
- * The Notification plugin can invoke the following actions:
- *
- * - alert(message, title, buttonLabel)
- * - confirm(message, title, button1,button2,button3...)
- * - beep(count)
- * - vibrate(duration)
- * - progressStart(title, message)
- * - progressStop()
- * - progressValue(value)
- * - activityStart(title, message)
- * - activityStop()
- */
-public class Notification extends Plugin {
-
- /**
- * Possible actions
- */
- private static final String ACTION_ALERT = "alert";
- private static final String ACTION_BEEP = "beep";
- private static final String ACTION_CONFIRM = "confirm";
- private static final String ACTION_VIBRATE = "vibrate";
- private static final String ACTION_PROGRESS_START = "progressStart";
- private static final String ACTION_PROGRESS_STOP = "progressStop";
- private static final String ACTION_PROGRESS_VALUE = "progressValue";
- private static final String ACTION_ACTIVITY_START = "activityStart";
- private static final String ACTION_ACTIVITY_STOP = "activityStop";
-
- /**
- * Creates a notification profile for the application on the device. The
- * application can trigger a notification event that will play the profile.
- * The profile settings are set by the user.
- */
- public static void registerProfile() {
- // Register with the NotificationsManager to create a notification
- // profile for this application and enable notifications to be
- // controlled by the user
- Object object = new Object() {
- private String appName = PhoneGapExtension.getAppName();
-
- public String toString() {
- return appName;
- }
- };
- NotificationsManager.registerSource(PhoneGapExtension.getAppID(),
- object, NotificationsConstants.IMPORTANT);
- }
-
- /**
- * Executes the request and returns CommandResult.
- *
- * @param action
- * The action to perform.
- * @param callbackId
- * The callback ID to be invoked upon action completion
- * @param args
- * JSONArry of arguments for the specified action.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
- PluginResult result = null;
-
- if (ACTION_ALERT.equals(action)) {
- result = AlertAction.execute(args);
- } else if (ACTION_BEEP.equals(action)) {
- result = BeepAction.execute(args);
- } else if (ACTION_CONFIRM.equals(action)) {
- result = ConfirmAction.execute(args);
- } else if (ACTION_VIBRATE.equals(action)) {
- result = VibrateAction.execute(args);
- } else if (ACTION_ACTIVITY_START.equals(action)) {
- result = ActivityDialog.start(args);
- } else if (ACTION_ACTIVITY_STOP.equals(action)) {
- result = ActivityDialog.stop();
- } else if (ACTION_PROGRESS_START.equals(action)) {
- result = ProgressDialog.start(args);
- } else if (ACTION_PROGRESS_STOP.equals(action)) {
- result = ProgressDialog.stop();
- } else if (ACTION_PROGRESS_VALUE.equals(action)) {
- result = ProgressDialog.setValue(args);
- } else {
- result = new PluginResult(PluginResult.Status.INVALID_ACTION,
- "Notification: Invalid action: " + action);
- }
-
- return result;
- }
-
- /**
- * 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_ALERT.equals(action) || ACTION_CONFIRM.equals(action)) {
- return false;
- }
-
- return true;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/notification/ProgressDialog.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/notification/ProgressDialog.java b/framework/ext/src/com/phonegap/notification/ProgressDialog.java
deleted file mode 100644
index e0f12b2..0000000
--- a/framework/ext/src/com/phonegap/notification/ProgressDialog.java
+++ /dev/null
@@ -1,182 +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 com.phonegap.notification;
-
-import net.rim.device.api.system.Characters;
-import net.rim.device.api.ui.UiApplication;
-import net.rim.device.api.ui.component.GaugeField;
-import net.rim.device.api.ui.component.LabelField;
-import net.rim.device.api.ui.component.SeparatorField;
-import net.rim.device.api.ui.container.PopupScreen;
-import net.rim.device.api.ui.container.VerticalFieldManager;
-
-import com.phonegap.api.PluginResult;
-import com.phonegap.json4j.JSONArray;
-import com.phonegap.json4j.JSONException;
-import com.phonegap.ui.SpacerField;
-
-/**
- * A Popup progress dialog box with an optional title and message and a progress
- * bar with a range from 0 to 100 (percent).
- */
-public final class ProgressDialog extends PopupScreen {
- private static ProgressDialog dialog = null;
- private GaugeField gauge = null;
-
- /**
- * Construct a progress dialog, with customizable title and message.
- *
- * @param title
- * Title of the progress dialog
- * @param message
- * Message to print in the body of the dialog
- */
- private ProgressDialog(String title, String message) {
- super(new VerticalFieldManager());
-
- if (title != null && title.length() > 0) {
- add(new LabelField(title));
- add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
- }
-
- if (message != null && message.length() > 0) {
- add(new SpacerField(0, 20));
- add(new LabelField(message, FIELD_HCENTER | FIELD_VCENTER));
- }
- add(new SpacerField(0, 20));
-
- gauge = new GaugeField(null, 0, 100, 0, GaugeField.PERCENT
- | GaugeField.FIELD_HCENTER);
- add(gauge);
- add(new SpacerField(0, 20));
- }
-
- /**
- * Changes the value displayed in the dialogs GaugeField.
- *
- * @param args
- * JSONArray of arguments.
- * @return a PluginResult indicating success or error.
- */
- static synchronized PluginResult setValue(JSONArray args) {
- if (dialog != null) {
- if (args.length() > 0 && !args.isNull(0)) {
- int value = -1;
- try {
- value = args.getInt(0);
- } catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "JSONException: " + e.getMessage());
- }
-
- if (value >= 0 && value <= 100) {
- dialog.setValue(value);
- }
- }
- }
- return new PluginResult(PluginResult.Status.OK, "");
- }
-
- /**
- * Creates and displays the progress dialog.
- *
- * @param args
- * JSONArray of arguments.
- * @return a PluginResult indicating success or error.
- */
- static synchronized PluginResult start(JSONArray args) {
- if (dialog == null) {
- String message = null;
- String title = null;
-
- // Title and message are optional, grab the strings from the args
- // if they are there.
- if (args != null && args.length() > 0) {
- try {
- if (!args.isNull(0)) {
- title = args.getString(0);
- }
- if (args.length() > 1 && !args.isNull(1)) {
- message = args.getString(1);
- }
- } catch (JSONException e) {
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "JSONException: " + e.getMessage());
- }
- }
-
- dialog = new ProgressDialog(title, message);
- final UiApplication uiApp = UiApplication.getUiApplication();
- uiApp.invokeLater(new Runnable() {
- public void run() {
- uiApp.pushModalScreen(dialog);
- }
- });
- }
-
- return new PluginResult(PluginResult.Status.OK, "");
- }
-
- /**
- * Closes the progress dialog.
- *
- * @return a PluginResult indicating success or error.
- */
- static synchronized PluginResult stop() {
- if (dialog != null) {
- final UiApplication uiApp = UiApplication.getUiApplication();
- final ProgressDialog tmpDialog = dialog;
- uiApp.invokeLater(new Runnable() {
- public void run() {
- uiApp.popScreen(tmpDialog);
- }
- });
- dialog = null;
- }
-
- return new PluginResult(PluginResult.Status.OK, "");
- }
-
- /**
- * @see net.rim.device.api.ui.Screen#keyChar(char, int, int)
- */
- protected boolean keyChar(char key, int status, int time) {
- // If the user clicks back key while progress dialog is displayed, close
- // the progress dialog.
- if (key == Characters.ESCAPE) {
- stop();
- }
-
- return super.keyChar(key, status, time);
- }
-
- /**
- * Changes the value displayed in the GaugeField.
- *
- * @param value
- * the value (percentage) to set in GaugeField.
- */
- private void setValue(final int value) {
- UiApplication.getUiApplication().invokeLater(new Runnable() {
- public void run() {
- gauge.setValue(value);
- }
- });
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/notification/VibrateAction.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/notification/VibrateAction.java b/framework/ext/src/com/phonegap/notification/VibrateAction.java
deleted file mode 100644
index fa03773..0000000
--- a/framework/ext/src/com/phonegap/notification/VibrateAction.java
+++ /dev/null
@@ -1,64 +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 com.phonegap.notification;
-
-import net.rim.device.api.system.Alert;
-
-import com.phonegap.api.PluginResult;
-import com.phonegap.json4j.JSONArray;
-import com.phonegap.json4j.JSONException;
-
-/**
- * Vibrate Action
- *
- * Vibrates the device for specified duration.
- */
-public class VibrateAction {
-
- private static final int DEFAULT_DURATION = 1000;
-
- /**
- * Vibrates the device for a given amount of time.
- *
- * @param args JSONArray formatted as [ duration ]
- * duration: specifies the vibration length in milliseconds (default: 1000).
- * @return A PluginResult object with the success or failure state for vibrating the device.
- */
- public static PluginResult execute(JSONArray args) {
- PluginResult result = null;
-
- if (Alert.isVibrateSupported()) {
- try {
- int duration = (args.length() >= 1) ? args.getInt(0) : DEFAULT_DURATION;
-
- Alert.startVibrate(duration);
- }
- catch (JSONException e) {
- result = new PluginResult(PluginResult.Status.JSON_EXCEPTION, "JSONException: " + e.getMessage());
- }
-
- result = new PluginResult(PluginResult.Status.OK, "OK");
- }
- else {
- result = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION, "Vibrate not supported");
- }
-
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/pim/Contact.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/pim/Contact.java b/framework/ext/src/com/phonegap/pim/Contact.java
deleted file mode 100644
index 0a2dff3..0000000
--- a/framework/ext/src/com/phonegap/pim/Contact.java
+++ /dev/null
@@ -1,430 +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 com.phonegap.pim;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import javax.microedition.io.Connector;
-import javax.microedition.io.HttpConnection;
-import javax.microedition.pim.PIM;
-import javax.microedition.pim.PIMException;
-import javax.microedition.pim.PIMItem;
-
-import net.rim.blackberry.api.pdap.BlackBerryContact;
-import net.rim.blackberry.api.pdap.BlackBerryContactList;
-import net.rim.device.api.io.Base64InputStream;
-import net.rim.device.api.io.FileNotFoundException;
-import net.rim.device.api.io.IOUtilities;
-import net.rim.device.api.io.http.HttpProtocolConstants;
-import net.rim.device.api.math.Fixed32;
-import net.rim.device.api.system.Bitmap;
-import net.rim.device.api.system.EncodedImage;
-import net.rim.device.api.system.PNGEncodedImage;
-
-import com.phonegap.api.Plugin;
-import com.phonegap.api.PluginResult;
-import com.phonegap.file.FileUtils;
-import com.phonegap.http.HttpUtils;
-import com.phonegap.json4j.JSONArray;
-import com.phonegap.json4j.JSONException;
-import com.phonegap.util.Logger;
-
-/**
- * Performs operations on Contacts stored in the BlackBerry Contacts database.
- */
-public class Contact extends Plugin {
-
- /**
- * Possible actions
- */
- public static final int ACTION_SET_PICTURE = 0;
- public static final int ACTION_GET_PICTURE = 1;
-
- /**
- * Maximum object size is 64KB in contact database. The raw image is Base64
- * encoded before insertion.
- * Base64 = (Bytes + 2 - ((Bytes + 2) MOD 3)) / 3 * 4
- */
- private static final long MAX_BYTES = 46080L;
-
- /**
- * Executes the requested action and returns a PluginResult.
- *
- * @param action The action to execute.
- * @param callbackId The callback ID to be invoked upon action completion.
- * @param args JSONArry of arguments for the action.
- * @return A PluginResult object with a status and message.
- */
- public PluginResult execute(String action, JSONArray args, String callbackId) {
-
- PluginResult result = null;
- int a = getAction(action);
-
- // perform specified action
- if (a == ACTION_SET_PICTURE) {
- // get parameters
- String uid;
- String type;
- String value;
- try {
- uid = args.isNull(0) ? null : args.getString(0);
- type = args.isNull(1) ? null : args.getString(1).toLowerCase();
- value = args.isNull(2) ? null : args.getString(2);
- } catch (JSONException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "Invalid or missing photo parameters");
- }
-
- // get the raw image data
- byte[] photo = null;
- if ("base64".equals(type)) {
- // decode the image string
- try {
- photo = decodeBase64(value.getBytes());
- }
- catch (Exception e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.ERROR, "Unable to decode image.");
- }
- }
- else {
- // retrieve the photo from URL
- try {
- photo = getPhotoFromUrl(value);
- }
- catch (Exception e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.ERROR, "Unable to retrieve image at " + value);
- }
- }
-
- // set the contact picture
- result = setPicture(uid, photo);
- }
- else if (a == ACTION_GET_PICTURE) {
- // get required parameters
- String uid = null;
- try {
- uid = args.getString(0);
- } catch (JSONException e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION,
- "Invalid or missing image URL");
- }
- result = getPictureURI(uid);
- }
- else {
- // invalid action
- result = new PluginResult(PluginResult.Status.INVALID_ACTION,
- "Contact: invalid action " + action);
- }
-
- return result;
- }
-
- /**
- * Decodes the base64 encoded data provided.
- * @param data Base64 encoded data
- * @return byte array containing decoded data
- * @throws IllegalArgumentException if encodedData is null
- * @throws IOException if there is an error decoding
- */
- protected byte[] decodeBase64(final byte[] encodedData) throws IllegalArgumentException, IOException {
- if (encodedData == null) {
- throw new IllegalArgumentException();
- }
- ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(encodedData, 0, encodedData.length);
- Base64InputStream base64InputStream = new Base64InputStream(byteArrayInputStream);
- byte[] raw = null;
- try {
- raw = IOUtilities.streamToBytes(base64InputStream);
- }
- finally {
- base64InputStream.close();
- }
- return raw;
- }
-
- /**
- * Sets the photo of the specified contact to the picture at the specified URL.
- * Local file-based (file:///) and web-based (http://) URLs are supported.
- * The specified photo is retrieved and a scaled down copy is created and stored
- * in the contacts database.
- * @param uid Unique identifier of contact
- * @param url URL of the photo to use for contact photo
- * @return PluginResult providing status of operation
- */
- protected PluginResult setPicture(final String uid, final byte[] photo) {
- Logger.log(this.getClass().getName() + ": setting picture for contact " + uid);
-
- // We need to ensure the image encoding is supported, and resize the image
- // so that it will fit in the persistent store. Note: testing indicates
- // that the max image size is 64KB, so we scale it down considerably.
- byte[] thumbnail = null;
- try {
- thumbnail = resizeImage(photo);
- }
- catch (IllegalArgumentException e) {
- // unsupported image format
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Unsupported image format.");
- }
-
- // lookup contact and save the photo
- BlackBerryContactList contactList = null;
- try {
- // lookup the contact
- contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(
- PIM.CONTACT_LIST, PIM.READ_WRITE);
- BlackBerryContact contact = contactList.getByUID(uid);
- if (contact == null) {
- return new PluginResult(PluginResult.Status.ERROR, "Contact " + uid + " not found.");
- }
-
- // save photo image
- if(contact.countValues(javax.microedition.pim.Contact.PHOTO) > 0) {
- contact.setBinary(javax.microedition.pim.Contact.PHOTO, 0,
- PIMItem.ATTR_NONE, thumbnail, 0, thumbnail.length);
- }
- else {
- contact.addBinary(javax.microedition.pim.Contact.PHOTO,
- PIMItem.ATTR_NONE, thumbnail, 0, thumbnail.length);
- }
-
- // commit contact record to persistent store
- contact.commit();
- }
- catch (Exception e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
- }
- finally {
- // be sure to close the contact list to avoid locking it up
- if (contactList != null) {
- try { contactList.close(); } catch (PIMException ignored) { }
- }
- }
-
- return new PluginResult(PluginResult.Status.OK);
- }
-
- /**
- * Returns the URI of the contact photo. The photo image is extracted from
- * the Contacts database and saved to a temporary file system. The URI of
- * the saved photo is returned.
- * @param uid unique Contact identifier
- * @return PluginResult containing photo URI
- */
- protected PluginResult getPictureURI(final String uid) {
- Logger.log(this.getClass().getName() + ": retrieving picture for contact " + uid);
- String photoPath = null;
-
- // lookup contact
- BlackBerryContactList contactList = null;
- try {
- // lookup the contact
- contactList = (BlackBerryContactList) PIM.getInstance().openPIMList(
- PIM.CONTACT_LIST, PIM.READ_WRITE);
- BlackBerryContact contact = contactList.getByUID(uid);
- if (contact == null) {
- return new PluginResult(PluginResult.Status.ERROR, "Contact " + uid + " not found.");
- }
-
- // get photo
- if(contact.countValues(javax.microedition.pim.Contact.PHOTO) > 0) {
- // decode from base64
- byte[] encPhoto = contact.getBinary(javax.microedition.pim.Contact.PHOTO, 0);
- byte[] photo = Base64InputStream.decode(encPhoto, 0, encPhoto.length);
-
- // save photo to file system and return file URI
- saveImage(uid, photo);
- }
- }
- catch (Exception e) {
- Logger.log(this.getClass().getName() + ": " + e);
- return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
- }
- finally {
- // be sure to close the contact list to avoid locking it up
- if (contactList != null) {
- try { contactList.close(); } catch (PIMException ignored) { }
- }
- }
-
- return new PluginResult(PluginResult.Status.OK, photoPath);
- }
-
- /**
- * Retrieves the raw image data from the URL provided.
- * @param url URL of the image
- * @return raw image data from the URL provided
- * @throws FileNotFoundException - if file URL could not be found
- * @throws IOException - if there was an error processing the image file
- */
- protected byte[] getPhotoFromUrl(final String url) throws FileNotFoundException, IOException {
- byte[] photo = null;
-
- // externally hosted image
- if (url != null && url.startsWith("http")) {
- // open connection
- HttpConnection conn = HttpUtils.getHttpConnection(url);
- if (conn == null) {
- throw new IllegalArgumentException("Invalid URL: " + url);
- }
-
- // retrieve image
- InputStream in = null;
- try {
- conn.setRequestMethod(HttpConnection.GET);
- conn.setRequestProperty(
- HttpProtocolConstants.HEADER_USER_AGENT,
- System.getProperty("browser.useragent"));
- conn.setRequestProperty(
- HttpProtocolConstants.HEADER_KEEP_ALIVE, "300");
- conn.setRequestProperty(
- HttpProtocolConstants.HEADER_CONNECTION, "keep-alive");
- conn.setRequestProperty(
- HttpProtocolConstants.HEADER_CONTENT_TYPE,
- HttpProtocolConstants.CONTENT_TYPE_IMAGE_STAR);
-
- // send request and get response
- int rc = conn.getResponseCode();
- if (rc != HttpConnection.HTTP_OK) {
- throw new IOException("HTTP connection error: " + rc);
- }
- in = conn.openDataInputStream();
- photo = IOUtilities.streamToBytes(in, 64*1024);
- in.close();
- }
- finally {
- conn.close();
- }
- }
- // local image file
- else {
- photo = FileUtils.readFile(url, Connector.READ);
- }
- return photo;
- }
-
- /**
- * Saves the contact image to a temporary directory.
- * @param uid unique contact identifier
- * @param photo encoded photo image data
- * @throws IOException
- */
- protected void saveImage(final String uid, final byte[] photo) throws IOException {
- // create a temporary directory to store the contacts photos
- String contactsDir = "Contacts";
- String tempDir = FileUtils.getApplicationTempDirPath() + contactsDir;
- if (!FileUtils.exists(tempDir)) {
- FileUtils.createTempDirectory(contactsDir);
- }
-
- // save the photo image to the temporary directory, overwriting if necessary
- String photoPath = tempDir + FileUtils.FILE_SEPARATOR + uid + ".png";
- if (FileUtils.exists(photoPath)) {
- FileUtils.delete(photoPath);
- }
- FileUtils.writeFile(photoPath, photo, 0);
- }
-
- /**
- * Creates a scaled copy of the specified image.
- * @param photo Raw image data
- * @return a scaled-down copy of the image provided
- * @throws IllegalArgumentException
- */
- protected byte[] resizeImage(byte[] data) throws IllegalArgumentException {
- // create an EncodedImage to make sure the encoding is supported
- EncodedImage image = EncodedImage.createEncodedImage(data, 0, data.length);
-
- // we're limited to 64KB encoding size, do we need to scale?
- if (data.length < MAX_BYTES) {
- return data;
- }
-
- // if so, try to maintain aspect ratio of original image and set max resolution
- int srcWidth = image.getWidth();
- int srcHeight = image.getHeight();
- int dstWidth, dstHeight;
- int max_rez = 150;
- if (srcWidth > srcHeight) {
- dstWidth = max_rez;
- dstHeight = (dstWidth * srcHeight)/srcWidth;
- }
- else if (srcWidth < srcHeight) {
- dstHeight = max_rez;
- dstWidth = (dstHeight * srcWidth)/srcHeight;
- }
- else {
- dstWidth = max_rez;
- dstHeight = max_rez;
- }
-
- // calculate scale factors
- int currentWidthFixed32 = Fixed32.toFP(srcWidth);
- int currentHeightFixed32 = Fixed32.toFP(srcHeight);
- int requiredWidthFixed32 = Fixed32.toFP(dstWidth);
- int requiredHeightFixed32 = Fixed32.toFP(dstHeight);
- int scaleXFixed32 = Fixed32.div(currentWidthFixed32,
- requiredWidthFixed32);
- int scaleYFixed32 = Fixed32.div(currentHeightFixed32,
- requiredHeightFixed32);
-
- // scale image (must be redrawn)
- EncodedImage thumbnail = image.scaleImage32(scaleXFixed32, scaleYFixed32);
- Bitmap bitmap = thumbnail.getBitmap();
-
- // convert back to bytes
- PNGEncodedImage png = PNGEncodedImage.encode(bitmap);
- byte[] thumbData = png.getData();
- Logger.log(this.getClass().getName() + ": photo size reduced from " + data.length + " to " + thumbData.length);
- return thumbData;
- }
-
- /**
- * Returns action to perform.
- * @param action action to perform
- * @return action to perform
- */
- protected static int getAction(String action) {
- if ("setPicture".equals(action)) return ACTION_SET_PICTURE;
- if ("getPicture".equals(action)) return ACTION_GET_PICTURE;
- return -1;
- }
-
- /**
- * 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 (getAction(action) == ACTION_GET_PICTURE) {
- return true;
- }
- else {
- return super.isSynch(action);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/ui/SpacerField.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/ui/SpacerField.java b/framework/ext/src/com/phonegap/ui/SpacerField.java
deleted file mode 100644
index 0fe7d2d..0000000
--- a/framework/ext/src/com/phonegap/ui/SpacerField.java
+++ /dev/null
@@ -1,71 +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 com.phonegap.ui;
-
-import net.rim.device.api.ui.Field;
-import net.rim.device.api.ui.Graphics;
-
-/**
- * Provides an empty spacer field that can be used to provide custom spacing
- * between UI fields within a UI screen.
- */
-public class SpacerField extends Field {
-
- int width; // spacer width in pixels
- int height; // space height in pixels
-
- /**
- * Constructor.
- * @param width Width of the spacer in pixels.
- * @param height Height of the spacer in pixels.
- */
- public SpacerField(int width, int height) {
- super(NON_FOCUSABLE);
- this.width = width;
- this.height = height;
- }
-
- /**
- * Sets the extent to the custom width and height of this spacer.
- */
- protected void layout(int width, int height) {
- this.setExtent(this.width, this.height);
- }
-
- /**
- * Paints the field.
- */
- protected void paint(Graphics graphics) {
- // supposed to be empty. don't paint anything.
- }
-
- /**
- * Returns the custom width of this spacer as the preferred field width.
- */
- public int getPreferredWidth() {
- return this.width;
- }
-
- /**
- * Returns the custom height of this spacer as the preferred field height.
- */
- public int getPreferredHeight() {
- return this.height;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/util/ApplicationUtils.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/util/ApplicationUtils.java b/framework/ext/src/com/phonegap/util/ApplicationUtils.java
deleted file mode 100644
index fd3c7b4..0000000
--- a/framework/ext/src/com/phonegap/util/ApplicationUtils.java
+++ /dev/null
@@ -1,108 +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 com.phonegap.util;
-
-import com.phonegap.camera.Camera;
-
-import net.rim.device.api.system.ApplicationDescriptor;
-import net.rim.device.api.system.ApplicationManager;
-import net.rim.device.api.system.Characters;
-import net.rim.device.api.system.CodeModuleManager;
-import net.rim.device.api.system.ControlledAccessException;
-import net.rim.device.api.system.EventInjector;
-import net.rim.device.api.ui.UiApplication;
-
-public class ApplicationUtils {
- /**
- * Determines if the specified application is running in the foreground.
- *
- * @param handle
- * the name of the application handle (e.g., net_rim_bb_camera")
- * @return <code>true</code> if the application is running and in the
- * foreground
- */
- public static boolean isApplicationInForeground(String handle) {
- // determine if the specified application is running in the foreground
- ApplicationManager manager = ApplicationManager.getApplicationManager();
- int foregroundProcessId = manager.getForegroundProcessId();
- ApplicationDescriptor descriptors[] = manager.getVisibleApplications();
- for (int i = 0; i < descriptors.length; i++) {
- if (descriptors[i].getModuleName().equals(handle)
- && manager.getProcessId(descriptors[i]) == foregroundProcessId) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Determines if the specified application is installed.
- *
- * @param handle
- * the name of the application handle (e.g., net_rim_bb_camera")
- * @return <code>true</code> if the application is installed on the device
- */
- public static boolean isModuleInstalled(String handle) {
- return (CodeModuleManager.getModuleHandle(handle) != 0);
- }
-
- /**
- * Use this method when another native application has been launched by this
- * application, and you would like the application to be closed.
- * <p>
- * Unfortunately, the only way to do this programmatically is to simulate
- * the Escape (back) key being pressed. We do this by injecting key events,
- * which means the application permissions must have the key injection
- * permissions enabled for it to work.
- * <p>
- * An alternative to closing the applications would be to simply request
- * that our application be brought to the foreground; however, this just
- * pushes all the applications we've launched to the background, leaving a
- * mess for the user to cleanup after this application has been closed.
- *
- * @param repeat
- * the number of times to press the Esc key
- */
- public static void injectEscKeyPress(final int repeat) {
- // simulate escape characters (back button press)
- Runnable escKeyPresser = new Runnable() {
- public void run() {
- try {
- EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
- EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE,
- 0);
- int count = 0;
- while (count < repeat) {
- inject.post();
- count++;
- }
- }
- catch (ControlledAccessException e) {
- // the application doesn't have key injection
- // permissions
- Logger.log(Camera.class.getName() + ": "
- + ApplicationDescriptor
- .currentApplicationDescriptor().getName()
- + " does not have key injection permissions.");
- }
- }
- };
- UiApplication.getUiApplication().invokeLater(escKeyPresser);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/util/Log.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/util/Log.java b/framework/ext/src/com/phonegap/util/Log.java
deleted file mode 100644
index ed65760..0000000
--- a/framework/ext/src/com/phonegap/util/Log.java
+++ /dev/null
@@ -1,83 +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 com.phonegap.util;
-
-import net.rim.device.api.script.Scriptable;
-import net.rim.device.api.script.ScriptableFunction;
-
-/**
- * Log provides a mechanism for JavaScript code to utilize the Event Log.
- * Log represents an object in the script engine that can be accessed from the
- * script environment using <code>phonegap.Logger</code>.
- *
- * Log provides a function, <code>log(msg)</code>, that logs messages to the
- * BlackBerry Event Log as well as to System.out.
- *
- * To use of the Blackberry Event Log from JavaScript, you must first
- * invoke the <code>enable()</code> method:
- *
- * <code>phonegap.Logger.enable();</code>
- * <code>phonegap.Logger.log(msg);</code>
- */
-public final class Log extends Scriptable {
-
- /**
- * Field used to log messages.
- */
- public static final String FIELD_LOG = "log";
-
- /**
- * Field used to enable message logging.
- */
- public static final String FIELD_ENABLE = "enable";
-
- /**
- * Logs messages to the BlackBerry Event Log and to <code>System.out</code>.
- */
- public final LogFunction logFunction; // logs to the Event Log
-
- /**
- * Constructor.
- */
- public Log() {
- this.logFunction = new LogFunction();
- }
-
- /**
- * The following fields are supported from the script environment:
- *
- * <code>phonegap.Logger.enable</code> - Enables message logging.
- * <code>phonegap.Logger.log</code> - Logs the specified message.
- */
- public Object getField(String name) throws Exception {
-
- if (name.equals(FIELD_LOG)) {
- return this.logFunction;
- }
- else if (name.equals(FIELD_ENABLE)) {
- return new ScriptableFunction() {
- public Object invoke(Object obj, Object[] oargs) throws Exception {
- Logger.enableLogging();
- return null;
- }
- };
- }
- return super.getField(name);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/util/LogFunction.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/util/LogFunction.java b/framework/ext/src/com/phonegap/util/LogFunction.java
deleted file mode 100644
index 3675afc..0000000
--- a/framework/ext/src/com/phonegap/util/LogFunction.java
+++ /dev/null
@@ -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.
- */
-package com.phonegap.util;
-
-import net.rim.device.api.script.ScriptableFunction;
-
-/**
- * LogFunction represents a function that can be invoked from the script
- * environment of the widget framework. Messages are logged to the Blackberry
- * Event Log. From JavaScript, invoke
- *
- * <code>phonegap.Logger.log(msg);</code>
- */
-public class LogFunction extends ScriptableFunction {
-
- public Object invoke(Object obj, Object[] oargs) throws Exception {
-
- if (oargs != null) {
- String message = (String)oargs[0];
- Logger.log(message);
- }
-
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/util/Logger.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/util/Logger.java b/framework/ext/src/com/phonegap/util/Logger.java
deleted file mode 100644
index 9166b5a..0000000
--- a/framework/ext/src/com/phonegap/util/Logger.java
+++ /dev/null
@@ -1,155 +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 com.phonegap.util;
-
-import java.util.Date;
-
-import net.rim.device.api.i18n.SimpleDateFormat;
-import net.rim.device.api.system.EventLogger;
-
-import com.phonegap.PhoneGapExtension;
-
-/**
- * Logger provides a mechanism to log the the Blackberry Event Log. It uses
- * the Blackberry EventLogger class.
- *
- * The Event Log can be viewed on Blackberry simulators using Tools > Show Event
- * Log, or on physical devices by pressing the <code>Alt</code> key, followed by
- * the <code>LGLG</code> key combination.
- *
- * To enable event logging, you must first call <code>enableLogging</code>.
- *
- * Logger also provides methods to write to <code>System.out</code> and
- * <code>System.err</code>.
- */
-public class Logger {
-
- /**
- * Application name
- */
- protected static String appName;
-
- /**
- * Application GUID
- */
- protected static long appID;
-
- /**
- * Used to format dates into a standard format
- */
- private static final SimpleDateFormat dateFormat =
- new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
-
- /**
- * Invoke this method to enable logging to the BlackBerry Event Log.
- */
- public static void enableLogging() {
- appID = PhoneGapExtension.getAppID();
- appName = PhoneGapExtension.getAppName();
- if (EventLogger.register(appID, appName, EventLogger.VIEWER_STRING)) {
- log("Logger enabled: " + "GUID=" + appID + ", name=" + appName);
- }
- else {
- log("EventLogger registration failed.");
- }
- }
-
- /**
- * Sets the minimum logging level.
- */
- public static void setMinimumLoggingLevel(int level) {
- EventLogger.setMinimumLevel(level);
- }
-
- /**
- * Logs formatted message to Event Log with ALWAYS_LOG level.
- */
- public static void log(String msg) {
- logEvent(msg, EventLogger.ALWAYS_LOG);
- }
-
- /**
- * Logs formatted message to Event Log with DEBUG_INFO level.
- */
- public static void debug(String msg) {
- logEvent(msg, EventLogger.DEBUG_INFO);
- }
-
- /**
- * Logs formatted message to Event Log with INFORMATION level.
- */
- public static void info(String msg) {
- logEvent(msg, EventLogger.INFORMATION);
- }
-
- /**
- * Logs formatted message to Event Log with WARNING level.
- */
- public static void warn(String msg) {
- logEvent(msg, EventLogger.WARNING);
- }
-
- /**
- * Logs formatted message to Event Log with ERROR level.
- */
- public static void error(String msg) {
- logEvent(msg, EventLogger.ERROR);
- }
-
- /**
- * Logs formatted message to Event Log with SEVERE_ERROR level.
- */
- public static void severe(String msg) {
- logEvent(msg, EventLogger.SEVERE_ERROR);
- }
-
- /**
- * Prints unformatted message to System.out.
- */
- public static void out(String msg) {
- System.out.println(msg);
- }
-
- /**
- * Prints unformatted message to System.err.
- */
- public static void err(String msg, Throwable t) {
- System.err.println(msg);
- t.printStackTrace();
- }
-
- /**
- * Logs formatted message to Event Log (if enabled) and System.out.
- */
- private static void logEvent(String msg, int level) {
- String message = formatMessage(msg);
- EventLogger.logEvent(appID, message.getBytes(), level);
- out(message);
- }
-
- private static String formatMessage(String msg) {
- StringBuffer sb = new StringBuffer();
- sb.append(appName);
- sb.append(" [");
- sb.append(dateFormat.format(new Date()));
- sb.append("]: ");
- sb.append(msg);
- return sb.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/com/phonegap/util/StringUtils.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/com/phonegap/util/StringUtils.java b/framework/ext/src/com/phonegap/util/StringUtils.java
deleted file mode 100644
index 13a213c..0000000
--- a/framework/ext/src/com/phonegap/util/StringUtils.java
+++ /dev/null
@@ -1,103 +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.
- */
-/*
- * Taken from Research in Motion knowledge base article:
- *
- * DB-00728: "How To - Implement a string splitter based on a given string delimiter", 24 March 2009.
- * http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/832062/How_To_-_Implement_a_string_splitter_based_on_a_given_string_delimiter.html?nodeid=1498848&vernum=0
- */
-package com.phonegap.util;
-
-/**
- * Provides various string utility methods.
- */
-public class StringUtils {
-
- //Identifies the substrings in a given string that are delimited
- //by one or more characters specified in an array, and then
- //places the substrings into a String array.
- public static String[] split(String strString, String strDelimiter) {
- String[] strArray;
- int iOccurrences = 0;
- int iIndexOfInnerString = 0;
- int iIndexOfDelimiter = 0;
- int iCounter = 0;
-
- //Check for null input strings.
- if (strString == null) {
- throw new IllegalArgumentException("Input string cannot be null.");
- }
- //Check for null or empty delimiter strings.
- if (strDelimiter.length() <= 0 || strDelimiter == null) {
- throw new IllegalArgumentException("Delimeter cannot be null or empty.");
- }
-
- //strString must be in this format: (without {} )
- //"{str[0]}{delimiter}str[1]}{delimiter} ...
- // {str[n-1]}{delimiter}{str[n]}{delimiter}"
-
- //If strString begins with delimiter then remove it in order
- //to comply with the desired format.
-
- if (strString.startsWith(strDelimiter)) {
- strString = strString.substring(strDelimiter.length());
- }
-
- //If strString does not end with the delimiter then add it
- //to the string in order to comply with the desired format.
- if (!strString.endsWith(strDelimiter)) {
- strString += strDelimiter;
- }
-
- //Count occurrences of the delimiter in the string.
- //Occurrences should be the same amount of inner strings.
- while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
- iIndexOfInnerString)) != -1) {
- iOccurrences += 1;
- iIndexOfInnerString = iIndexOfDelimiter +
- strDelimiter.length();
- }
-
- //Declare the array with the correct size.
- strArray = new String[iOccurrences];
-
- //Reset the indices.
- iIndexOfInnerString = 0;
- iIndexOfDelimiter = 0;
-
- //Walk across the string again and this time add the
- //strings to the array.
- while((iIndexOfDelimiter = strString.indexOf(strDelimiter,
- iIndexOfInnerString)) != -1) {
-
- //Add string to array.
- strArray[iCounter] = strString.substring(iIndexOfInnerString,iIndexOfDelimiter);
-
- //Increment the index to the next character after
- //the next delimiter.
- iIndexOfInnerString = iIndexOfDelimiter +
- strDelimiter.length();
-
- //Inc the counter.
- iCounter += 1;
- }
-
- return strArray;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/library.xml
----------------------------------------------------------------------
diff --git a/framework/ext/src/library.xml b/framework/ext/src/library.xml
index d578795..32f9f3b 100644
--- a/framework/ext/src/library.xml
+++ b/framework/ext/src/library.xml
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<library>
<extension>
- <entryClass>com.phonegap.PhoneGapExtension</entryClass>
+ <entryClass>org.apache.cordova.CordovaExtension</entryClass>
</extension>
<features>
- <feature id="com.phonegap" version="1.0.0">PhoneGap JavaScript Extension</feature>
+ <feature id="org.apache.cordova" version="1.0.0">Cordova JavaScript Extension</feature>
</features>
</library>
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/org/apache/cordova/CordovaExtension.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/org/apache/cordova/CordovaExtension.java b/framework/ext/src/org/apache/cordova/CordovaExtension.java
new file mode 100644
index 0000000..86dad0b
--- /dev/null
+++ b/framework/ext/src/org/apache/cordova/CordovaExtension.java
@@ -0,0 +1,208 @@
+/*
+ * 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.
+ *
+ * Copyright (c) 2011, Research In Motion Limited.
+ */
+package org.apache.cordova;
+
+import net.rim.device.api.browser.field2.BrowserField;
+import net.rim.device.api.script.ScriptEngine;
+import net.rim.device.api.system.Application;
+import net.rim.device.api.web.WidgetConfig;
+import net.rim.device.api.web.WidgetExtension;
+import net.rim.device.api.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.cordova.api.PluginManager;
+import org.apache.cordova.api.PluginResult;
+import org.apache.cordova.notification.Notification;
+import org.apache.cordova.util.Log;
+import org.apache.cordova.util.Logger;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import java.lang.ref.WeakReference;
+
+/**
+ * CordovaExtension is a BlackBerry WebWorks JavaScript extension. It
+ * represents a single feature that can be used to access device capabilities.
+ */
+public final class CordovaExtension implements WidgetExtension {
+
+ // Weak reference encapsulating BrowserField object used to display the application
+ // We use the weak reference because keeping a direct reference can
+ // cause memory leak issues in WebWorks. Original solution described
+ // and suggested by Tim Neil on the BlackBerry support forums.
+ // Thanks Tim!
+ protected static WeakReference browser = null;
+
+ // Browser script engine
+ //
+ protected static ScriptEngine script;
+
+ // Application name
+ //
+ protected static String appName;
+
+ // Application GUID
+ //
+ protected static long appID;
+
+ // Plugin Manager
+ //
+ protected PluginManager pluginManager;
+
+ // Feature ID
+ //
+ private static final String FEATURE_ID ="org.apache.cordova";
+
+ // Called when the BlackBerry Widget references this extension for the first time.
+ // It provides a list of feature IDs exposed by this extension.
+ //
+ public String[] getFeatureList() {
+ return new String[] {FEATURE_ID};
+ }
+
+ // Called whenever a widget loads a resource that requires a feature ID that is supplied
+ // in the getFeatureList
+ //
+ public void loadFeature(String feature, String version, Document doc,
+ ScriptEngine scriptEngine) throws Exception {
+ script = scriptEngine;
+ // Not sure why logger is not already enabled?
+ Logger.enableLogging();
+ if (feature.equals(FEATURE_ID)) {
+ pluginManager = new PluginManager(this);
+
+ // create and parse the plugins.xml
+ Document c = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(Application.class.getResourceAsStream("/plugins.xml"));
+
+ NodeList plugins = c.getElementsByTagName("plugin");
+ if (plugins.getLength() == 0) {
+ Logger.warn("If you are using any Cordova APIs you will need to "+
+ "specify them in the config.xml using <gap:plugin name=\"MyPlugin\" "+
+ "value=\"com.example.MyPlugin\"/>");
+ }
+ for(int i=0; i<plugins.getLength() ; i++){
+ Node plugin = plugins.item(i);
+ Logger.log("Found plugin " + plugin.getAttributes().getNamedItem("name").getNodeValue() + " = " +
+ plugin.getAttributes().getNamedItem("value").getNodeValue());
+ pluginManager.addService(plugin.getAttributes().getNamedItem("name").getNodeValue(),
+ plugin.getAttributes().getNamedItem("value").getNodeValue());
+ }
+
+ scriptEngine.addExtension("org.apache.cordova.JavaPluginManager", pluginManager);
+ scriptEngine.addExtension("org.apache.cordova.Logger", new Log());
+
+ // let Cordova JavaScript know that extensions have been loaded
+ // if this is premature, we at least set the _nativeReady flag to true
+ // so that when the JS side is ready, it knows native side is too
+ Logger.log(this.getClass().getName() + ": invoking Cordova.onNativeReady.fire()");
+ scriptEngine.executeScript("try {Cordova.onNativeReady.fire();} catch(e) {_nativeReady = true;}", null);
+ }
+ }
+
+ // Called so that the extension can get a reference to the configuration or browser field object
+ //
+ public void register(WidgetConfig widgetConfig, BrowserField browserField) {
+ browser = new WeakReference(browserField);
+
+ // grab widget application name and use it to generate a unique ID
+ appName = widgetConfig.getName();
+ appID = Long.parseLong(Math.abs(("org.apache.cordova."+appName).hashCode())+"",16);
+
+ // create a notification profile for the application
+ Notification.registerProfile();
+ }
+
+ /**
+ * Called to clean up any features when the extension is unloaded. This is
+ * invoked by the WebWorks Framework when another URL is loaded.
+ *
+ * @see net.rim.device.api.web.WidgetExtension#unloadFeatures(org.w3c.dom.Document)
+ */
+ public void unloadFeatures(Document doc) {
+ // Cleanup plugin resources.
+ if (pluginManager != null) {
+ pluginManager.destroy();
+ }
+ }
+
+ public static void invokeScript(final String js) {
+ // Use a new thread so that JavaScript is invoked asynchronously.
+ // Otherwise executeScript doesn't return until JavaScript call back
+ // is finished.
+ (new Thread() {
+ public void run() {
+ try {
+ script.executeScript(js, null);
+ } catch (Exception e) {
+ // This is likely an IllegalStateException which is thrown
+ // because the framework is in the process of being shutdown
+ // so communication to JavaScript side is not allowed.
+ Logger.log("Caught exception while executing script: "
+ + e.getMessage());
+ }
+ }
+ }).start();
+ }
+
+ /**
+ * Invokes the Cordova success callback specified by callbackId.
+ * @param callbackId unique callback ID
+ * @param result Cordova PluginResult containing result
+ */
+ public static void invokeSuccessCallback(String callbackId, PluginResult result) {
+ invokeScript(result.toSuccessCallbackString(callbackId));
+ }
+
+ /**
+ * Invokes the Cordova error callback specified by callbackId.
+ * @param callbackId unique callback ID
+ * @param result Cordova PluginResult containing result
+ */
+ public static void invokeErrorCallback(String callbackId, PluginResult result) {
+ invokeScript(result.toErrorCallbackString(callbackId));
+ }
+
+ /**
+ * Provides access to the browser instance for the application.
+ */
+ public static BrowserField getBrowserField() {
+ Object o = browser.get();
+ if ( o instanceof BrowserField ) {
+ return (BrowserField)o;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Returns the widget application name.
+ */
+ public static String getAppName() {
+ return appName;
+ }
+
+ /**
+ * Returns unique ID of the widget application.
+ */
+ public static long getAppID() {
+ return appID;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-blackberry-webworks/blob/05319d3c/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java
----------------------------------------------------------------------
diff --git a/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java b/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java
new file mode 100644
index 0000000..25cf783
--- /dev/null
+++ b/framework/ext/src/org/apache/cordova/accelerometer/Accelerometer.java
@@ -0,0 +1,225 @@
+/*
+ * 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.accelerometer;
+
+import org.apache.cordova.api.Plugin;
+import org.apache.cordova.api.PluginResult;
+import org.apache.cordova.json4j.JSONArray;
+import org.apache.cordova.json4j.JSONException;
+import org.apache.cordova.json4j.JSONObject;
+import org.apache.cordova.util.Logger;
+
+import net.rim.device.api.system.AccelerometerData;
+import net.rim.device.api.system.AccelerometerListener;
+import net.rim.device.api.system.AccelerometerSensor;
+import net.rim.device.api.system.Application;
+
+public class Accelerometer extends Plugin implements AccelerometerListener {
+
+ public static final String ACTION_GET_ACCELERATION = "getAcceleration";
+ public static final String ACTION_SET_TIMEOUT = "setTimeout";
+ public static final String ACTION_GET_TIMEOUT = "getTimeout";
+ public static final String ACTION_STOP = "stop";
+
+ public static int STOPPED = 0;
+ public static int STARTED = 1;
+
+ private static AccelerometerSensor.Channel _rawDataChannel = null; // the single channel to the device sensor
+ int status; // status of this listener
+ public float timeout = 30000; // timeout in msec to close sensor channel
+ long lastAccessTime; // last time accel data was retrieved
+
+ public PluginResult execute(String action, JSONArray args, String calbackId) {
+
+ PluginResult result = null;
+
+ if (!AccelerometerSensor.isSupported()) {
+ result = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION, "Accelerometer sensor not supported");
+ }
+ else if (ACTION_GET_ACCELERATION.equals(action)) {
+ JSONObject accel = new JSONObject();
+ try {
+ AccelerometerData accelData = getCurrentAcceleration();
+ accel.put("x", (int)accelData.getLastXAcceleration());
+ accel.put("y", (int)accelData.getLastYAcceleration());
+ accel.put("z", (int)accelData.getLastZAcceleration());
+ accel.put("timestamp", accelData.getLastTimestamp());
+ } catch (JSONException e) {
+ return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "JSONException:" + e.getMessage());
+ }
+ result = new PluginResult(PluginResult.Status.OK, accel);
+ }
+ else if (ACTION_GET_TIMEOUT.equals(action)) {
+ float f = this.getTimeout();
+ return new PluginResult(PluginResult.Status.OK, Float.toString(f));
+ }
+ else if (ACTION_SET_TIMEOUT.equals(action)) {
+ try {
+ float t = Float.parseFloat(args.getString(0));
+ this.setTimeout(t);
+ return new PluginResult(PluginResult.Status.OK, "");
+ } catch (NumberFormatException e) {
+ return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
+ } catch (JSONException e) {
+ return new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
+ }
+ }
+ else if (ACTION_STOP.equals(action)) {
+ this.stop();
+ return new PluginResult(PluginResult.Status.OK, "");
+ }
+ else {
+ result = new PluginResult(PluginResult.Status.INVALID_ACTION, "Accelerometer: Invalid action:" + action);
+ }
+
+ return result;
+ }
+
+ /**
+ * 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) {
+ return true;
+ }
+
+ /**
+ * Get status of accelerometer sensor.
+ *
+ * @return status
+ */
+ public int getStatus() {
+ return this.status;
+ }
+
+ /**
+ * Set the status and send it to JavaScript.
+ * @param status
+ */
+ private void setStatus(int status) {
+ this.status = status;
+ }
+
+ /**
+ * Set the timeout to turn off accelerometer sensor.
+ *
+ * @param timeout Timeout in msec.
+ */
+ public void setTimeout(float timeout) {
+ this.timeout = timeout;
+ }
+
+ /**
+ * Get the timeout to turn off accelerometer sensor.
+ *
+ * @return timeout in msec
+ */
+ public float getTimeout() {
+ return this.timeout;
+ }
+
+ /**
+ * Opens a raw data channel to the accelerometer sensor.
+ * @return the AccelerometerSensor.Channel for the application
+ */
+ private static AccelerometerSensor.Channel getChannel() {
+ // an application can only have one open channel
+ if (_rawDataChannel == null || !_rawDataChannel.isOpen()) {
+ _rawDataChannel = AccelerometerSensor.openRawDataChannel(
+ Application.getApplication());
+ Logger.log(Accelerometer.class.getName() +": sensor channel opened");
+ }
+ return _rawDataChannel;
+ }
+
+ /**
+ * Returns last acceleration data from the accelerometer sensor.
+ * @return AccelerometerData with last acceleration data
+ */
+ private AccelerometerData getCurrentAcceleration() {
+ // open sensor channel
+ if (this.getStatus() != STARTED) {
+ this.start();
+ }
+
+ // get the last acceleration
+ AccelerometerData accelData = getChannel().getAccelerometerData();
+
+ Logger.log(this.getClass().getName() +
+ ": x=" + accelData.getLastXAcceleration() +
+ ", y=" + accelData.getLastYAcceleration() +
+ ", z=" + accelData.getLastZAcceleration() +
+ ", timestamp=" + accelData.getLastTimestamp());
+
+ // remember the access time (for timeout purposes)
+ this.lastAccessTime = System.currentTimeMillis();
+
+ return accelData;
+ }
+
+ /**
+ * Implements the AccelerometerListener method. We listen for the purpose
+ * of closing the application's accelerometer sensor channel after timeout
+ * has been exceeded.
+ */
+ public void onData(AccelerometerData accelData) {
+ // time that accel event was received
+ long timestamp = accelData.getLastTimestamp();
+
+ // If values haven't been read for length of timeout,
+ // turn off accelerometer sensor to save power
+ if ((timestamp - this.lastAccessTime) > this.timeout) {
+ this.stop();
+ }
+ }
+
+ /**
+ * Adds this listener to sensor channel.
+ */
+ public void start() {
+ // open the sensor channel and register listener
+ getChannel().setAccelerometerListener(this);
+
+ Logger.log(this.getClass().getName() +": sensor listener added");
+
+ this.setStatus(STARTED);
+ }
+
+ /**
+ * Stops accelerometer listener and closes the sensor channel.
+ */
+ public void stop() {
+ // close the sensor channel
+ if (_rawDataChannel != null && _rawDataChannel.isOpen()) {
+ _rawDataChannel.close();
+ Logger.log(this.getClass().getName() +": sensor channel closed");
+ }
+
+ this.setStatus(STOPPED);
+ }
+
+ /**
+ * Called when Plugin is destroyed.
+ */
+ public void onDestroy() {
+ this.stop();
+ }
+}