I want to get the value of current location. I use this code but I just obtain this message "Waiting for location update...". There is a configuraition should I make it in the phone to get the adress of current location???
The GPS status is available of my mobile. But I think the location is not valid because I didn't get the alert dialog. What should do to get the latitude and longitude of current location ??
package mypackage;
import net.rim.device.api.gps.*;
import net.rim.device.api.system.Application;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import javax.microedition.location.*;
public class MultipleFixDemo extends UiApplication
{
private static int _interval = 1;
private EditField _status;
public static void main(String[] args)
{
new MultipleFixDemo().enterEventDispatcher();
}
public MultipleFixDemo()
{
MultipleFixScreen screen = new MultipleFixScreen();
screen.setTitle("Multiple Fix Demo");
_status = new EditField(Field.NON_FOCUSABLE);
screen.add(_status);
startLocationUpdate();
pushScreen(screen);
}
private void updateLocationScreen(final String msg)
{
invokeLater(new Runnable()
{
public void run()
{
_status.setText(msg);
}
});
}
private void startLocationUpdate()
{
try
{
BlackBerryCriteria myCriteria = new BlackBerryCriteria();
myCriteria.enableGeolocationWithGPS();
try
{
BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider)LocationProvider.getInstance(myCriteria);
if ( myProvider == null )
{
Runnable showUnsupportedDialog = new Runnable()
{
public void run() {
Dialog.alert("Location service unsupported, exiting...");
System.exit( 1 );
}
};
invokeLater( showUnsupportedDialog );
}
else
{
myProvider.setLocationListener(new LocationListenerImpl(), _interval, 1, 1);
}
}
catch (LocationException le)
{
System.err.println("Failed to retrieve a location provider");
System.err.println(le);
System.exit(0);
}
}
catch (UnsupportedOperationException ue)
{
System.err.println("Require mode is unavailable");
System.err.println(ue);
System.exit(0);
}
return;
}
private class LocationListenerImpl implements LocationListener
{
public void locationUpdated(LocationProvider provider, Location location)
{
if(location.isValid())
{
Dialog.alert("if");
double longitude = location.getQualifiedCoordinates().getLongitude();
double latitude = location.getQualifiedCoordinates().getLatitude();
float altitude = location.getQualifiedCoordinates().getAltitude();
StringBuffer sb = new StringBuffer();
sb.append("Longitude: ");
sb.append(longitude);
sb.append("\n");
sb.append("Latitude: ");
sb.append(latitude);
sb.append("\n");
sb.append("Altitude: ");
sb.append(altitude);
sb.append(" m");
MultipleFixDemo.this.updateLocationScreen(sb.toString());
}
}
public void providerStateChanged(LocationProvider provider, int newState)
{
// Not implemented
}
}
private final static class MultipleFixScreen extends MainScreen
{
MultipleFixScreen()
{
super(DEFAULT_CLOSE | DEFAULT_MENU);
RichTextField instructions = new RichTextField("Waiting for location update...",Field.NON_FOCUSABLE);
this.add(instructions);
}
}
}
Try this code it will work for me. it will give lat and long every 1 sec with update.
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;
public final class MyScreen extends MainScreen
{
private LocationProvider locationProvider;
private static int interval = 1;
double lat;
double longt;
public MyScreen()
{
setTitle("MyTitle");
startLocationUpdate();
}
private boolean startLocationUpdate()
{
boolean retval = false;
try
{
locationProvider = LocationProvider.getInstance(null);
if ( locationProvider == null )
{
Runnable showGpsUnsupportedDialog = new Runnable()
{
public void run()
{
Dialog.alert("GPS is not supported on this platform, exiting...");
//System.exit( 1 );
}
};
UiApplication.getUiApplication().invokeAndWait( showGpsUnsupportedDialog ); // Ask event-dispatcher thread to display dialog ASAP.
}
else
{
locationProvider.setLocationListener(new LocationListenerImpl(), interval, 1, 1);
retval = true;
}
}
catch (LocationException le)
{
System.err.println("Failed to instantiate the LocationProvider object, exiting...");
System.err.println(le);
System.exit(0);
}
return retval;
}
private class LocationListenerImpl implements LocationListener
{
public void locationUpdated(LocationProvider provider, Location location)
{
if(location.isValid())
{
double longitude = location.getQualifiedCoordinates().getLongitude();
double latitude = location.getQualifiedCoordinates().getLatitude();
updateLocationScreen(latitude, longitude);
}
}
public void providerStateChanged(LocationProvider provider, int newState)
{
}
}
private void updateLocationScreen(final double latitude, final double longitude)
{
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
lat = latitude;
longt = longitude;
RichTextField txt=new RichTextField();
txt.setText("Long=="+longt);
RichTextField txt1=new RichTextField();
txt1.setText("lat=="+lat);
add(txt);
add(txt1);
// persistentLatitude.setContents(Double.toString(latitude));
// persistentLongitude.setContents(Double.toString(longitude));
}
});
}
}
Try this code to get current location;
private LocationProvider provider;
private Location _location= null;
Criteria myCriteria = new Criteria();
myCriteria.setCostAllowed(true);
provider = LocationProvider.getInstance(myCriteria);
_location = provider.getLocation(4);
QualifiedCoordinates coordinates = _location.getQualifiedCoordinates();
String lon =Double.toString(coordinates.getLongitude());
String lat = Double.toString(coordinates.getLatitude());
If you are working on Blackberry OS 5.0 and letter than check my answer to "How i can get Latitude and Longitude in blackberry?". It get location within 2 or 3 second . i hope its it will help u . try it out in device and check .
Related
I am working on Blackberry Twitter integration to tweet a message on twitter.
The app is working fine in simulator but giving exception when I am running it on a device.
Here is the exception I am getting every time I run the app on the device{
OAuth_IO_Exception
I have done some research and saw a solution to set the correct date time on device, but it still is not working.
Here is my code:
import com.kc.twitter.activity.TweetToFriend;
import com.twitterapime.rest.Credential;
import com.twitterapime.xauth.Token;
import com.twitterapime.xauth.ui.OAuthDialogListener;
import com.twitterapime.xauth.ui.OAuthDialogWrapper;
import net.rim.device.api.browser.field2.BrowserField;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class TwitterScreen extends MainScreen {
private final String CONSUMER_KEY = "{redected}";
private final String CONSUMER_SECRET = "{redected}";
private final String CALLBACK_URL = "http://kingdomconnectng.net/redirect.php";
private LabelField _labelStutus;
public static OAuthDialogWrapper pageWrapper = null;
private ShowAuthBrowser showAuthBrowserScreen;
private String adminMessage;
public String adminMessages[];
boolean done=false;
Credential c ;
TweetToFriend tw;
public static StoreToken _tokenValue;
public static boolean isTweetPosted=false;
public static boolean isTweeterScreen =false ;
public TwitterScreen(final String adminMessage)
{
this.adminMessage=adminMessage;
isTweeterScreen = true ;
showAuthBrowserScreen = new ShowAuthBrowser();
_tokenValue = StoreToken.fetch();
/*if(_tokenValue.token.equalsIgnoreCase("nothing"))
{*/
showAuthBrowserScreen.doAuth(null);
UiApplication.getUiApplication().pushScreen(showAuthBrowserScreen);
/*}
else
{
final Token t = new Token(_tokenValue.token, _tokenValue.secret,
_tokenValue.userId, _tokenValue.username);
Credential c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, t);
TweetToFriend tw=new TweetToFriend();
boolean done=tw.doTweet(adminMessage, c);
if(done==true){
Dialog.alert("Tweet posted.");
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
isTweetPosted=true;
}
else{
Dialog.alert("Tweet not posted.");
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
isTweetPosted=true;
}
}*/
}
class ShowAuthBrowser extends MainScreen implements OAuthDialogListener
{
BrowserField b = new BrowserField();
public ShowAuthBrowser()
{
//if(isTweetPosted==false){
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
//}
_labelStutus = new LabelField("KingdomConnect App" );
//add(_labelStutus );
add(b);
pageWrapper = new BrowserFieldOAuthDialogWrapper(b,CONSUMER_KEY,CONSUMER_SECRET,CALLBACK_URL,this);
pageWrapper.setOAuthListener(this);
}
public void doAuth( String pin )
{
try
{
if ( pin == null )
{
pageWrapper.login();
}
else
{
this.deleteAll();
add(b);
pageWrapper.login(pin);
}
}
catch ( Exception e )
{
final String message = "Error loggin Twitter: " + e.getMessage();
Dialog.alert( message );
}
}
public void onAccessDenied(String response ) {
System.out.println("Access denied! -> " + response );
updateScreenLog( "Acceso denegado! -> " + response );
}
public void onAuthorize(final Token token) {
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run(){
UiApplication.getUiApplication().popScreen();
}
});
final Token myToken = token;
_tokenValue = StoreToken.fetch();
_tokenValue.token = myToken.getToken();
_tokenValue.secret = myToken.getSecret();
_tokenValue.userId = myToken.getUserId();
_tokenValue.username = myToken.getUsername();
_tokenValue.save();
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
try{
deleteAll();
c = new Credential(CONSUMER_KEY, CONSUMER_SECRET, myToken);
tw = new TweetToFriend();
/*done=tw.doTweet("KingdomConnect App: "+adminMessage, c);
if(done == true)
{
Dialog.alert( "Buzz posted successfully." );
close();
}
*/
prepareMessage(adminMessage);
}catch(NullPointerException e){
}catch(Exception e){
}
}
});
}
public void onFail(String arg0, String arg1) {
updateScreenLog("Error authenticating user! -> " + arg0 + ", " + arg1);
}
}
//TWEET METHOD
public void tweet(String message){
done=tw.doTweet("KingdomConnect: "+message, c);
/*if(done == true){
Dialog.alert( "Shared successfully." );
close();
} */
}
//PREPARE MESSAGE TO TWEET
public void prepareMessage(String msg){
int charLimit = 120;
int _msgSize = msg.length();
int i=0;
int parts = _msgSize/124;
try {
if(_msgSize > charLimit){
int temp1=0,temp2=charLimit;
while(i<parts+1){
String data = null;
if(i==parts){
data = msg.substring(temp1, _msgSize);
}else{
data = msg.substring(temp1, temp2);
temp1=temp2;
temp2=temp2+charLimit;
}
i++;
tweet(data);
}
Dialog.alert( "Shared successfully." );
}else{
tweet(msg);
//System.out.println("Data:======================"+msg);
}
}catch (Exception e) {
System.out.println("e = "+e);
}
}
private void updateScreenLog( final String message )
{
UiApplication.getUiApplication().invokeLater( new Runnable() {
public void run() {
_labelStutus.setText( message );
}
});
}
}
i want to know how determine the state of the GPS, soo if the state is different to AVAILABLE i don't create the Listener to save battery.
But in execution always enter for the else create the LocationListener and not for the if.
Here is my code
public class UpdateGPS extends Thread{
public void run(){
while (true){
try{
getGPS();
sleep(30000); //Update GPS for each 30secs
}
catch(Exception e){}
}
}
}
public void getGPS() {
String state = "RUNNING";
BlackBerryCriteria myCriteria = new BlackBerryCriteria(GPSInfo.GPS_MODE_ASSIST);
try {
locationProvider = LocationProvider.getInstance(myCriteria);
if (locationProvider != null) {
if (locationProvider.getState() != locationProvider.AVAILABLE) {
state= "STOP";
}
else {
locationProvider.setLocationListener(
new LocationListenerImplementacion(),valor_reintento, -1, -1);
}
}
}
catch(Exception e) {}
}
private class LocationListenerImplementacion implements LocationListener {
public void locationUpdated(LocationProvider provider,Location location) {
if (location.isValid()) {
//GET DATA
}
else {}
public void providerStateChanged(LocationProvider provider, int newState){
}
}
I have written the following code to find the location in blackberry but sometimes I am getting invalid location instance. What value should be passed to location listener to get location continuously?
package com.sims.sendlocation;
/**
*
* #author PramodKumarVishwakarma
*
*/
import java.util.Calendar;
import java.util.TimerTask;
import javax.microedition.location.Criteria;
import javax.microedition.location.Location;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import com.sims.commonmethods.Constants;
import com.sims.datahandler.GPRSHandler;
import com.sims.rms.RMSHandler;
public class LocationTimerTask extends TimerTask implements LocationListener {
private String locationStr;
private LocationProvider provider;
private String exception;
public void run()
{
try
{
Criteria criteria = new Criteria();
criteria.setCostAllowed(false);
//criteria.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
provider = LocationProvider.getInstance(criteria);
provider.setLocationListener(this, -1, -1, -1);
}
catch (Exception e)
{
RMSHandler.addDataValues(Constants.CURRENT_LOCATION,"Provider Initialization: " + e.getMessage());
System.out.println("***********"+e);
}
if (checkTimeToSendMail())
startRequestThread();
}
public boolean cancel() {
return false;
}
private void startRequestThread()
{
final GPRSHandler gprs = new GPRSHandler();
Thread thread = new Thread() {
public void run() {
try {
sleep(Constants.MINUTE * Constants.LOC_THREAD_WAIT);
{
FindLocationReceiver location = new FindLocationReceiver();
location.sendOrderToServer(RMSHandler.getDataValues(Constants.IP_INFO)+ gprs.updateConnectionSuffix().trim());
}
} catch (InterruptedException e)
{
//Dialog.ask(Dialog.D_OK, "startRequestThread: " + e);
}
}
};
thread.start();
}
private boolean checkTimeToSendMail() {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR);
if (calendar.get(Calendar.AM_PM) == 0) {
if (hour >= Constants.MNG_TIME)
return true;
} else {
if (hour < Constants.EVNG_TIME)
return true;
}
return false;
}
public void locationUpdated(LocationProvider provider, Location location)
{
if (location.isValid())
{
locationStr = location.getQualifiedCoordinates().getLatitude()+ "-" + location.getQualifiedCoordinates().getLongitude();
RMSHandler.addDataValues(Constants.CURRENT_LOCATION, locationStr);
}
else
RMSHandler.addDataValues(Constants.CURRENT_LOCATION,"Not valid Location Provider");
}
public void providerStateChanged(LocationProvider provider, int newState)
{
}
}
Sometimes I am able to get a valid location but other times I am not able to get a valid location. What value should be passed in Listener parameter list?
Can somebody tell me how to close the Screen (which opened by the BarcodeScanner) and show the mainscreen again after the barcodeDecoded method was invoked?
I can't get it right. I tried a lot, one of them was this:
public void barcodeDecoded(String rawText) {
final String result = rawText;
try
{
final UiApplication ui = UiApplication.getUiApplication();
final MainScreen current = (MainScreen) ui.getActiveScreen();
System.out.println("Current: " + current.toString());
if (UiApplication.isEventDispatchThread()) {
getText(result);
ui.popScreen(current);
System.out.println("Close Window by active screen");
ui.pushScreen(_frm);
System.out.println("Push screen frmMain");
}else{
ui.invokeLater(new Runnable() {
public void run() {
getText(result); <-- Abstract method to use within the main app.
ui.popScreen(current);
ui.pushScreen(_frm);
}
});
}
}catch(Exception err){
System.out.println(err.getMessage());
}
}
the abstract method when i start the Scanner
private MenuItem mnuCamera = new MenuItem("Scan", 1, 1){
public void run(){
frmMain f = (frmMain)getScreen();
_decode = new BarcodeDecoderClass(f) {
public void getText(String tekst) {
setScannedText(tekst);
}
};
_decode.Start();
}
};
Ok, for the people who are stuck with the same problem. I found it out. Below you find the complete code:
The BarcodeScanner class:
public abstract class BarcodeDecoderClass implements BarcodeDecoderListener {
private Hashtable _hints;
private Vector _formats;
private BarcodeScanner _scanner;
private BarcodeDecoder _decoder;
private Field _viewFinder;
private MainScreen _screen;
public abstract void getText(String tekst, Screen screen);
public BarcodeDecoderClass(){
_hints = new Hashtable();
_formats = new Vector();
_formats.addElement(BarcodeFormat.QR_CODE);
_hints.put(DecodeHintType.POSSIBLE_FORMATS, _formats);
_decoder = new BarcodeDecoder(_hints);
try
{
_scanner = new BarcodeScanner(_decoder, this);
_scanner.getVideoControl().setDisplayFullScreen(true);
_viewFinder = _scanner.getViewfinder();
}catch(Exception err){
System.out.println(err.getMessage());
}
}
public void Start(){
try
{
_screen = new MainScreen();
_screen.add(_viewFinder);
UiApplication.getUiApplication().pushScreen(_screen);
_scanner.startScan();
}catch(Exception err){
System.out.println(err.getMessage());
}
}
public synchronized void Close(){
if(_scanner.isScanning()){
try{
_scanner.stopScan();
}catch(Exception err){
Dialog.alert(err.getMessage());
}
}
_scanner.getVideoControl().setVisible(false);
_scanner.getPlayer().close();
}
public void barcodeDecoded(String rawText) {
try
{
getText(rawText, _screen);
}catch(Exception err){
System.out.println(err.getMessage());
}
}
}
The MainScreen from which I start the BarcodeScanner (i just copied the method)
private MenuItem mnuCamera = new MenuItem("Scan", 1, 1){
public void run(){
final Screen f = getScreen();
_decode = new BarcodeDecoderClass() {
public void getText(String tekst, final Screen _screen) {
setScannedText(tekst);
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_decode.Close();
_screen.close();
}
});
}
};
_decode.Start();
}
};
May be help full this code.
import java.util.Hashtable;
import java.util.Vector;
import net.rim.device.api.barcodelib.BarcodeDecoder;
import net.rim.device.api.barcodelib.BarcodeDecoderListener;
import net.rim.device.api.barcodelib.BarcodeScanner;
import net.rim.device.api.system.KeyListener;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.FullScreen;
import net.rim.device.api.ui.container.MainScreen;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
public class BarcodeScanSample extends MainScreen{
private FullScreen _barcodeScreen;
private BarcodeScanner _scanner;
private LabelField lblBarcodeText;
private ButtonField btnScan;
public BarcodeScanSample(String barcodeText){
lblBarcodeText = new LabelField(barcodeText);
add(lblBarcodeText);
btnScan = new ButtonField("Scan");
btnScan.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
scanBarcode();
}
});
add(btnScan);
}
private void scanBarcode() {
// If we haven't scanned before, we will set up our barcode scanner
if (_barcodeScreen == null) {
// First we create a hashtable to hold all of the hints that we can
// give the API about how we want to scan a barcode to improve speed
// and accuracy.
Hashtable hints = new Hashtable();
// The first thing going in is a list of formats. We could look for
// more than one at a time, but it's much slower. and set Barcode Format.
Vector formats = new Vector();
formats.addElement(BarcodeFormat.QR_CODE);
formats.addElement(BarcodeFormat.CODE_128);
formats.addElement(BarcodeFormat.CODE_39);
formats.addElement(BarcodeFormat.DATAMATRIX);
formats.addElement(BarcodeFormat.EAN_13);
formats.addElement(BarcodeFormat.EAN_8);
formats.addElement(BarcodeFormat.ITF);
formats.addElement(BarcodeFormat.PDF417);
formats.addElement(BarcodeFormat.UPC_A);
formats.addElement(BarcodeFormat.UPC_E);
hints.put(DecodeHintType.POSSIBLE_FORMATS, formats);
// We will also use the "TRY_HARDER" flag to make sure we get an
// accurate scan
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
// We create a new decoder using those hints
BarcodeDecoder decoder = new BarcodeDecoder(hints);
// Finally we can create the actual scanner with a decoder and a
// listener that will handle the data stored in the barcode. We put
// that in our view screen to handle the display.
try {
_scanner = new BarcodeScanner(decoder, new MyBarcodeDecoderListener());
_barcodeScreen = new MyBarcodeScannerViewScreen(_scanner);
} catch (Exception e) {
System.out.println("Could not initialize barcode scanner: " + e);
return;
}
}
// If we get here, all the barcode scanning infrastructure should be set
// up, so all we have to do is start the scan and display the viewfinder
try {
_scanner.startScan();
UiApplication.getUiApplication().pushScreen(_barcodeScreen);
} catch (Exception e) {
System.out.println("Could not start scan: " + e);
}
}
/***
* MyBarcodeScannerViewScreen
* <p>
* This view screen is simply an extension of MainScreen that will hold our
* scanner's viewfinder, and handle cleanly stopping the scan if the user
* decides they want to abort via the back button.
*
* #author PBernhardt
*
*/
private class MyBarcodeScannerViewScreen extends MainScreen {
public MyBarcodeScannerViewScreen(BarcodeScanner scanner) {
super();
try {
// Get the viewfinder and add it to the screen
_scanner.getVideoControl().setDisplayFullScreen(true);
Field viewFinder = _scanner.getViewfinder();
this.add(viewFinder);
// Create and add our key listener to the screen
this.addKeyListener(new MyKeyListener());
} catch (Exception e) {
System.out.println("Error creating view screen: " + e);
}
}
/***
* MyKeyListener
* <p>
* This KeyListener will stop the current scan cleanly when the back
* button is pressed, and then pop the viewfinder off the stack.
*
* #author PBernhardt
*
*/
private class MyKeyListener implements KeyListener {
public boolean keyDown(int keycode, int time) {
// First convert the keycode into an actual key event, taking
// modifiers into account
int key = Keypad.key(keycode);
// From there we can compare against the escape key constant. If
// we get it, we stop the scan and pop this screen off the stack
if (key == Keypad.KEY_ESCAPE) {
try {
_scanner.stopScan();
} catch (Exception e) {
System.out.println("Error stopping scan: " + e);
}
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().popScreen(_barcodeScreen);
}
});
return true;
}
// Otherwise, we'll return false so as not to consume the
// keyDown event
return false;
}
// We will only act on the keyDown event
public boolean keyChar(char key, int status, int time) {
return false;
}
public boolean keyRepeat(int keycode, int time) {
return false;
}
public boolean keyStatus(int keycode, int time) {
return false;
}
public boolean keyUp(int keycode, int time) {
return false;
}
}
}
/***
* MyBarcodeDecoderListener
* <p>
* This BarcodeDecoverListener implementation tries to open any data encoded
* in a barcode in the browser.
*
* #author PBernhardt
*
**/
private class MyBarcodeDecoderListener implements BarcodeDecoderListener {
public void barcodeDecoded(final String rawText) {
// First pop the viewfinder screen off of the stack so we can see
// the main app
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().popScreen(_barcodeScreen);
}
});
_barcodeScreen.invalidate();
//Display this barcode on LabelField on BarcodeScanSample MainScreen we can also set whatever field here.
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().popScreen();
UiApplication.getUiApplication().pushScreen(new BarcodeScanSample(rawText));
_barcodeScreen.close();
_barcodeScreen=null;
}
});
}
}
}
I am developing an app which has GPS functionality. How can I get latitude and longitude of the current location.
I found a solution by myself. The following code works fine for me:
package mypackage;
import javax.microedition.location.Location;
import javax.microedition.location.LocationException;
import javax.microedition.location.LocationListener;
import javax.microedition.location.LocationProvider;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.MainScreen;
public final class MyScreen extends MainScreen
{
private LocationProvider locationProvider;
private static int interval = 1;
double lat;
double longt;
public MyScreen()
{
setTitle("MyTitle");
startLocationUpdate();
}
private boolean startLocationUpdate()
{
boolean retval = false;
try
{
locationProvider = LocationProvider.getInstance(null);
if ( locationProvider == null )
{
Runnable showGpsUnsupportedDialog = new Runnable()
{
public void run()
{
Dialog.alert("GPS is not supported on this platform, exiting...");
//System.exit( 1 );
}
};
UiApplication.getUiApplication().invokeAndWait( showGpsUnsupportedDialog ); // Ask event-dispatcher thread to display dialog ASAP.
}
else
{
locationProvider.setLocationListener(new LocationListenerImpl(), interval, 1, 1);
retval = true;
}
}
catch (LocationException le)
{
System.err.println("Failed to instantiate the LocationProvider object, exiting...");
System.err.println(le);
System.exit(0);
}
return retval;
}
private class LocationListenerImpl implements LocationListener
{
public void locationUpdated(LocationProvider provider, Location location)
{
if(location.isValid())
{
double longitude = location.getQualifiedCoordinates().getLongitude();
double latitude = location.getQualifiedCoordinates().getLatitude();
updateLocationScreen(latitude, longitude);
}
}
public void providerStateChanged(LocationProvider provider, int newState)
{
}
}
private void updateLocationScreen(final double latitude, final double longitude)
{
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
lat = latitude;
longt = longitude;
RichTextField txt=new RichTextField();
txt.setText("Long=="+longt);
RichTextField txt1=new RichTextField();
txt1.setText("lat=="+lat);
add(txt);
add(txt1);
//persistentLatitude.setContents(Double.toString(latitude));
//persistentLongitude.setContents(Double.toString(longitude));
}
});
}
}
If you need to get the current location fast, then use the following code. It works for OS 6 and higher:
private void findGeolocation() {
Thread geolocThread = new Thread() {
public void run() {
try {
if (!LocationInfo.isLocationOn()) {
LocationInfo.setLocationOn();
}
BlackBerryCriteria myCriteria = new BlackBerryCriteria();
myCriteria
.enableGeolocationWithGPS(BlackBerryCriteria.FASTEST_FIX_PREFERRED);
try {
BlackBerryLocationProvider myProvider = (BlackBerryLocationProvider) LocationProvider
.getInstance(myCriteria);
try {
BlackBerryLocation myLocation = (BlackBerryLocation) myProvider
.getLocation(-1);
_longitude = myLocation.getQualifiedCoordinates()
.getLongitude();
_latitude = myLocation.getQualifiedCoordinates()
.getLatitude();
showResults(_latitude, _longitude);
} catch (InterruptedException e) {
showException(e);
} catch (LocationException e) {
showException(e);
}
} catch (LocationException e) {
showException(e);
} catch (Exception e) {
showException(e);
}
} catch (UnsupportedOperationException e) {
showException(e);
} catch (Exception e) {
showException(e);
}
}
};
geolocThread.start();
}
private void showResults(double _latitude, double _longitude) {
System.out.println("latitude = " + _latitude + "longitude" + _longitude );
Application.getApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("latitude = " + _latitude + "longitude" + _longitude );
}
});
}
private void showException(final Exception e) {
Application.getApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(e.getMessage());
}
});
}