BlackBerry - Get Location from GPS, webservice or cell tower - blackberry

I am attempting to get location in BlackBerry. I am able to acquire the location successfully through GPS or Google Web service. If GPS is unavailable (inside a building) or not supported in the handset, location is acquired through Google Web service. However I would like to update this class to do the following:
1) Check if GPS is available -> Get Location from GPS
2) Else Check if internet is available -> (Yes) Get Location from Google Webservice
3) (No) Get Location from mobile network cell tower
4) Update the location continuously after a given interval (10-20 seconds)
Kindly help.
public class GPSHandler {
private GPSThread _gpsThread;
private Coordinates _location;
private boolean _gotLocation;
private GPSListener _listener;
/** this class will be a Singleton, as the device only has one GPS system */
private static GPSHandler _instance;
/** #return the Singleton instance of the GPSHandler */
public static GPSHandler getInstance() {
if (_instance == null) {
_instance = new GPSHandler();
}
return _instance;
}
/** not publicly accessible ... use getInstance() */
private GPSHandler() {
_gpsThread = new GPSThread();
// NOTE: you might not want to call start() unless you have a listener.
// Otherwise, just make sure to handle the case where the location is
// received before setListener() is called.
_gpsThread.start();
}
public void setListener(GPSListener listener) {
// only supports one listener this way
_listener = listener;
}
private void setLocation(final Coordinates value) {
_location = value;
if (value.getLatitude() != 0.0 || value.getLongitude() != 0.0) {
_gotLocation = true;
if (_listener != null) {
// this assumes listeners are UI listeners, and want callbacks on the UI thread:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_listener.onLocationReceived(value);
}
});
}
}
}
private class GPSThread extends Thread {
private void getLocationFromGoogle() {
try {
int cellID = GPRSInfo.getCellInfo().getCellId();
int lac = GPRSInfo.getCellInfo().getLAC();
String urlString2 = "http://www.google.com/glm/mmap";
// Open a connection to Google Maps API
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(urlString2);
HttpConnection httpConn2;
httpConn2 = (HttpConnection)connDesc.getConnection();
httpConn2.setRequestMethod("POST");
// Write some custom data to Google Maps API
OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream();
writeDataGoogleMaps(outputStream2, cellID, lac);
// Get the response
InputStream inputStream2 = httpConn2.openInputStream();//getInputStream();
DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
// Interpret the response obtained
dataInputStream2.readShort();
dataInputStream2.readByte();
final int code = dataInputStream2.readInt();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(code + "");
}
});
if (code == 0) {
final double latitude = dataInputStream2.readInt() / 1000000D;
final double longitude = dataInputStream2.readInt() / 1000000D;
setLocation(new Coordinates(latitude, longitude, 0.0f));
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(latitude+"-----"+longitude);
}
});
dataInputStream2.readInt();
dataInputStream2.readInt();
dataInputStream2.readUTF();
} else {
System.out.println("Error obtaining Cell Id ");
}
outputStream2.close();
inputStream2.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private void tryGetLocationFromDevice() {
_gotLocation = false;
try {
Criteria myCriteria = new Criteria();
myCriteria.setCostAllowed(false);
LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
try {
Location myLocation = myLocationProvider.getLocation(300);
setLocation(myLocation.getQualifiedCoordinates());
} catch ( InterruptedException iex ) {
System.out.println(iex.getMessage());
} catch ( LocationException lex ) {
System.out.println(lex.getMessage());
}
} catch ( LocationException lex ) {
System.out.println(lex.getMessage());
}
if (!_gotLocation) {
getLocationFromGoogle();
}
}
public void run() {
int bbMapsHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs"); // OS 4.5 - 6.0
int bbMapsHandle60 = CodeModuleManager.getModuleHandle("net_rim_bb_maps"); // OS 6.0
if (bbMapsHandle > 0 || bbMapsHandle60 > 0) {
tryGetLocationFromDevice();
} else {
getLocationFromGoogle();
}
return;
}
}
private void writeDataGoogleMaps(OutputStream out, int cellID, int lac) throws IOException {
DataOutputStream dataOutputStream = new DataOutputStream(out);
dataOutputStream.writeShort(21);
dataOutputStream.writeLong(0);
dataOutputStream.writeUTF("en");
dataOutputStream.writeUTF("Android");
dataOutputStream.writeUTF("1.0");
dataOutputStream.writeUTF("Web");
dataOutputStream.writeByte(27);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(3);
dataOutputStream.writeUTF("");
dataOutputStream.writeInt(cellID);
dataOutputStream.writeInt(lac);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.flush();
}
}

Related

BlackBerry Refresh location via GPS or Cell Tower

I am trying to refresh the current location through a click of a button. The location can be acquired via GPS or Cell Tower, whichever is available. My problem is I never see the "Loading Screen". I know it appears as something appears/closes instantly while the coordinates remain zero. Can somebody help me - what I am doing wrong below?
Neither the location is updated nor the loading screen appears. Without the loading screen and by multiple clicks of the "refresh button" I do get the location. Below is my code for handling clicks on the "Refresh Button":
FieldChangeListener refreshImgListener = new FieldChangeListener() {
public void fieldChanged(Field field, int context)
{
Thread backgroundWorker = new Thread(new Runnable() {
public void run() {
refreshCoordinates();
}
});
busyDialog.setEscapeEnabled(false);
busyDialog.show();
backgroundWorker.start();
}
};
And my refreshCoordinates() method is as below:
public void refreshCoordinates() {
do
{
getLatitude(handleeGPS.latitude);
getLongitude(handleeGPS.longitude);
} while ((longi == "0.0" || lati == "0.0") || (longi.length() == 0 || lati.length()==0));
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
lblLatitude.setText(lati);
lblLongitude.setText(longi);
busyDialog.cancel();
}
} );
}
public static String getLatitude(double value)
{
lati= Double.toString(value);
return lati;
}
public static String getLongitude(double value)
{
longi= Double.toString(value);
return longi;
}
Class that returns the latitude and longitude values:
public class handleeGPS{
static GPSThread gpsThread;
public static double latitude;
public static double longitude;
public handleeGPS(){
gpsThread = new GPSThread();
gpsThread.start();
}
private static class GPSThread extends Thread{
public void run() {
Criteria myCriteria = new Criteria();
myCriteria.setCostAllowed(false);
int m_bbHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs");
if(m_bbHandle>0){
try {
int cellID = GPRSInfo.getCellInfo().getCellId();
int lac = GPRSInfo.getCellInfo().getLAC();
String urlString2 = "http://www.google.com/glm/mmap";
// Open a connection to Google Maps API
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(urlString2);
HttpConnection httpConn2;
httpConn2 = (HttpConnection)connDesc.getConnection();
httpConn2.setRequestMethod("POST");
// Write some custom data to Google Maps API
OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream();
WriteDataGoogleMaps(outputStream2, cellID, lac);
// Get the response
InputStream inputStream2 = httpConn2.openInputStream();//getInputStream();
DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
// Interpret the response obtained
dataInputStream2.readShort();
dataInputStream2.readByte();
int code = dataInputStream2.readInt();
//Dialog.alert(code+"");
if (code == 0) {
latitude= dataInputStream2.readInt() / 1000000D;
longitude=dataInputStream2.readInt() / 1000000D;
//Dialog.alert(latitude+"-----"+longitude);
dataInputStream2.readInt();
dataInputStream2.readInt();
dataInputStream2.readUTF();
} else {
System.out.println("Error obtaining Cell Id ");
}
outputStream2.close();
inputStream2.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
} else {
try {
LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
try {
Location myLocation = myLocationProvider.getLocation(300);
latitude = myLocation.getQualifiedCoordinates().getLatitude();
longitude = myLocation.getQualifiedCoordinates().getLongitude();
if(latitude==0.0 && longitude==0.0){
try {
int cellID = GPRSInfo.getCellInfo().getCellId();
int lac = GPRSInfo.getCellInfo().getLAC();
String urlString2 = "http://www.google.com/glm/mmap";
// Open a connection to Google Maps API
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(urlString2);
HttpConnection httpConn2;
httpConn2 = (HttpConnection)connDesc.getConnection();
httpConn2.setRequestMethod("POST");
// Write some custom data to Google Maps API
OutputStream outputStream2 = httpConn2.openOutputStream();
//getOutputStream();
WriteDataGoogleMaps(outputStream2, cellID, lac);
// Get the response
InputStream inputStream2 = httpConn2.openInputStream();
//getInputStream();
DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
// Interpret the response obtained
dataInputStream2.readShort();
dataInputStream2.readByte();
int code = dataInputStream2.readInt();
//Dialog.alert(code+"");
if (code == 0) {
latitude= dataInputStream2.readInt() / 1000000D;
longitude=dataInputStream2.readInt() / 1000000D;
//Dialog.alert(latitude+"-----"+longitude);
dataInputStream2.readInt();
dataInputStream2.readInt();
dataInputStream2.readUTF();
} else {
System.out.println("Error obtaining Cell Id ");
}
outputStream2.close();
inputStream2.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
catch ( InterruptedException iex ) {
return;
}
catch ( LocationException lex ) {
return;
}
} catch ( LocationException lex ) {
return;
}
}
return;
}
}
private static void WriteDataGoogleMaps(OutputStream out, int cellID, int lac)
throws IOException {
DataOutputStream dataOutputStream = new DataOutputStream(out);
dataOutputStream.writeShort(21);
dataOutputStream.writeLong(0);
dataOutputStream.writeUTF("en");
dataOutputStream.writeUTF("Android");
dataOutputStream.writeUTF("1.0");
dataOutputStream.writeUTF("Web");
dataOutputStream.writeByte(27);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(3);
dataOutputStream.writeUTF("");
dataOutputStream.writeInt(cellID);
dataOutputStream.writeInt(lac);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.flush();
}
}
Ok, so although my original answer was valid, the new code you posted has some different problems, so I'm posting a second answer. There were enough things that didn't look right, that I just rewrote your handleeGPS class. I'll explain the major changes I made, one-by-one:
Try to use Java naming conventions. This makes it easier for us to help you. Before you posted the code to your handleeGPS class, I thought it was a variable, because lowercase names are usually used for variables, not classes.
Avoid duplicating code. The handleeGPS class had a lot of code to read through, but most of it was the code to get location from Google's web service, which you duplicated in two places. Just make a method that contains only that code, and call it twice.
I renamed your handleeGPS class to GPSHandler. I'm not sure if handlee was an error, or if that's a word in another language that you used. Anyway, the name should at least start with an uppercase letter.
Avoid lots of static variables and methods. Sometimes, there really should be only one of something. A GPS handling class is probably a good example of that, because the device only has one GPS system. But, to enforce this code construct, don't mark everything as static. Just make the class a Singleton, which involves creating only one static member variable (_instance) and one static method (getInstance()). In my code, you will access the class like this: GPSHandler gps = GPSHandler.getInstance();.
I believe the check you had for whether BB maps was installed was actually backwards. You looked up the net_rim_bb_lbs module, and if it was greater than zero (which means BB Maps is installed) then you went directly to the Google webservice. I think you want it the other way around (try device GPS if BB Maps installed). Also, since 6.0, you need to check for net_rim_bb_maps, too.
Before you posted the update, I thought your getLatitude() and getLongitude() methods were actually fetching the device location. That was a bad assumption on my part. They were just converting numbers to strings. So, there's no reason for that to be done in the background (with a Thread). You already wrote your handleeGPS class to use a background thread, which is good. One background thread is enough. The UI that uses the location information should not also need a background Thread. I changed the code to add a GPSListener interface. That interface should be implemented by your UI code, to receive location updates. There is no reason to keep looping, asking if the location is not equal to {0.0, 0.0}. That's inefficient. With my code, you will just get notified when the location does change.
The original code was not thread safe. The handleeGPS latitude and longitude variables were set on the background thread, and accessed on the UI thread. That's not safe. Two threads should not be reading and writing the same piece of data at once. By changing the code to push location data to the GPSListener, it avoids this problem.
I uncommented the Dialog.alert() code you had inside your handleeGPS class, which would not have worked for you, because you're not allowed to make UI calls from the background. I surrounded those calls with UiApplication.getUiApplication().invokeLater() to make them safe.
To use this class, in your UI code somewhere, you would do this, instead of using a Thread to run your refreshCoordinates() method:
public void fieldChanged(Field field, int context)
// this is called when your location refresh button is clicked
GPSHandler.getInstance().setListener(this);
GPSHandler.getInstance().requestLocationUpdates();
busyDialog.setEscapeEnabled(false);
busyDialog.show();
}
...
public void onLocationReceived(Coordinates location) {
lblLatitude.setText(Double.toString(location.getLatitude()));
lblLongitude.setText(Double.toString(location.getLongitude()));
busyDialog.cancel();
}
Make sure the class where you put that code (above) also implements GPSListener, which is an interface, defined here:
public interface GPSListener {
public void onLocationReceived(Coordinates location);
}
and finally, the GPSHandler:
public class GPSHandler {
private GPSThread _gpsThread;
private Coordinates _location;
private boolean _gotLocation;
private GPSListener _listener;
/** this class will be a Singleton, as the device only has one GPS system */
private static GPSHandler _instance;
/** #return the Singleton instance of the GPSHandler */
public static GPSHandler getInstance() {
if (_instance == null) {
_instance = new GPSHandler();
}
return _instance;
}
/** not publicly accessible ... use getInstance() */
private GPSHandler() {
}
/** call this to trigger a new location fix */
public void requestLocationUpdates() {
if (_gpsThread == null || !_gpsThread.isAlive()) {
_gpsThread = new GPSThread();
_gpsThread.start();
}
}
public void setListener(GPSListener listener) {
// only supports one listener this way
_listener = listener;
}
private void setLocation(final Coordinates value) {
_location = value;
if (value.getLatitude() != 0.0 || value.getLongitude() != 0.0) {
_gotLocation = true;
if (_listener != null) {
// this assumes listeners are UI listeners, and want callbacks on the UI thread:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_listener.onLocationReceived(value);
}
});
}
}
}
private class GPSThread extends Thread {
private void getLocationFromGoogle() {
try {
int cellID = GPRSInfo.getCellInfo().getCellId();
int lac = GPRSInfo.getCellInfo().getLAC();
String urlString2 = "http://www.google.com/glm/mmap";
// Open a connection to Google Maps API
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(urlString2);
HttpConnection httpConn2;
httpConn2 = (HttpConnection)connDesc.getConnection();
httpConn2.setRequestMethod("POST");
// Write some custom data to Google Maps API
OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream();
writeDataGoogleMaps(outputStream2, cellID, lac);
// Get the response
InputStream inputStream2 = httpConn2.openInputStream();//getInputStream();
DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
// Interpret the response obtained
dataInputStream2.readShort();
dataInputStream2.readByte();
final int code = dataInputStream2.readInt();
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(code + "");
}
});
if (code == 0) {
final double latitude = dataInputStream2.readInt() / 1000000D;
final double longitude = dataInputStream2.readInt() / 1000000D;
setLocation(new Coordinates(latitude, longitude, 0.0f));
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(latitude+"-----"+longitude);
}
});
dataInputStream2.readInt();
dataInputStream2.readInt();
dataInputStream2.readUTF();
} else {
System.out.println("Error obtaining Cell Id ");
}
outputStream2.close();
inputStream2.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
private void tryGetLocationFromDevice() {
_gotLocation = false;
try {
Criteria myCriteria = new Criteria();
myCriteria.setCostAllowed(false);
LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
try {
Location myLocation = myLocationProvider.getLocation(300);
setLocation(myLocation.getQualifiedCoordinates());
} catch ( InterruptedException iex ) {
System.out.println(iex.getMessage());
} catch ( LocationException lex ) {
System.out.println(lex.getMessage());
}
} catch ( LocationException lex ) {
System.out.println(lex.getMessage());
}
if (!_gotLocation) {
getLocationFromGoogle();
}
}
public void run() {
int bbMapsHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs"); // OS < 6.0
int bbMapsHandle60 = CodeModuleManager.getModuleHandle("net_rim_bb_maps"); // OS 6.0+
if (bbMapsHandle > 0 || bbMapsHandle60 > 0) {
tryGetLocationFromDevice();
} else {
getLocationFromGoogle();
}
}
}
private void writeDataGoogleMaps(OutputStream out, int cellID, int lac) throws IOException {
DataOutputStream dataOutputStream = new DataOutputStream(out);
dataOutputStream.writeShort(21);
dataOutputStream.writeLong(0);
dataOutputStream.writeUTF("en");
dataOutputStream.writeUTF("Android");
dataOutputStream.writeUTF("1.0");
dataOutputStream.writeUTF("Web");
dataOutputStream.writeByte(27);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(3);
dataOutputStream.writeUTF("");
dataOutputStream.writeInt(cellID);
dataOutputStream.writeInt(lac);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.flush();
}
}
There's a lot of code that we can't see (e.g. getLatitude(), getLongitude(), refreshDetails()). So, there could be something going wrong there. Also, I don't see any Loading Screen in the code you posted, so I can't say why that isn't showing.
But, here's something that doesn't look right:
synchronized (Application.getEventLock())
{
busyDialog.show();
}
If you read this BlackBerry forum question, you'll see that trying to synchronize on the application event lock from the main (UI) thread can cause your app to freeze. The public void fieldChanged(Field field, int context) method is always called on the UI thread, because it's the UI thread that monitors buttons for clicks, and calls back your click handlers, like fieldChanged().
You can also read the BlackBerry API docs for Application, that explain that getEventLock() is for worker (also known as background) threads, not the main (aka UI) thread.
So, there's no need to use special techniques to get the event lock, in code that already runs on the UI thread. Instead of the code above, just do this:
busyDialog.show();
Both of these techniques:
synchronized (Application.getEventLock())
{
busyDialog.show();
}
or
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
busyDialog.show();
}
});
are ways to safely call UI methods from a background thread. But, you shouldn't use those in code that you know is running on the UI thread already.
Try fixing that, and see if your problem disappears.
Edit: also, your code is checking for a username and password before refreshing the location. Is that really what you want? I don't think this has anything to do with your problem, but normally, I wouldn't expect to need a username or password to access location services. Of course, I don't know your application, so this is really just a comment on my part.
I think thee is simple answer is error here:
((longi == "0.0" || lati == "0.0") || (longi.length() == 0 || lati.length()==0));
You have to use String.equals() instead of == operator.
After first call longi and lati have "0.0" value. But == will return false because it compare references by default and they are different because it's different objects.

Blackberry GPS Test Demo

Can you please help me to create Blackberry GPS Sample Demo? Actually I am messed with so many devices of Blackberry and some has GPS receiver and others don't have.
If the device has GPS receiver how it will search for the current device location? and what if the device does not have GPS like BB 8520 ?
Please share your understandings about GPS in Blackberry and how can I achieve Latitude and Longitude of Device Location whether by GPS or not.
Thank you
try this , this will check the gps. If gps is available, then it will get the location, else, it will find the location from the network.
call this class on your class - handleGPS gps=new handleGPS();
public class handleGPS{
static GPSThread gpsThread;
public static double latitude=0;
public static double longitude=0;
public handleGPS(){
gpsThread = new GPSThread();
gpsThread.start();
}
private static class GPSThread extends Thread{
public void run() {
Criteria myCriteria = new Criteria();
myCriteria.setCostAllowed(false);
int m_bbHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs");
if(m_bbHandle>0){
try {
int cellID = GPRSInfo.getCellInfo().getCellId();
int lac = GPRSInfo.getCellInfo().getLAC();
String urlString2 = "http://www.google.com/glm/mmap";
// Open a connection to Google Maps API
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(urlString2);
HttpConnection httpConn2;
httpConn2 = (HttpConnection)connDesc.getConnection();
httpConn2.setRequestMethod("POST");
// Write some custom data to Google Maps API
OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream();
WriteDataGoogleMaps(outputStream2, cellID, lac);
// Get the response
InputStream inputStream2 = httpConn2.openInputStream();//getInputStream();
DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
// Interpret the response obtained
dataInputStream2.readShort();
dataInputStream2.readByte();
int code = dataInputStream2.readInt();
//Dialog.alert(code+"");
if (code == 0) {
latitude= dataInputStream2.readInt() / 1000000D;
longitude=dataInputStream2.readInt() / 1000000D;
//Dialog.alert(latitude+"-----"+longitude);
dataInputStream2.readInt();
dataInputStream2.readInt();
dataInputStream2.readUTF();
} else {
System.out.println("Error obtaining Cell Id ");
}
outputStream2.close();
inputStream2.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
else{
try {
LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
try {
Location myLocation = myLocationProvider.getLocation(300);
latitude = myLocation.getQualifiedCoordinates().getLatitude();
longitude = myLocation.getQualifiedCoordinates().getLongitude();
if(latitude==0 && longitude==0){
try {
int cellID = GPRSInfo.getCellInfo().getCellId();
int lac = GPRSInfo.getCellInfo().getLAC();
String urlString2 = "http://www.google.com/glm/mmap";
// Open a connection to Google Maps API
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(urlString2);
HttpConnection httpConn2;
httpConn2 = (HttpConnection)connDesc.getConnection();
httpConn2.setRequestMethod("POST");
// Write some custom data to Google Maps API
OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream();
WriteDataGoogleMaps(outputStream2, cellID, lac);
// Get the response
InputStream inputStream2 = httpConn2.openInputStream();//getInputStream();
DataInputStream dataInputStream2 = new DataInputStream(inputStream2);
// Interpret the response obtained
dataInputStream2.readShort();
dataInputStream2.readByte();
int code = dataInputStream2.readInt();
//Dialog.alert(code+"");
if (code == 0) {
latitude= dataInputStream2.readInt() / 1000000D;
longitude=dataInputStream2.readInt() / 1000000D;
//Dialog.alert(latitude+"-----"+longitude);
dataInputStream2.readInt();
dataInputStream2.readInt();
dataInputStream2.readUTF();
} else {
System.out.println("Error obtaining Cell Id ");
}
outputStream2.close();
inputStream2.close();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
catch ( InterruptedException iex ) {
return;
}
catch ( LocationException lex ) {
return;
}
}catch ( LocationException lex ) {
return;
}
}
return;
}
}
private static void WriteDataGoogleMaps(OutputStream out, int cellID, int lac)
throws IOException {
DataOutputStream dataOutputStream = new DataOutputStream(out);
dataOutputStream.writeShort(21);
dataOutputStream.writeLong(0);
dataOutputStream.writeUTF("en");
dataOutputStream.writeUTF("Android");
dataOutputStream.writeUTF("1.0");
dataOutputStream.writeUTF("Web");
dataOutputStream.writeByte(27);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(3);
dataOutputStream.writeUTF("");
dataOutputStream.writeInt(cellID);
dataOutputStream.writeInt(lac);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.writeInt(0);
dataOutputStream.flush();
}
}
This previous SO post should point you in the right direction.
Regarding other methods, you can use Triangulation, in which you can use the signal strength from at least 3 cell towers to obtain a rough estimate of your location. Depending on how accurate you need the location, Triangulation will most likely be faster than GPS, but GPS will be significantly much more accurate (triangulation tends to have a best case margin of error of about 100m).
Note however, that if you are inside a building or do not have a clear view of the sky, the GPS will most likely not work.

Blackberry Location Service fails on real device?

I've been trying to get longitude and latitude values using Blackberry's GPS listener. My device is a blackberry torch. The simulator I use also is a blackberry torch. The GPS listener seems to be working on the sim, but once on a real device it fails. When I say fail, it does not pick up longitude and latitude values, rather, it struggles to even connect to the GPS. I checked my options menu, and I'm able to pick up long and lat values from the location settings, so why would my app not be able to do it?
I call the class handleGPS in another class, i.e by doing this:
new handleGPS();
As I said, using the SIM I the provider finds my location after about 10 seconds. On the real device, I debug it and it does reach this statement (as the System.out's are printed)
try {
lp = LocationProvider.getInstance(cr);
System.out.println("location Provider");
lp.setLocationListener(new handleGPSListener(), 10, -1, -1);
//lp.setLocationListener(listener, interval, timeout, maxAge)
System.out.println("location Provider after listener");
} catch (LocationException e) {
e.printStackTrace();
}
However no values get returned. Below is my code.
GPS class:
public class handleGPS extends TimerTask {
//Thread t = new Thread(new Runnable() {
private Timer timer;
LocationProvider lp = null;
public handleGPS()
{
timer =new Timer();
System.out.println("timer");
GPS();
//timer.schedule(this, 0, 10000);
timer.schedule(this, 1000);
}
public void GPS() {
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
cr.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
cr.setCostAllowed(false);
cr.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT);
//cr.setPreferredResponseTime(1000);
System.out.println("GPS ()");
try {
lp = LocationProvider.getInstance(cr);
System.out.println("location Provider");
lp.setLocationListener(new handleGPSListener(), 10, -1, -1);
//lp.setLocationListener(listener, interval, timeout, maxAge)
System.out.println("location Provider after listener");
} catch (LocationException e) {
e.printStackTrace();
}
}
// });
public void run() {
// TODO Auto-generated method stub
lp.setLocationListener(new handleGPSListener(), 10, -1, -1);
}
}
And here is the handler:
public class handleGPSListener implements LocationListener {
Coordinates c = null;
private static double lat=0.00;
private static double lon=0.00;
Database sqliteDB;
String username;
public static final String NAMESPACE = "http://tempuri.org/";
public String URL = "http://77.245.77.195:60010/Webservice/IDLMobile.asmx?WSDL";
public static final String SOAP_ACTION = "http://tempuri.org/Get_OfferCount_By_Location";
public static final String METHOD_NAME = "Get_OfferCount_By_Location";
private double x,y;
public void locationUpdated(LocationProvider loc, Location location) { //method to update as the location changes.
System.out.println("class handle GPS Listener");
if (loc == null) { //condition to check if the location information is null.
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("GPS not supported!"); //dialog box to alert gps is not started.
System.out.println("Problem 1");
return;
}
});
} else { //if not checked.
System.out.println("OK");
switch (loc.getState()) { //condition to check state of the location.
case (LocationProvider.AVAILABLE): //condition to check if the location is available.
System.out.println("Provider is AVAILABLE");
try {
location = loc.getLocation(-1); //location to get according to user present.
} catch (LocationException e) {
return;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (location != null && location.isValid()) { //condition to check if the location is not null and is valid.
c = location.getQualifiedCoordinates(); //to get the coordinates of the location.
}
if (c != null) { //condition to check if the location is not null.
lat = c.getLatitude(); //retrieve the latitude values into variable.
lon = c.getLongitude(); //retrieve the longitude values into variable.
System.out.println("lat and lon"+lat+lon);
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
updateFields();
getValues();
// Dialog.alert(lat+"GPS supported!"+lon);
return;
}
private void getValues() {
// TODO Auto-generated method stub
try {
URI uri = URI
.create("file:///SDCard/"
+ "database3.db"); //database3 to retrieve the values from location table.
sqliteDB = DatabaseFactory.open(uri);
Statement st = null;
st = sqliteDB
.createStatement("SELECT Latitude,Longitude FROM Location");//statement to retrieve the lat and lon values.
st.prepare();
Cursor c = st.getCursor();//cursor to point.
Row r;
int i = 0;
while (c.next()) { //loop to execute until there are no values in the cursor.
r = c.getRow(); //store the values in row.
i++;
lat=Double.parseDouble(r.getString(0)); //retrieve the latitude values from the database and store in variable.
lon=Double.parseDouble(r.getString(1)); //retrieve the longitude values from the database and store in variable.
System.out.println(r.getString(0)
+ " Latitude");
System.out.println(r.getString(1)
+ " Longitude");
}
st.close();
sqliteDB.close();
}
catch (Exception e) {
System.out.println(e.getMessage()
+ " wut");
e.printStackTrace();
}
try {
URI uri = URI
.create("file:///SDCard/"
+ "database1.db");
sqliteDB = DatabaseFactory.open(uri);
Statement st = null;
st = sqliteDB
.createStatement("SELECT Name FROM People");
st.prepare();
Cursor c = st.getCursor();
Row r;
int i = 0;
while (c.next()) {
r = c.getRow();
i++;
username=r.getString(0);
System.out.println(r.getString(0)
+ "Name");
}
st.close();
sqliteDB.close();
}
catch(Exception e)
{
e.printStackTrace();
}
SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);
rpc.addProperty("Username", username);
rpc.addProperty("latitude", String.valueOf(lat));
rpc.addProperty("longitude", String.valueOf(lon));
rpc.addProperty("distance", "1.5");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.bodyOut = rpc;
envelope.dotNet = true;
envelope.encodingStyle = SoapSerializationEnvelope.XSD;
HttpTransport ht = new HttpTransport(URL);
ht.debug = true;
try {
ht.call(SOAP_ACTION, envelope);
System.out.println("IN TRY");
SoapObject resultProperties = (SoapObject) envelope
.getResponse();
System.out.println("username INT RIGHT HERE " + resultProperties.getProperty(0));
System.out.println("username INT RIGHT HERE " + resultProperties.getProperty(1).toString());
System.out.println("username INT RIGHT HERE " + resultProperties.getProperty(2).toString());
System.out.println("lat and lon PARSE HERE " + lat+"\n"+lon);
/* here is the notification code */
//ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry.getInstance();
//EncodedImage image = EncodedImage.getEncodedImageResource("logosmall.png");
//ApplicationIcon icon = new ApplicationIcon( image );
//ApplicationIndicator indicator = reg.register( icon, false, true);
//indicator.setIcon(icon);
//indicator.setVisible(true);
//setupIndicator();
//setVisible(true, 0);
//NotificationsManager.triggerImmediateEvent(1, 0, 20, null);
//NotificationsManager.
/* end notification code */
} catch (org.xmlpull.v1.XmlPullParserException ex2) {
} catch (Exception ex) {
String bah = ex.toString();
}
}
private void updateFields() {
// TODO Auto-generated method stub
try {
URI myURI = URI
.create("file:///SDCard/"
+ "database3.db");
sqliteDB = DatabaseFactory.open(myURI);
Statement st = null;
Statement oops = null;
st = sqliteDB
.createStatement("SELECT Latitude,Longitude FROM Location");
st.prepare();
Cursor c = st.getCursor();
Row r;
int i = 0;
while (c.next()) {
r = c.getRow();
i++;
x=Double.parseDouble(r.getString(0));
y=Double.parseDouble(r.getString(1));
System.out.println(r.getString(0)
+ " Latitude in update fields");
System.out.println(r.getString(1)
+ " Longitude in update fields");
}
st = sqliteDB
.createStatement("UPDATE Location SET Latitude='"
+ lat
+ "' "
+ "WHERE Latitude="
+ "'" + x + "'" + "");
oops = sqliteDB
.createStatement("UPDATE Location SET Longitude='"
+ lon
+ "' "
+ "WHERE Longitude="
+ "'" + y + "'" + "");
System.out.println("location updated");
System.out
.println("lat and lon values are"
+ lat + lon);
st.prepare();
oops.prepare();
st.execute();
oops.execute();
st.close();
oops.close();
sqliteDB.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
});
}
}
}
}
public void providerStateChanged(LocationProvider provider, int newState) {
if (newState == LocationProvider.OUT_OF_SERVICE) {
// GPS unavailable due to IT policy specification
System.out.println("GPS unavailable due to IT policy specification");
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("GPS unavailable due to IT policy specification");
return;
}
});
} else if (newState == LocationProvider.TEMPORARILY_UNAVAILABLE) {
// no GPS fix
System.out.println("GPS temporarily unavailable due to IT policy specification");
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("no GPS fix");
return;
}
});
}
}
public ApplicationIndicator _indicator;
public static handleGPSListener _instance;
public void setupIndicator() {
//Setup notification
if (_indicator == null) {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry.getInstance();
_indicator = reg.getApplicationIndicator();
if(_indicator == null) {
ApplicationIcon icon = new ApplicationIcon(EncodedImage.getEncodedImageResource ("daslogo.png"));
_indicator = reg.register(icon, false, true);
_indicator.setValue(0);
_indicator.setVisible(false);
}
}
}
public void setVisible(boolean visible, int count) {
if (_indicator != null) {
if (visible) {
_indicator.setVisible(true);
_indicator.setValue(count);
} else {
_indicator.setVisible(false);
}
}
}
handleGPSListener () {
}
public static handleGPSListener getInstance() {
if (_instance == null) {
_instance = new handleGPSListener ();
}
return(_instance);
}
public double returnLong(){
return lon;
}
public double returnLat(){
return lat;
}
}
Your handler's locationUpdated method is never being called, right? If you call getLocation directly does it work?
I was unable to get the listener to work correctly and eventually moved to using a timer instead from which I call getLocation...
I suspect that the listener only listens to events and does not create them, i.e. if something asked for the location, the listener will receive it as well, but if nothing asked for the location you get nothing.
In GPS it is wise to never trust the simulator, it lies. :)

How to get current location in blackberry device?

In simulator my gps code work fine. But when I install my app in device I can't get current latitude and longitude.
When I send lat long from simulator it get proper lat long which is send through simulator. I don't know why is not working in device?
I have already enable from Option > Advance option > gps > gps servce and set Location ON.
Is there any other setting for get current location in device?
private boolean currentLocation() {
boolean retval = true;
try {
LocationProvider lp = LocationProvider.getInstance(null);
if (lp != null) {
lp.setLocationListener(new LocationListenerImpl(), interval, 1, 1);
} else {
// GPS is not supported, that sucks!
// Here you may want to use UiApplication.getUiApplication() and post a Dialog box saying that it does not work
retval = false;
}
} catch (LocationException e) {
System.out.println("Error: " + e.toString());
}
return retval;
}
private class LocationListenerImpl implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location.isValid()) {
heading = location.getCourse();
longitude = location.getQualifiedCoordinates().getLongitude();
latitude = location.getQualifiedCoordinates().getLatitude();
altitude = location.getQualifiedCoordinates().getAltitude();
speed = location.getSpeed();
// This is to get the Number of Satellites
String NMEA_MIME = "application/X-jsr179-location-nmea";
satCountStr = location.getExtraInfo("satellites");
if (satCountStr == null) {
satCountStr = location.getExtraInfo(NMEA_MIME);
}
// this is to get the accuracy of the GPS Cords
QualifiedCoordinates qc = location.getQualifiedCoordinates();
accuracy = qc.getHorizontalAccuracy();
}
}
Try this code
Thread thread = new Thread(new Runnable() {
public void run() {
bCriteria = new BlackBerryCriteria();
if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_CELLSITE)) {
bCriteria.setMode(GPSInfo.GPS_MODE_CELLSITE);
} else if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST)) {
bCriteria.setMode(GPSInfo.GPS_MODE_ASSIST);
} else if (GPSInfo
.isGPSModeAvailable(GPSInfo.GPS_MODE_AUTONOMOUS)) {
bCriteria.setMode(GPSInfo.GPS_MODE_AUTONOMOUS);
} else {
bCriteria.setCostAllowed(true);
bCriteria
.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
}
try {
bProvider = (BlackBerryLocationProvider) BlackBerryLocationProvider
.getInstance(bCriteria);
if (bProvider != null) {
bProvider.setLocationListener(new handleGPSListener(),
-1, -1, -1);
try {
bLocation = (BlackBerryLocation) bProvider
.getLocation(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (LocationException lex) {
lex.printStackTrace();
return;
}
}
});
thread.start();
then implement Location Listener in the class
public class handleGPSListener implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location.isValid()) {
}
}
public void providerStateChanged(LocationProvider provider, int newState) {
}
}

Blackberry not able to fetch Latitude and longitude

I need to get the users latitude and longitude to display data in increasing order of distance.
I am using 2 phones in 2 different countries to test the app. It works fine with a bb bold 9700 when used in south asia. But does not with a bb 9650 when used in nyc.
I tried using the bb gps api based classes and also google tower based gps classes.
Both don't seem to work in nyc with bb 9650.I used other location based apps like yelp etc which work perfectly.
Attaching both the codes
Phone GPS
public class GPS_Location
{
private String log;
double longi;
double lati;
public GPS_Location()
{
new LocationTracker();
}
public boolean onClose()
{
Application.getApplication().requestBackground();
return false;
}
class LocationTracker extends TimerTask
{
private Timer timer;
private LocationProvider provider;
Criteria cr;
public LocationTracker()
{
timer = new Timer();
cr= new Criteria();
resetGPS();
timer.schedule(this, 0, 60000);
}
public void resetGPS()
{
try
{
provider = LocationProvider.getInstance(cr);
if(provider != null)
{
/*provider.setLocationListener(null, 0, 0, 0);
provider.reset();
provider = null;*/
provider.setLocationListener(new MyLocationListener(), 3, -1, -1);
}
//provider = LocationProvider.getInstance(null);
} catch(Exception e)
{
}
}
public void run()
{
System.out.println("********************");
}
private class MyLocationListener implements LocationListener
{
public void locationUpdated(LocationProvider provider, Location location)
{
if(location != null && location.isValid())
{
QualifiedCoordinates qc = location.getQualifiedCoordinates();
try
{
lati = location.getQualifiedCoordinates().getLatitude();
System.out.println("********************latitude :: "+lati);
longi = location.getQualifiedCoordinates().getLongitude();
System.out.println("********************longitude ::"+longi);
CustomSession.getInstance().setLatitude(lati);
CustomSession.getInstance().setLongitude(longi);
}
catch(Exception e)
{
}
}
}
public void providerStateChanged(LocationProvider provider, int newState)
{
//LocationTracker.this.resetGPS();
if(newState == LocationProvider.TEMPORARILY_UNAVAILABLE)
{
provider.reset();
provider.setLocationListener(null, 0, 0, -1);
}
}
}
}
}
cell tower google service
public class JsonGenerator {
public void locating() throws IOException{
byte[] postData = getGPSJsonObject().toString().getBytes();
JSONObject jsonObject = null;
HttpConnection gpsConnection;
DataOutputStream os;
DataInputStream dis;
String gpsString = retrunURLString("http://www.google.com/loc/json");
try {
gpsConnection = (HttpConnection) Connector.open(gpsString);
gpsConnection.setRequestMethod(HttpConnection.POST);
gpsConnection.setRequestProperty(
HttpProtocolConstants.HEADER_CONTENT_LENGTH, String
.valueOf(postData.length));
gpsConnection.setRequestProperty(
HttpProtocolConstants.HEADER_CONTENT_TYPE,
"application / requestJson");
os = gpsConnection.openDataOutputStream();
os.write(postData);
int rc = gpsConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
return;
}
dis = gpsConnection.openDataInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while ((j = dis.read()) != -1) {
baos.write(j);
}
byte[] data = baos.toByteArray();
String jsonString = new String(data);
try {
jsonObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject locationObject = jsonObject.getJSONObject("location");
if (locationObject.getDouble("latitude") != 0.0
&& locationObject.getDouble("longitude") != 0.0) {
System.out.println("Latitute is =================::::"+locationObject.getDouble("latitude"));
System.out.println("Llongitude is =================::::"+locationObject.getDouble("longitude"));
CustomSession.getInstance().setLatitude(locationObject.getDouble("latitude"));
CustomSession.getInstance().setLongitude(locationObject.getDouble("longitude"));
// Global.horizontal_accuracy = locationObject
// .getDouble("accuracy");
// Global.locAvailable = true;
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
}
public JSONObject getGPSJsonObject() {
JSONObject jsonString = new JSONObject();
try {
jsonString.put("version", "1.1.0");
jsonString.put("host", "maps.google.com");
int x = RadioInfo.getMCC(RadioInfo.getCurrentNetworkIndex());
jsonString.put("home_mobile_country_code", Integer.parseInt(Integer
.toHexString(x)));
jsonString.put("home_mobile_network_code", RadioInfo
.getMNC(RadioInfo.getCurrentNetworkIndex()));
int radio = RadioInfo.getNetworkType();
if(radio==RadioInfo.NETWORK_CDMA){
jsonString.put("radio_type", "cdma");
}
else{
jsonString.put("radio_type", "gsm");
}
jsonString.put("carrier", RadioInfo.getCurrentNetworkName());
jsonString.put("request_address", true);
jsonString.put("address_language", "en_GB");
CellTower cellInfo = new CellTower(Integer.toHexString(x), GPRSInfo
.getCellInfo().getLAC(), GPRSInfo.getCellInfo().getRSSI(),
GPRSInfo.getCellInfo().getCellId(), 0, RadioInfo
.getMNC(RadioInfo.getCurrentNetworkIndex()));
Hashtable map = new Hashtable();
map.put("mobile_country_code", new Integer(Integer
.parseInt(cellInfo.mobileCountryCode)));
map.put("location_area_code",
new Integer(cellInfo.locationAreaCode));
map.put("signal_strength", new Integer(cellInfo.signalStrength));
map.put("cell_id", new Integer(cellInfo.cellID));
map.put("age", new Integer(0));
map.put("mobile_network_code", new Integer(
cellInfo.mobileNetworkCode));
JSONArray array = new JSONArray();
array.put(0, map);
jsonString.put("cell_towers", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonString;
}
public static String retrunURLString(String url) {
String urlString = null;
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
// WIFI
urlString = url + ";interface=wifi";
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
ServiceRecord record = getWAP2ServiceRecord();
if (record != null
&& (coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// WAP 2.0
urlString = url + ";deviceside=true;ConnectionUID="
+ record.getUid();
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// BES/MDS
urlString = url + ";deviceside=false";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// Direct TCP/IP
urlString = url + ";deviceside=true";
} else if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
// BIS
urlString = url + ";deviceside=false;ConnectionUID="
+ record.getUid();
}
}
return urlString;
}
protected static ServiceRecord getWAP2ServiceRecord() {
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
for (int i = 0; i < records.length; i++) {
String cid = records[i].getCid().toLowerCase();
String uid = records[i].getUid().toLowerCase();
if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1
&& uid.indexOf("mms") == -1) {
return records[i];
}
}
return null;
}
private class CellTower {
public String mobileCountryCode;
public int locationAreaCode;
public int signalStrength;
public int cellID;
public int age;
public int mobileNetworkCode;
private CellTower(String mcc, int lac, int ss, int ci, int a, int mnc) {
mobileCountryCode = mcc;
locationAreaCode = lac;
signalStrength = ss;
cellID = ci;
age = a;
mobileNetworkCode = mnc;
}
}
}
Ideally you should be using multiple fix methods (your Criteria) to gather GPS information. Using just the default will not work in all circumstances, so you need to have fallback options. Here are the Criteria, in preferred order, that I use in the States and seems to do well. You just have to loop through them until you have a set that works.
//Speed optimal
BlackBerryCriteria speed = new BlackBerryCriteria();
speed.setHorizontalAccuracy(50);
speed.setPreferredPowerConsumption(Criteria.POWER_USAGE_HIGH);
speed.setCostAllowed(true);
speed.setPreferredResponseTime(10000);
//MS-Based
BlackBerryCriteria msBased = new BlackBerryCriteria();
msBased.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_MEDIUM);
msBased.setHorizontalAccuracy(50);
msBased.setVerticalAccuracy(50);
msBased.setCostAllowed(true);
msBased.setPreferredResponseTime(10000);
//Assisted mode
BlackBerryCriteria assisted = new BlackBerryCriteria();
assisted.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_HIGH);
assisted.setHorizontalAccuracy(50);
assisted.setVerticalAccuracy(50);
assisted.setCostAllowed(true);
assisted.setPreferredResponseTime(10000);
//Autonomous
BlackBerryCriteria autonomous = new BlackBerryCriteria();
autonomous.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_MEDIUM);
autonomous.setHorizontalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
autonomous.setVerticalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
autonomous.setCostAllowed(true);
autonomous.setPreferredResponseTime(180000);
//Cell site
BlackBerryCriteria cell = new BlackBerryCriteria();
cell.setPreferredPowerConsumption(BlackBerryCriteria.POWER_USAGE_LOW);
cell.setHorizontalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
cell.setVerticalAccuracy(BlackBerryCriteria.NO_REQUIREMENT);
cell.setCostAllowed(true);
cell.setPreferredResponseTime(180000);

Resources