Sie sind auf Seite 1von 36

Research In Motion (RIM)

LAB – Building a BlackBerry


Widget JavaScript Extension
v1.1
For BlackBerry Smartphones
Adam Stanley
Tim Neil
2|Page

Contents

Objectives .............................................................................................................................................. 3
Prerequisites ......................................................................................................................................... 3
Scenario ................................................................................................................................................. 3
Document History ................................................................................................................................. 4
Starter and Solution Files .................................................................................................................... 4
Exercise ................................................................................................................................................. 5
Creating a Custom JavaScript Extension ..................................................................................... 5
Deploying a Custom JavaScript Extension to be used by the BlackBerry Web Plug-in ..... 16
Creating a BlackBerry Widget that uses a Custom JavaScript Extension ............................ 23
Check your work ................................................................................................................................. 35
Advanced Developers ....................................................................................................................... 35
Review ................................................................................................................................................. 35
Links ..................................................................................................................................................... 36
3|Page

Objectives

After completing this lab, you will be able to:

• Use the BlackBerry® JDE Plug-in for Eclipse® 1.1 to write a custom JavaScript®
Extension
• Use the BlackBerry Web Plug-in for Eclipse or Microsoft® Visual Studio® to create
and package a BlackBerry® Widget application that uses features provided by a
custom JavaScript extension

Prerequisites

• BlackBerry JDE Plug-in for Eclipse 1.1 installed


• BlackBerry Web Plug-in for Eclipse 2.0 or BlackBerry Web Plug-in for Microsoft
Visual Studio 2.0 installed
• Java® Development Kit 1.6 or higher installed

Scenario

A JavaScript Extension is Java code that is built into a BlackBerry Widget, and can be
accessed through JavaScript. This capability allows you to extend the functionality of your
BlackBerry Widget application to include functionality from the Java development
environment as well as the native BlackBerry® Smartphone.

This lab will demonstrate how to extend the out-of-the box functionality of a BlackBerry
Widget by completing the following two steps

A. Creating a Custom JavaScript Extension

B. Creating a BlackBerry Widget that uses the Custom JavaScript Extension


4|Page

Document History

Date Version Details

04/06/2010 1.1 Updated instructions to describe how to use the


BlackBerry Web Plug-in for Eclipse or Microsoft Visual
Studio to include a custom extension JAR file when
packaging a BlackBerry Widget application. BlackBerry
Widget SDK no longer in BETA.

02/02/2010 1.0 Initial document (BlackBerry Widget SDK in BETA).


Instructions on how to manually configure BlackBerry
Widget Packager to recognize and include custom
extension source code when packaging a widget.

Starter and Solution Files

There are starter and solution files associated with this lab. The starter files can be found in
the install_folder\Labs\Lab_Widget_Extension\starter folder and the solution files are in the
install_folder\Labs\Lab_Widget_Extension\solution folder.

The starter folder should contain the following two folders files:

• MyWidgetExtension – Eclipse project folder for JavaScript Extension source code.

• Alert – contains BlackBerry Widget source code.

The solution folder contains the completed source code of the JavaScript Extension and
BlackBerry Widget that will be created as part of this lab.

Estimated time to complete this lab: 60 minutes


5|Page

Exercise

Creating a Custom JavaScript Extension

You will use the BlackBerry JDE Plug-in for Eclipse 1.1 (with component pack 5.0) to create
and package the source code of your custom JavaScript extension. This is a separate tool
from the BlackBerry Widget Packager, and is typically used by Java developers to write
BlackBerry applications. This tool can be downloaded from the following location:

http://na.blackberry.com/eng/developers/javaappdev/javaplugin.jsp

Important tip!
If you also have the BlackBerry Web Plug-in for Eclipse installed (used for testing/debugging
web and BlackBerry Widget content in a BlackBerry smartphone simulator), it is important to
be aware that sharing the same workspace may result in the incorrect Eclipse perspective
being opened when each Plug-in is opened. When working with the BlackBerry JDE Plug-in
for Eclipse, make sure to have the “Java” perspective opened:

1. Open the BlackBerry JDE Plug-in for Eclipse 1.1 and create a new BlackBerry project
from the File menu.
6|Page

2. Name your project MyWidgetExtension. Ensure that the “BlackBerry JRE 5.0.0” is
selected as the project specific JRE and click on the Finish button. If there is no option
available for the 5.0 BlackBerry JRE, it means the 5.0 component pack is not installed in
Eclipse. This component pack is required for building custom JavaScript extensions for
BlackBerry Widgets, as they make use of new APIs introduced in 5.0.
7|Page

3. From the Package Explorer window, right click on the SRC folder within your project and
create a new package.

4. Name the package widgetpackage and click on the Finish button.


8|Page

5. Right click on the new package and add a class to your project named AlertSample.
Make sure the class has the public and final modifiers, and that it has a super class of
“net.rim.device.api.script.Scriptable”.
9|Page

6. The new class will contain the following code

package widgetpackage;

import net.rim.device.api.script.Scriptable;

public final class AlertSample extends Scriptable {

7. This class will be used to map keywords provided by a Widget application to internal
BlackBerry logic. Add the following code to the AlertSample class. The getField()
function is called when the dot “.” extender is used on your JavaScript object. It will be
used to check to see if the vibration feature is supported on the given device when a
Widget makes a call to a JavaScript function named “vibrateSupported”. Since a
Widget application may run on BlackBerry smartphone models with different hardware
configurations, it is considered good practice to always check whether a hardware
feature is supported before it is used.

package widgetpackage;

import net.rim.device.api.script.Scriptable;
import net.rim.device.api.system.Alert;

public final class AlertSample extends Scriptable {


public static final String FIELD_VIBRATE_SUPPORTED = "vibrateSupported";

public AlertSample() {
}

public Object getField(String name) throws Exception {


if (name.equals(FIELD_VIBRATE_SUPPORTED)) {
return new Boolean(Alert.isVibrateSupported());
}
return super.getField(name);
}
}

8. Next, add a class to your project named Vibrate. Ensure this class is also public and
final, and has a super class of
net.rim.device.api.script.ScriptableFunction.
10 | P a g e

9. The source code for the Vibrate class will look like this:

package widgetpackage;

import net.rim.device.api.script.ScriptableFunction;

public final class Vibrate extends ScriptableFunction {

}
11 | P a g e

10. Add the following functionality to this class. This logic will cause the BlackBerry
smartphone to vibrate for a fixed duration of time:

package widgetpackage;

import net.rim.device.api.script.ScriptableFunction;
import net.rim.device.api.system.Alert;

public final class Vibrate extends ScriptableFunction {

public Object invoke(Object obj, Object[] args) throws Exception


{

if (!Alert.isVibrateSupported()) {
return UNDEFINED;
}

if (args.length == 1) {
int duration = ((Integer)args[0]).intValue();
Alert.startVibrate(duration);
}

return UNDEFINED;
}
}

11. Now you will connect the functionality defined in the Vibrate class to the AlertSample
class. Add the following logic within the AlertSample class:

package widgetpackage;

import net.rim.device.api.script.Scriptable;
import net.rim.device.api.system.Alert;

public final class AlertSample extends Scriptable {


public static final String FIELD_VIBRATE_SUPPORTED = "vibrateSupported";

private Vibrate callVibrate;

public AlertSample() {
this.callVibrate = new Vibrate();
}

public Object getField(String name) throws Exception {

if (name.equals(FIELD_VIBRATE_SUPPORTED)) {
return new Boolean(Alert.isVibrateSupported());
}

return super.getField(name);
}
}
12 | P a g e

12. Next, add logic that provides support for calls made to these methods:

package widgetpackage;

import net.rim.device.api.script.Scriptable;
import net.rim.device.api.system.Alert;

public final class AlertSample extends Scriptable {


public static final String FIELD_VIBRATE_SUPPORTED = "vibrateSupported";
public static final String FIELD_VIBRATE = "vibrate";

private Vibrate callVibrate;

public AlertSample() {
this.callVibrate = new Vibrate();
}

public Object getField(String name) throws Exception {

if (name.equals(FIELD_VIBRATE_SUPPORTED)) {
return new Boolean(Alert.isVibrateSupported());

} else if (name.equals(FIELD_VIBRATE)) {
return this.callVibrate;
}

return super.getField(name);
}
}

13. Finally, add a class named SampleExtension to your project. This class will tie
everything together and act as the interface between JavaScript used by a BlackBerry
Widget and the custom logic you have defined in your AlertSample class. Ensure the
public and final modifiers are selected. This class will be defined with an interface of
“net.rim.device.api.web.WidgetExtension” To add an interface, click on the
add button next to the Interfaces field and then type in the full name of the interface:
13 | P a g e
14 | P a g e

14. The SampleExtension class will contain the following source code:

package widgetpackage;

import org.w3c.dom.Document;

import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.script.ScriptEngine;
import net.rim.device.api.web.WidgetConfig;
import net.rim.device.api.web.WidgetExtension;

public final class SampleExtension implements WidgetExtension {

public String[] getFeatureList() {


// TODO Auto-generated method stub
return null;
}

public void loadFeature(String arg0, String arg1, Document arg2,


ScriptEngine arg3) throws Exception {
// TODO Auto-generated method stub
}

public void register(WidgetConfig arg0, BrowserField arg1) {


// TODO Auto-generated method stub
}

public void unloadFeatures(Document arg0) {


// TODO Auto-generated method stub
}
}

15. To provide a brief overview of what each of these methods do:

o getFeatureList() – this method is called when the extension is created to


provide a full list of <feature> id’s that it would like to provide extensions for.

o loadFeature() – this method is called when a widget loads a resource that


requires a <feature> id that you supplied in getFeatureList()

o register() – this method is called so that your extension can get a handle to the
configuration document or BrowserField object if it needs it.

o unloadFeatures() – this method is available if you need to do any clean-up when


your extension is unloaded.
15 | P a g e

16. Add the following code to the getFeatureList() function. When this extension is
created, it will return an array representing the available features that it provides:

package widgetpackage;

import org.w3c.dom.Document;

import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.script.ScriptEngine;
import net.rim.device.api.web.WidgetConfig;
import net.rim.device.api.web.WidgetExtension;

public final class SampleExtension implements WidgetExtension {

public String[] getFeatureList() {


String[] result = new String[1];
result[0] = "sample";
return result;
}

public void loadFeature(String arg0, String arg1, Document arg2,


ScriptEngine arg3) throws Exception {
// TODO Auto-generated method stub
}

public void register(WidgetConfig arg0, BrowserField arg1) {


// TODO Auto-generated method stub
}

public void unloadFeatures(Document arg0) {


// TODO Auto-generated method stub
}
}

17. Add the following code to the loadFeature() function. Also the parameters of this
function have been renamed to clarify their purpose. The loadFeature() function is
called when a BlackBerry Widget application loads a web resource that makes use of
the feature defined by this extension:

package widgetpackage;

import org.w3c.dom.Document;

import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.script.ScriptEngine;
import net.rim.device.api.web.WidgetConfig;
import net.rim.device.api.web.WidgetExtension;

public final class SampleExtension implements WidgetExtension {

public String[] getFeatureList() {


String[] result = new String[1];
result[0] = "sample";
return result;
}
16 | P a g e

public void loadFeature(String feature, String version,


Document doc, ScriptEngine scriptEngine) throws Exception {

if (feature == "sample") {
scriptEngine.addExtension("sample.alert", new AlertSample());
}

public void register(WidgetConfig arg0, BrowserField arg1) {


// TODO Auto-generated method stub
}

public void unloadFeatures(Document arg0) {


// TODO Auto-generated method stub
}
}

18. The source code for your custom JavaScript extension is now complete. You have
written Java code that will invoke the vibration feature of the BlackBerry smartphone for
a fixed period of time. The next step is to export this code as a JAR file that will be used
by the BlackBerry Web Plug-in during the packaging of a Widget application.

Deploying a Custom JavaScript Extension to be used by the BlackBerry


Web Plug-in

The source code for the custom JavaScript extension will be exported to a JAR file using the
BlackBerry JDE Plug-in for Eclipse 1.1. . This JAR file is then used within a BlackBerry
Widget project, created using the BlackBerry Web Plug-in for Eclipse or Microsoft Visual
Studio.

You will use the BlackBerry JDE Plug-in for Eclipse 1.1 to export the source code for the
linked JavaScript extension to a JAR file.

1. Right click on the src folder in your project and select New à Other to add an XML file
named library.xml to your project:
17 | P a g e

2. Choose file type of XML and click on the Next button:


18 | P a g e

3. Enter the file name library.xml and click on the Finish button:

4. The library.xml file will be created with the following contents:

<?xml version="1.0" encoding="utf-8"?>

5. Add for the following XML meta data to the library.xml file. This information will be
used by the BlackBerry Web Plug-in to correlate a feature ID with the internal class
name of this JavaScript extension:

<?xml version="1.0" encoding="utf-8"?>


<library>
<extension>
<entryClass>widgetpackage.SampleExtension</entryClass>
19 | P a g e

</extension>
<features>
<feature id="sample" version="1.0.0" >My sample alert JavaScript
extension</feature>
</features>
</library>

6. From within the Package explorer window in Eclipse, right click on your
MyWidgetExtension project name and select “Export …” from the menu.

7. Expand the “Java” item and select JAR file as the export destination. Click Next:
20 | P a g e

8. You will only want to export the contents of the SRC and RES folders. De-select all
checkboxes except for those shown in the following screenshot. Also make sure the
“Export Java source files and resources” checkbox is selected. Choose an
appropriate location to export the JAR file to and click on the Finish button:
21 | P a g e

9. You can confirm the JAR file was exported successfully by navigating to the directory
you chose to export to using file explorer. This folder should now contain a JAR file
which, when opened using an archive utility (e.g. WinZip) contains the source code of
your customized JavaScript extension:
22 | P a g e

The next and final step will be to use the BlackBerry Web Plug-in for Eclipse or Microsoft
Visual Studio to create a BlackBerry Widget application that makes use of the “sample”
extension.
23 | P a g e

Creating a BlackBerry Widget that uses a Custom JavaScript Extension

Now you will use either the BlackBerry Web Plug-in for Eclipse or the BlackBerry Web Plug-
in for Microsoft Visual Studio build a BlackBerry Widget application. This application will
present a single text input field and button. The user may enter a numeric value in the text
input field that corresponds to the number of milliseconds to vibrate the device when the
button is clicked.

1. Begin by creating a BlackBerry Widget Project. You will notice that two files and one
folder are automatically created within your project:
o config.xml – a configuration document that defines the characteristics and
features of a BlackBerry Widget.
o index.html – the initial file that will be used to render content in a compiled
BlackBerry Widget.
o Extension / ext – a folder that will contain JavaScript extension JAR files

Using the BlackBerry Web Plug-in for Eclipse:

a. Select New à “BlackBerry Widget Project” from the File Menu.

b. Specify “alertWidget” as the project name and click Finish


24 | P a g e

Using the BlackBerry Web Plug-in for Microsoft Visual Studio:

a. Select “New Project” from the File Menu

b. Create a new BlackBerry Widget Project, named “alertWidget”:

2. Add the JAR file for the “alert” JavaScript extension to the Extensions / ext
folder within the BlackBerry Widget project:

Using the BlackBerry Web Plug-in for Eclipse:

a. Right click on the “ext” folder within the Package Explorer window
25 | P a g e

b. Select New àOther … from the popup menu (Do not select the “Import …”
menu item):

c. From the New window that opens, expand and select “File” from the “General”
tree and click Next:
26 | P a g e

d. Click on the “Advanced >>” button and select the “Link to file in the file system”
checkbox:
27 | P a g e

e. Click on the “Browse …” button and navigate to the location where you
exported the JAR file for the alert JavaScript extension.

f. Select the JAR file and click Finish. Verify the alert extension has successfully
been added to the BlackBerry Widget Project. A single JAR file should exist
within the ext folder:
28 | P a g e

Using the BlackBerry Web Plug-in for Microsoft Visual Studio:

a. Right click on the “Extension” folder within the Solution Explorer window

b. Select Add à Existing Item from the popup menu

c. Navigate to the location where you exported the JAR file for the alert JavaScript
Extension and click on the Add button
29 | P a g e

d. Verify the alert extension has successfully been added to the BlackBerry
Widget Project. A single JAR file should exist within the Extensions folder:

3. Modify the config.xml document to recognize the newly added JavaScript


extension API, by adding a feature element. This feature can be accessed by
JavaScript processed internally within a BlackBerry Widget application:

Using the BlackBerry Web Plug-in for Eclipse:

a. Open the config.xml file and open the “Widget Permissions” tab, located at
the bottom of the screen:

b. Select the “Local” node, and click on the “Add Feature” button.

c. A popup window will appear listing all BlackBerry Widget APIs that are
available for use. The “sample” API should be listed as it has been referenced
in the project as the alert JavaScript Extension. Select the “sample” item and
click OK
30 | P a g e

d. Confirm that the sample feature was successfully added to the widget
permissions:

Using the BlackBerry Web Plug-in for Microsoft Visual Studio:

a. Open the config.xml file and scroll to the “Widget Permissions” section,
located at the bottom of the document:
31 | P a g e

b. Select the “Local” node, and click on the “Add Feature” button.

c. A popup window will appear listing all BlackBerry Widget APIs that are
available for use. The “sample” API should be listed as it has been referenced
in the project as the alert JavaScript Extension. Select the “sample” checkbox
and click OK.
32 | P a g e

d. Confirm that the sample feature was successfully added to the widget
permissions:

4. Modify index.htm page content to provide input mechanism for invoking logic built
into alert JavaScript extension:

Using either BlackBerry Web Plug-in for Eclipse or Microsoft Visual Studio:

a. Open the index.htm file. This file should contain the following HTML
content:

<html>
<head>
<meta name="viewport" content="user-scalable=no,
width=device-width; height=device-height" />
<title>Untitled Page</title>
</head>
<body>
Hello World
</body>
</html>

b. Modify the index.htm file by adding the following HTML input fields. These
input fields be used to invoke the vibrate feature of the BlackBerry Smartphone
for a given period of time:

<html>
<head>
<meta name="viewport" content="user-scalable=no,
width=device-width; height=device-height" />
<title>Untitled Page</title>
</head>
33 | P a g e

<body>
Duration
<input type="text" id="txtLength" value="1000"/> (ms)
<input type="submit" value="Alert"/>
<br/>
* Click on the 'Alert' button to vibrate the BlackBerry
Smartphone.
</body>
</html>

c. Add the following JavaScript to the index.htm file. This code invokes the
functionality provided by the alert JavaScript extension when a user clicks on
the “Alert” button, passing a single value (the duration of time, provided by the
user in the text field) as a parameter:

<html>
<head>
<meta name="viewport" content="user-scalable=no,
width=device-width; height=device-height" />
<title>Untitled Page</title>
<script type="text/JavaScript">
function vibrateAlert()
{
if (sample.alert.vibrateSupported)
{
var ele = document.getElementById("txtLength");
var iDuration = parseInt(ele.value);
sample.alert.vibrate(iDuration);
}
else
alert('sample.alert.vibrate not supported');
}
</script>
</head>
<body>
Duration
<input type="text" id="txtLength" value="1000"/> (ms)
<input type="submit" value="Alert" onclick="vibrateAlert()"/>
<br/>
* Click on the 'Alert' button to vibrate the BlackBerry
Smartphone.
</body>
</html>
34 | P a g e

5. Start a new debug session to test your Widget. The BlackBerry Web Plug-in will
package your Widget application and deploy it to a new instance of the BlackBerry
smartphone simulator. Click on the “Alert” button and watch as the Smartphone
Simulator vibrates.
35 | P a g e

Check your work

Compare your work to the files found in the


install_folder\Labs\Lab_Widget_Extension\solution folder.

Advanced Developers

Try repeating this exercise but this time make appropriate changes to use the
net.rim.device.api.system.LED class to change the state of the BlackBerry
smartphone when LED the user clicks on the “Alert” button from within the BlackBerry
Widget.

Hint: See BlackBerry JAVA API Reference for information on the LED class.

http://www.blackberry.com/developers/docs/5.0.0api/index.html

Review

In this exercise, you built a BlackBerry Widget that uses a Custom JavaScript extension to
programmatically invoke the device vibration capability.

This Lab has demonstrated how you can add new features to the Widget SDK and extend
the functionality of the BlackBerry Widget API through the creation of your own customized
JavaScript extensions.
36 | P a g e

Links

BlackBerry Widgets home page:


http://www.blackberry.com/developers/widgets

BlackBerry® Developer Zone

http://www.blackberry.com/developers

BlackBerry App World™:


http://na.blackberry.com/eng/developers/appworld.jsp

Developer Video Library:


http://na.blackberry.com/eng/developers/resources/videolibrary.jsp

Documentation:
http://na.blackberry.com/eng/support/docs/developers/?userType=21

Knowledge Base Articles:


http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/cus
tomview.html?func=ll&objId=348583

BlackBerry Development Community Forums:


http://supportforums.blackberry.com/rim/?category.id=BlackBerryDevelopment

© 2010 Research In Motion Limited. All rights reserved. BlackBerry®, RIM®, Research In Motion®,
SureType®, SurePress™ and related trademarks, names and logos are the property of Research In Motion
Limited and are registered and/or used in the U.S. and countries around the world.

Das könnte Ihnen auch gefallen