Posts Tagged ‘Blackberry’
20
Jul

The concept of retrieving location information using GPS device and Location API is already discussed in one of the earlier post (http://www.xoriant.com/blog/mobile-application-development/location-based-programming.html ). In this article we are going to learn to use of Blackberry’s Location API and work with geocoding and reverse geocoding. Though, Geocoding and reverse Geocoding information could be used in multiple applications, a majority of applications will need to integrate the location information and display that on a Map.

To start with, let me introduce some terms:

Geocoding: is the process of finding associated geographic coordinates (often expressed as latitude and longitude) from other geographic data, such as street addresses, or zip codes (postal codes). With geographic coordinates, the features can be mapped and entered into Geographic Information Systems, or the coordinates can be embedded into media such as digital photographs via geotagging.

Reverse Geocoding: is the process of back (reverse) coding of a point location (latitude, longitude) to a readable address or place name. This permits the identification of nearby street addresses, places, and/or real subdivisions such as neighborhoods, county, state, or country. Combined with geocoding and routing services, reverse geocoding is a critical component of mobile location-based services to convert a coordinate obtained by GPS to a readable street address which is easier to understand by the end user.

Before we see the code part, let us look at the BlackBerry API (Locator) that facilitates the application to gain access to geospatial coordinates for an address and vice-versa i.e.  retrieve a street address for given coordinates in case of reverse geocoding.

Locator is a Geocoding service in BlackBerry that allows you to obtain location address for an address. This service has static method “geocode”, “reverseGeocode” and as it should be obvious by now, geocode require address and returns coordinates, reverseGeocode require coordinates and returns the address information.

There are few things to keep in mind while Locator is used in the application

  1. LBS Map API is a pre-requisite for Locator API to work. Application may throw exception if the LS MAP API is not installed.
  2. Call to geocode is synchronous in nature. And at any given time there should be one call made using the Locator class. Application may throw exception if more than one call is made.
  3. Call to geocode and reverseGeocode should be made outside the event dispatch thread. Requests to these methods that are made on the event dispatch thread are denied and result in an exception.

Let us look how to use the Locator API to retrieve geospatial coordinates for an address using geocode.

  • Packages required
import net.rim.device.api.lbs.*;
import javax.microedition.location.*;
  • Create a class and constructor
public class myGeocode
{
public myGeocode()
{

}
}
  • Create a private Thread variable
private Thread geocoder;
  • In constructor, create instance of the Thread class. As mentioned earlier, geocode cannot be performed on the application’s primary thread.
geocoder = new Thread(thread);
geocoder.setPriority(Thread.MIN_PRIORITY);
geocoder.start();
  • In the class, create a Thread that invokdes a public run() method.
Runnable thread = new Runnable() {

public void run() {

AddressInfo addrInfo = new AddressInfo();

addrInfo.setField(AddressInfo.STREET, "Whitewood Dr");

addrInfo.setField(AddressInfo.CITY, "San Jose");

addrInfo.setField(AddressInfo.STATE, "California");

addrInfo.setField(AddressInfo.POSTAL_CODE, "95110");

addrInfo.setField(AddressInfo.COUNTRY, "US");

Coordinates startCoords = new Coordinates(37.386087,-121.889244, Float.NaN);

try {

Landmark[] results = Locator.geocode(addrInfo, startCoords);

}

catch ( LocatorException lex ) {

//thrown when The BlackBerry device is not sufficiently connected to send or receive over any transport.

}

catch (MapServiceException mex) {

// if the LBS Map API is not installed on a BlackBerry device or if an application makes more than one request at a time.

}

catch (IllegalThreadStateException itex) {

// if a request is made on the event dispatch thread

}

catch(IllegalStateException isex) {

// if there is no valid radio/wi-fi connection to send the request to

}

}

};
  • The new two classes used above AddressInfo and Landmark, they allow application to pass formatted address object. However, overloaded geocode also accept “String” (e.g. Whitewood Dr, San Jose, Santa Clara, California 95110). This should also work and return the array of Landmark, the first array element contains the most relevant Landmark to the locator request. May be null if geocode request is cancelled or the request fails.
  • startCoords are for hint to the geocode for starting the search specified in the request. This could also be null.
  • Using the same class structure, let us see how to get the address info using coordinates.
Runnable thread = new Runnable() {

public void run() {

AddressInfo addrInfo = null;

int latitude = (int)(45.423488 * 100000);

int longitude = (int)(-80.32480 * 100000);

try {

Landmark[] results = Locator.reverseGeocode

(latitude, longitude, Locator.ADDRESS );

if ( results != null && results.length > 0 )

addrInfo = results[0].getAddressInfo();

} catch ( LocatorException lex ) {

//do something

}

}

};
  • Pass one of the following parameters to Locator.reverseGeocode():
    • Locator.ADDRESS: requests the nearest address or nearest street to the specified latitude/longitude
    • Locator.CITY: returns a value that is focused on the city level Development Guide Retrieve an address by using reverse geocoding 44
    • Locator.COUNTRY: returns a value that is focused on the country level
    • Locator.PROVINCE_STATE: returns a value that is focused on the province or state level

Now, we’ve seen how to use the Locator API to get geospatial and address information. When we talk about coordinates, the next thing that comes to mind is how the same code can be extended to show the location on a map.

Well, BlackBerry also has a Map API that allows us to extend the above example and use the information as is i.e. to plot the address point on a map.

  • Package required
import net.rim.blackberry.api.invoke.*;
import net.rim.blackberry.api.maps.*;
  • Maps is an inbuilt application in BlackBerry. This eliminates the user from writing core Map logic like displaying images, , calling Google Maps API and rendering the image in the application. All we have to do is invoke the external application (external to your application).
  • Create class and constructor
public class showMap {
public showMap ()
{
}
}
  • In constructor create an instance of MapView
MapView mapView = new MapView();
mapView.setLatitude(4328915);
mapView.setLongitude(-8032480);
mapView.setZoom(10);
  • In the constructor, create an instance of the MapsArguments class using the MapView object as an argument. Invoke Invoke.invokeApplication() to open BlackBerry Maps and pass in the MapsArguments object.
MapsArguments mapsArgs = new MapsArguments(mapView);
Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, mapsArgs);

Or you can also use the Lankmark object return by Locator.geocode

MapsArguments mapsArgs = new MapsArguments(results);
Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, mapsArgs)

Location Based applications that incorporate maps are everywhere. The BlackBerry platform allows you to incorporate both location information and merge that into maps as we have seen in the blog post. It is important to note that the BlackBerry platform provide additional ways of showing a map using different inputs. You can also embed the map  within the application. What I have covered here are the basics and hope that this article highlights the important nuances that could be useful for developers to try things quickly and then extend the same by building more complex applications.

Pawan Sachdeva
Pawan Sachdeva– Technical Architect

07
Jul

A BlackBerry phone is primarily a business phone with additional features like Email, Phone, Maps, GPS, Organizer, Social Networking and games. Developers can take advantage of various BlackBerry APIs to take the user experience to a new level. In this article, I am going to talk about BlackBerry and Location API,that allows you to develop Location based (LB) applications.

Compatibility

BlackBerry is packed with advanced features, but they are not supported in all models. Let us quickly have a glance at some of the models.

In general there are two options for using GPS with a BlackBerry. You either have a device with an internal GPS receiver, or you will need an external Bluetooth GPS receiver, which will provide the GPS data to your BlackBerry. Refer to this link to find out the models which support GPS http://na.blackberry.com/eng/devices/features/gps.jsp

Do not be disappointed if your preferred model is not the list, you can always download the simulator from https://www.blackberry.com/Downloads/entry.do

Though, the above list mentions about GPS support by default, it should also be noted that there will be existing applications developed based on JSR 179 java ME api even if the model doesn’t not have inbuilt GPS support. GPS capabilities could also be obtained by connecting to an external GPS device over Bluetooth, but this comes with its own set of challenges. Another option is for old blackberry models (RIM 857/957), which works with a serial GPS receiver attached via cable.

Overview

You must enable GPS on your device, for applications to retrieve the current location. The location is nothing but coordinates for latitude, longitude and altitude.

Additionally, support for JSR 179 Location API for Java ME comes with device software 4.0.2 and later. If you want BlackBerry extensions to JSR 179, you will need device software 5.0.0 and later.

To obtain a location via the GPS support in your device, your application has to do the following:

○   Specify the GPS mode

○   Get the location provider

○   Make GPS request

○   Retrieve the GPS location of a BlackBerry device

Code sample: Specifying the GPS mode

/* JSR 179 */
Criteria myCriteria = new Criteria();
/* JSR 179 extension */
BlackBerryCriteria myBlackBerryCriteria = new BlackBerryCriteria(…);

Dig Deep

There are three GPS modes and they have speficic properties that are described below. You will need to select one based on your application requirements.

○   Autonomous – relies on the GPS satellite only. This mode uses the GPS receiver on the BlackBerry device to retrieve location information. This mode cannot be used indoors or in close proximity to many physical obstructions, and it can take several minutes to fully synchronize with four or more satellites for the first GPS fix. An example application that can use this mode is a Car Parking Spot application.

○   Assisted Mode – GPS satellite and servers on the wireless network only. This mode uses the wireless network to retrieve satellite information. This mode can achieve a fast retrieval of the first GPS fix. An example application that can use this mode is a Nearby Restaurants application.

○    Cell site Mode – Geolocation service or the wireless network to provide on the location information of current base station. This mode uses the wireless network to achieve the first GPS fix, and is generally considered the fastest mode. This mode does not provide BlackBerry device tracking information such as the speed and the bearing. An example application that can use this mode is a Weather Application.

Let us look at the code samples to use the BlackBerry API to get location and satellite information. The code fragments are used to highlight the API rather than give a fully working GPS Application that also provides additional value added information.

First, let us look at a Java class GPSSatteliteInfo listed below. This is a utility class in which we will wrap all the GPS related sample code. The thread implementation is currently empty.

/* packages to import */
import java.util.*;
import java.lang.*;
import net.rim.device.api.gps.*;
/* create public class */
public class GPSSatelliteInfo {
	/* member variables */
	…
	public GPSSatelliteInfo() {
		gpsThread = new GPSThread(); //private thread class reference
		gpsThread.start();
	}
	/* private thread class */
	private static class GPSThread extends Thread
	{
		public void run()
		{
			//do something
		}
	}
}

○   Next, specify the GPSMode inside the run() method of Thread class

BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_AUTONOMOUS);
//OR  to be on safer side
BlackBerryCriteria myCriteria = new BlackBerryCriteria();
if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST))
	myCriteria.setMode(GPSInfo.GPS_MODE_ASSIST);
else if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_AUTONOMOUS))
	myCriteria.setMode(GPSInfo.GPS_MODE_AUTONOMOUS);

○   Next, get the LocationProvider and create a BlackBerryLocation object to retrieve the GPS fix including a 300 second timeout expiry.

BlackBerryLocationProvider myProvider;
myProvider  = (BlackBerryLocationProvider) LocationProvider.getInstance(myCriteria);
BlackBerryLocation myLocation;
myLocation = (BlackBerryLocation) myProvider.getLocation(300);

○   Retrieve the satellite information

satCount  = myLocation.getSatelliteCount();
signalQuality  = myLocation.getAverageSatelliteSignalQuality();
dataSource  = myLocation.getDataSource();
gpsMode  = myLocation.getGPSMode();
SatelliteInfo si;
StringBuffer sb = new StringBuffer("[Id:SQ:E:A]\n");
String separator = ":";
for( Enumeration infoEnum  = myLocation.getSatelliteInfo(); infoEnum != null; infoEnum.hasMoreElements();){
	si = (SatelliteInfo)e.nextElement();
	sb.append(si.getId() + separator);
	sb.append(si.getSignalQuality() + separator);
	sb.append(si.getElevation() + separator);
	sb.append(si.getAzimuth());
	sb.append('\n');
}

Note:The assisted mode can be used with BlackBerry devices that are associated with a CDMA network that utilizes PDE server technology. The assisted mode is designed to provide fast retrieval of a GPS fix. Assisted GPS capabilities are currently defined by wireless service providers. In many instances, you must enter into a formal relationship with wireless service providers before you can connect to their PDE server.

if ( !GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST) || !GPSSettings.isPDEInfoRequired(GPSInfo.GPS_MODE_ASSIST))
	return;

On similar lines, let us see how to retrieve location information.

static double lat, lon;
static float alt, spd, crs;
lat = myLocation.getQualifiedCoordinates().getLatitude();
lon = myLocation.getQualifiedCoordinates().getLongitude();
alt = myLocation.getQualifiedCoordinates().getAltitude();
spd = myLocation.getSpeed();
crs = myLocation.getCourse();

This covers how to retrieve satellite information and location coordinates.

However, there is a lot more that an application should do to provide a good user experience. Majority of times it is driven by the kind of application being developed. For example, if the application is designed to display my location on a map at a given time, then retrieving GPS location one time should suffice. But, at the same time, if the application is designed to keep retrieving the GPS coordinates as person moves some distance, then something more needs to be done. One way is to use the  setLocationListener() by passing the interval value, timeout value, and maximum age as parameters to add a LocationListener.)

myProvider.setLocationListener(new handleGPSListener(), 10, -1, -1);

In the class, implement the LocationListener interface. Implement the basic framework for the locationUpdated () method, and the providerStateChanged() method.

public static class handleGPSListener implements LocationListener
{
	public void locationUpdated(LocationProvider provider, Location location)
	{
		if (location.isValid())
		{...}
		else
		{... }
	}
	public void providerStateChanged(LocationProvider provider,	int newState)
	{
		if (newState == LocationProvider.AVAILABLE)
		{...}
		else if (newState == LocationProvider.OUT_OF_SERVICE)
		{...}
		else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE )
		{...}
	}
}

This gets invoked at a fixed interval to any location changes. This is ideal for application that is plotting user movement over a map. (Similar to the GPS navigation device to get directions).

We have now covered how to use the BlackBerry JSR 179 extension (aka GPS API) to get satellite and location coordinates. The code covered so far provides a basic working example to retrieve the satellite and location information. The same could be extended to  make complex applications. There are other areas which are “good to know” like GPS error code, Location error codes, control the power consumption, preferred response time, manage cost allowed, setting the failover mode (fall back on other available options if one is not available), etc and the reader is advised to refer to the available documentation.

Location Based Services and applications are growing in importance. The BlackBerry platform provides good support for you to get started with building location based applications today. In future posts, we shall delve into deeper topics that help you to take advantage of the full range of BlackBerry location based APIs.

Pawan Sachdeva
Pawan Sachdeva– Technical Architect

, ,

15
Jun

In this blog post, we shall take a look at how to get started with programming for the BlackBerry device. We shall cover what the device is, give you an overview of BlackBerry development and then provide you with detailed steps to setup your development environment. Future blog posts will focus on programming on the BlackBerry.

What is a BlackBerry Device?

The BlackBerry is a wireless handheld device developed by the Canadian company known as Research In Motion (RIM) and was launched in year 1999. It holds 20.8% market share in worldwide Smartphone sales, making it the second most popular platform after Nokia. It is known as the most popular Smartphone around the world for its connectivity and security.

Its primary goal is to support push e-mail, web browsing, text messaging and other wireless internet services in a secure manner. Now a days the BlackBerry devices are integrated with advanced software’s which enable access to wide range of data, communications services, Email, phone, maps, GPS, organizer, social networking, games and other applications. These features of a Smartphone make life easy by allowing access to everything on the move at any place in the world on your fingertips.

The BlackBerry software development kit is a wide collection of examples, documentation, and mature set of APIs and tools grown in an extensive manner, which have shown the directions to develop all kinds of great applications. BlackBerry community and its App World help to get your application noticed and downloaded by users worldwide.

The list of BlackBerry device and its models:

BlackBerry Development Platform consists of:

BlackBerry Development Environment is completely based on the Java Platform. It is collectively integrated with BlackBerry RIM APIs, J2ME APIs and basic Java SE APIs. It is built on top of Java Micro Edition (Java ME) which itself is derived from Java SE.  In order to get into the BlackBerry Application development one need to know Object Oriented programming with the basic understanding of J2ME concepts of configurations and profiles, and in particular the CLDC and MIDP standards.

The BlackBerry Development Environment tools:

The BlackBerry application can be developed on any platform, even in Linux, OSX, the easiest and best supported is Windows 32bit platform. RIM provides two BlackBerry development environments such as:

  • BlackBerry Java Development Environments (JDEs) and
  • BlackBerry Eclipse Plug-in.

Both Blackberry development environment tools work with standard Java Software Development Kit (Java SDK) and fully integrated with development tools, simulators and provides to necessary to create, package, compile, test and debug the Blackberry application. You don’t even need the real handheld device to test the application, because it also includes the full featured Blackberry device simulator. A complete set of BlackBerry JDE API Doc is available for referring available packages and classes for development. Both the development tools are being used by many professional developers to develop BlackBerry applications. We will look into both the tools in detail. The best thing about BlackBerry development tools is that they are absolutely free.

Now we will see the step by step installations for both BlackBerry Java Development Environments (JDEs) and BlackBerry Eclipse Plug-in.

Let’s Start with Installation process:

BlackBerry Java Development Environments (JDEs)

Installing the BlackBerry JDE is very easy as compared to any other tools:

  1. Before installing the Blackberry development tools, you will need to install Java SE Development Kit (JDK) version 5 or later from http://java.sun.com. Which version has to be downloaded will depend on the version of Blackberry platform you want to target. The Java SE JDK v6.0 helps you to develop for BlackBerry Device Software version 4.2 or later. More specific information is available on the BlackBerry Developer page at http://na.blackberry.com/eng/developers/javaappdev/javadevenv.jsp
  2. Now you download appropriate version of BlackBerry Java Development Environment (JDE) from BlackBerry Developer Zone at http://www.blackberry.com/developers/ , you have to register an account. Free Developer tools, whitepapers, the developer Knowledge base and the Blackberry Developer forums are found here. (BlackBerry JDE versions: The BlackBerry OS is backward compatible, So something developed on OS 4.2 will work on OS 4.3 and later without requiring code changes done. It may be the case where certain features are only supported on higher versions. But most of the basic features are covered from OS 4.2)
  3. Once the BlackBerry JDE installer is downloaded, run the installer and follow the on-screen instructions. It will be installed to the default path C:\Program Files\Research In Motion\BlackBerry JDE 4.5.0, which can be changed during installation.
  4. Launch the BlackBerry JDE from Start>Program Files>Research In Motion> BlackBerry JDE 4.5>JDE.
  5. Once the BlackBerry JDE is launched it will look as shown in Figure 1.0. The left hand pane shows sample.jdw workspace, the right hand side shows the HelloWorldDemo.java file in editor. The sample.jdw workspace contains the Blackberry sample examples and it is located in the BlackBerry JDE folder at C:\Program Files\Research In Motion\BlackBerry JDE 4.5.0\samples. The BlackBerry API reference doc can be found in via Help>API Reference in the JDE.

BlackBerry JDE v4.2.1 with workspace in left hand side pane, source code editor in right hand side and console at the bottom

The BlackBerry JDE v4.2.1 with workspace in left hand side pane, source code editor in right hand side and console at the bottom.

BlackBerry Eclipse Plug-in installation:

You can download the Eclipse IDE at http://www.eclipse.org/downloads/ . Don’t forget to install the Java Development Kit as a pre-requisite as explained in step 1 of the BlackBerry JDE installation. And download the plug-in from BlackBerry tools at http://na.blackberry.com/eng/developers/resources/devtools.jsp

Perform the following steps to install the BlackBerry Eclipse Plug-in with Eclipse IDE of Java Development version 3.4.0.

  1. Start Eclipse
  2. From the main menu, Select Help > Software Updates.
  3. In the Software Updates and Add-ons dialog, click the Available Software tab.
  4. Click the Add Site button.
  5. In the Add Site dialog, click the Archive button.
  6. In the Repository archive dialog, select the .zip file to install.
  7. Click Open.
  8. In the Add Site dialog, click OK.
  9. Select the check box for the BlackBerry JDE Plug-in for Eclipse. All subcomponents should be checked automatically.
  10. Click Install.
  11. Click Finish.
    When the installation completes, the Software Updates dialog is displayed.
  12. Click Yes to restart Eclipse.

I hope this post is helpful in understanding the BlackBerry Environment, tools and its installation process. If you have any queries feel free to comment.

Siddhesh Bingi
Siddhesh Bingi– Member of Mobile Center of Excellence

, , , ,

24
Nov

Enterprise software is now going mobile. More and more work, which needed your presence in office/home, can be done on-the-go. With introduction of addictive UIs on smart phones, the market for Mobile based Software has grown into a new niche.

Smart phone applications can be categorized in to Native Applications and Web Applications. Native apps are downloaded on the device may or may not require internet connectivity. Most of the games and utilities like calculator, unit-converter fall in this category. Web Apps are applications that run on the device’s inbuilt browser. It does not need downloading, but requires continuous internet connectivity in most cases.

Both types of applications on Mobile can be developed by following these interdependent life cycle stages:

1. Design: A typical smart phone dimensions of 320×480 gives a very limited real estate to stuff-in the amazing functionalities they can support. Designers really need to master the art of small.

Native

The design needs to be in alignment with various UI standards and can closely follow Human Interface Guidelines(HIG) from Apple. Though they have defined it for iPhone, many of them in my opinion are pure common sense. Hence, HIG is applicable for all devices, specifically for the Native apps. The smart-phone vendors (RIM, Apple etc.) have gone a long way in providing standard and useful applications to their users via their own app-stores.

Web Based

In web based application development, for multiple devices for e.g. for iPhone and Blackberry Bold, design issues need to be taken care at the CSS level. For lower versions of Blackberry though UI has to be generated by a different code set.

2. Server side: APIs not only cater to web based mobile applications, native applications too need to shift the data intensive computation to server side. So there is not much difference between the server side programming for Web and Native apps. Bringing website functionality to mobile is not mere reuse of APIs. It involves optimization of existing APIs for performance. It may also involve revisiting the code for adding device specific checks, abstraction and exception handling etc.

3. Client side: iPhone, Blackberry, Android, Windows Mobile, Symbian have their own SDKs for development of Native Apps. While iPhone requires experience on Objective C and Mac OS, Blackberry and Android can be handled by Java developers while Windows mobile application can be created using Visual Studio 2008.

Native

Advanced hardware like inbuilt camera, accelerometers etc can also be harnessed for making the mobile application feature-rich – like Auto-orientation, motion based gaming etc. The inbuilt GPS and assisted GPS can be leveraged for creating location based services. Though a plethora of applications are already providing LBS, I find it to be a tip of the iceberg. Adding LBS can make a lot of applications information rich, for end users as well as for vendors, distributors and advertisers.

Web Based

Web based applications on almost all devices, sparing iPhone in some cases; do not need specified SDKs for development. The major issue for web based apps is handling the large number of device-browser combinations that a user may use. What works for IE on BB may not work for FF on the same device. To resolve the issue of developing and maintaining code for different devices XHTML-MP is gaining wide popularity among developers.

4. Testing: Other than functionality and UI related testing, Mobile app QA requires testing for performance and connectivity related issues.

Native

Mobile software requires to be tested in real (non-simulated) Wi-Fi, GPRS, 3G etc. with different service providers. Something that works on AT&T may be blocked by T-Mobile. Also, an internet savvy application may behave differently in different geographies. Based on expected usage, the application should be tested for all the geographies. One may take assistance from www.deviceanywhere.com.

Web Based

Web apps always need to be tested on variety of browsers (Mobile browsers) for rendering issues. iPhone supports Safari, while BB supports IE and Firefox and also has it’s own browser. Rigorous manual testing can reveal functionality glitches and alignment issues. Generally for all types of browsers, testing and debugging using Firebug and HTTP watch can be quite helpful.

One should plan the development of mobile applications with these distinct yet interdependent processes in mind. It should really help in developing a standard application in minimum time.

-Ujjwal Trivedi

, , , , ,