how to get location continuously using GPS and AGPS in blackberry - blackberry

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?

Related

How to publish and receive data from Android Studio and have it on Google Cloud IoT Core?

I'm a student doing an Android Things project, which is about connecting Rasperi pi with an Accelerometer sensor to get acceleration data, I finished the coding part in Android Studio and the sensor is working fine, then I tried to connect my project to the cloud by following this tutorial: http://blog.blundellapps.co.uk/tut-google-cloud-iot-core-mqtt-on-android/
I think I have to publish the accelerometer data to the cloud by calling this method below in MainActivity class, I did that but still have an error, see the update I did at end of this question please.
#Override
public void onSensorChanged(SensorEvent event) {
Log.d(TAG, "Accel X " + event.values[0]);
Log.d(TAG, "Accel Y " + event.values[1]);
Log.d(TAG, "Accel Z " + event.values[2]);
}
Also, do I have to do something in the cloud platform to receive the data?, I already set up the communication with my Google IoT Core details as shown in the below code:
communicator = new IotCoreCommunicator.Builder()
.withContext(this)
.withCloudRegion("us-central1")
.withProjectId("my-first-project-198704")
.withRegistryId("vibration")
.withDeviceId("my-device")
.withPrivateKeyRawFileId(R.raw.rsa_private)
.build();
This is what I'm seeing in the cloud:
And this is the acceleration data I have in Android Studio:
My project consists of two modules but here I will attach only the second module because the question is limited to 3000 characters only and the second module is what I need to edit I think.
sample module:
AccelerometerActivity class:
package com.cacaosd.sample;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import com.cacaosd.adxl345.ADXL345SensorDriver;
import com.cacaosd.sample.BoardDefaults;
import java.io.IOException;
public class AccelerometerActivity extends Activity implements SensorEventListener {
private static final String TAG = AccelerometerActivity.class.getSimpleName();
private ADXL345SensorDriver mSensorDriver;
private SensorManager mSensorManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorManager.registerDynamicSensorCallback(new SensorManager.DynamicSensorCallback() {
#Override
public void onDynamicSensorConnected(Sensor sensor) {
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
mSensorManager.registerListener(AccelerometerActivity.this,
sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
});
try {
mSensorDriver = new ADXL345SensorDriver(BoardDefaults.getI2CPort());
mSensorDriver.registerAccelerometerSensor();
} catch (IOException e) {
Log.e(TAG, "Error configuring sensor", e);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "Closing sensor");
if (mSensorDriver != null) {
mSensorManager.unregisterListener(this);
try {
mSensorDriver.close();
} catch (IOException e) {
Log.e(TAG, "Error closing sensor", e);
} catch (Exception e) {
e.printStackTrace();
} finally {
mSensorDriver = null;
}
}
}
#Override
public void onSensorChanged(SensorEvent event) {
Log.d(TAG, "Accel X " + event.values[0]);
Log.d(TAG, "Accel Y " + event.values[1]);
Log.d(TAG, "Accel Z " + event.values[2]);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.i(TAG, "sensor accuracy changed: " + accuracy);
}
}
BoardDefaults class:
package com.cacaosd.sample;
import android.os.Build;
import com.google.android.things.pio.PeripheralManagerService;
import java.util.List;
/**
* Created by cagdas on 20.12.2016.
*/
#SuppressWarnings("WeakerAccess")
public class BoardDefaults {
private static final String DEVICE_EDISON_ARDUINO = "edison_arduino";
private static final String DEVICE_EDISON = "edison";
private static final String DEVICE_RPI3 = "rpi3";
private static final String DEVICE_NXP = "imx6ul";
private static String sBoardVariant = "";
/**
* Return the preferred I2C port for each board.
*/
public static String getI2CPort() {
switch (getBoardVariant()) {
case DEVICE_EDISON_ARDUINO:
return "I2C6";
case DEVICE_EDISON:
return "I2C1";
case DEVICE_RPI3:
return "I2C1";
case DEVICE_NXP:
return "I2C2";
default:
throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE);
}
}
private static String getBoardVariant() {
if (!sBoardVariant.isEmpty()) {
return sBoardVariant;
}
sBoardVariant = Build.DEVICE;
// For the edison check the pin prefix
// to always return Edison Breakout pin name when applicable.
if (sBoardVariant.equals(DEVICE_EDISON)) {
PeripheralManagerService pioService = new PeripheralManagerService();
List<String> gpioList = pioService.getGpioList();
if (gpioList.size() != 0) {
String pin = gpioList.get(0);
if (pin.startsWith("IO")) {
sBoardVariant = DEVICE_EDISON_ARDUINO;
}
}
}
return sBoardVariant;
}
}
IotCoreCommunicator class:
package com.cacaosd.sample1;
import android.content.Context;
import android.util.Log;
import java.util.concurrent.TimeUnit;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class IotCoreCommunicator {
private static final String SERVER_URI = "ssl://mqtt.googleapis.com:8883";
public static class Builder {
private Context context;
private String projectId;
private String cloudRegion;
private String registryId;
private String deviceId;
private int privateKeyRawFileId;
public Builder withContext(Context context) {
this.context = context;
return this;
}
public Builder withProjectId(String projectId) {
this.projectId = projectId;
return this;
}
public Builder withCloudRegion(String cloudRegion) {
this.cloudRegion = cloudRegion;
return this;
}
public Builder withRegistryId(String registryId) {
this.registryId = registryId;
return this;
}
public Builder withDeviceId(String deviceId) {
this.deviceId = deviceId;
return this;
}
public Builder withPrivateKeyRawFileId(int privateKeyRawFileId) {
this.privateKeyRawFileId = privateKeyRawFileId;
return this;
}
public IotCoreCommunicator build() {
if (context == null) {
throw new IllegalStateException("context must not be null");
}
if (projectId == null) {
throw new IllegalStateException("projectId must not be null");
}
if (cloudRegion == null) {
throw new IllegalStateException("cloudRegion must not be null");
}
if (registryId == null) {
throw new IllegalStateException("registryId must not be null");
}
if (deviceId == null) {
throw new IllegalStateException("deviceId must not be null");
}
String clientId = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/" + registryId + "/devices/" + deviceId;
if (privateKeyRawFileId == 0) {
throw new IllegalStateException("privateKeyRawFileId must not be 0");
}
MqttAndroidClient client = new MqttAndroidClient(context, SERVER_URI, clientId);
IotCorePasswordGenerator passwordGenerator = new IotCorePasswordGenerator(projectId, context.getResources(), privateKeyRawFileId);
return new IotCoreCommunicator(client, deviceId, passwordGenerator);
}
}
private final MqttAndroidClient client;
private final String deviceId;
private final IotCorePasswordGenerator passwordGenerator;
IotCoreCommunicator(MqttAndroidClient client, String deviceId, IotCorePasswordGenerator passwordGenerator) {
this.client = client;
this.deviceId = deviceId;
this.passwordGenerator = passwordGenerator;
}
public void connect() {
monitorConnection();
clientConnect();
subscribeToConfigChanges();
}
private void monitorConnection() {
client.setCallback(new MqttCallback() {
#Override
public void connectionLost(Throwable cause) {
Log.e("TUT", "connection lost", cause);
}
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
Log.d("TUT", "message arrived " + topic + " MSG " + message);
// You need to do something with messages when they arrive
}
#Override
public void deliveryComplete(IMqttDeliveryToken token) {
Log.d("TUT", "delivery complete " + token);
}
});
}
private void clientConnect() {
try {
MqttConnectOptions connectOptions = new MqttConnectOptions();
// Note that the the Google Cloud IoT Core only supports MQTT 3.1.1, and Paho requires that we explicitly set this.
// If you don't, the server will immediately close its connection to your device.
connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
// With Google Cloud IoT Core, the username field is ignored, however it must be set for the
// Paho client library to send the password field. The password field is used to transmit a JWT to authorize the device.
connectOptions.setUserName("unused-but-necessary");
connectOptions.setPassword(passwordGenerator.createJwtRsaPassword());
IMqttToken iMqttToken = client.connect(connectOptions);
iMqttToken.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("TUT", "success, connected");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.e("TUT", "failure, not connected", exception);
}
});
iMqttToken.waitForCompletion(TimeUnit.SECONDS.toMillis(30));
Log.d("TUT", "IoT Core connection established.");
} catch (MqttException e) {
throw new IllegalStateException(e);
}
}
/**
* Configuration is managed and sent from the IoT Core Platform
*/
private void subscribeToConfigChanges() {
try {
client.subscribe("/devices/" + deviceId + "/config", 1);
} catch (MqttException e) {
throw new IllegalStateException(e);
}
}
public void publishMessage(String subtopic, String message) {
String topic = "/devices/" + deviceId + "/" + subtopic;
String payload = "{msg:\"" + message + "\"}";
MqttMessage mqttMessage = new MqttMessage(payload.getBytes());
mqttMessage.setQos(1);
try {
client.publish(topic, mqttMessage);
Log.d("TUT", "IoT Core message published. To topic: " + topic);
} catch (MqttException e) {
throw new IllegalStateException(e);
}
}
public void disconnect() {
try {
Log.d("TUT", "IoT Core connection disconnected.");
client.disconnect();
} catch (MqttException e) {
throw new IllegalStateException(e);
}
}
}
IotCorePasswordGenerator class:
package com.cacaosd.sample1;
import android.content.res.Resources;
import android.util.Base64;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
class IotCorePasswordGenerator {
private final String projectId;
private final Resources resources;
private final int privateKeyRawFileId;
IotCorePasswordGenerator(String projectId, Resources resources, int privateKeyRawFileId) {
this.projectId = projectId;
this.resources = resources;
this.privateKeyRawFileId = privateKeyRawFileId;
}
char[] createJwtRsaPassword() {
try {
byte[] privateKeyBytes = decodePrivateKey(resources, privateKeyRawFileId);
return createJwtRsaPassword(projectId, privateKeyBytes).toCharArray();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Algorithm not supported. (developer error)", e);
} catch (InvalidKeySpecException e) {
throw new IllegalStateException("Invalid Key spec. (developer error)", e);
} catch (IOException e) {
throw new IllegalStateException("Cannot read private key file.", e);
}
}
private static byte[] decodePrivateKey(Resources resources, int privateKeyRawFileId) throws IOException {
try(InputStream inStream = resources.openRawResource(privateKeyRawFileId)) {
return Base64.decode(inputToString(inStream), Base64.DEFAULT);
}
}
private static String inputToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
private static String createJwtRsaPassword(String projectId, byte[] privateKeyBytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
return createPassword(projectId, privateKeyBytes, "RSA", SignatureAlgorithm.RS256);
}
private static String createPassword(String projectId, byte[] privateKeyBytes, String algorithmName, SignatureAlgorithm signatureAlgorithm) throws NoSuchAlgorithmException, InvalidKeySpecException {
Instant now = Instant.now();
// Create a JWT to authenticate this device. The device will be disconnected after the token
// expires, and will have to reconnect with a new token. The audience field should always be set
// to the GCP project id.
JwtBuilder jwtBuilder =
Jwts.builder()
.setIssuedAt(Date.from(now))
.setExpiration(Date.from(now.plus(Duration.ofMinutes(20))))
.setAudience(projectId);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory kf = KeyFactory.getInstance(algorithmName);
return jwtBuilder.signWith(signatureAlgorithm, kf.generatePrivate(spec)).compact();
}
}
MainActivity class:
package com.cacaosd.sample1;
import android.app.Activity;
import android.hardware.SensorEvent;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.Handler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import com.cacaosd.sample.AccelerometerActivity;
import com.cacaosd.sample.R;
import com.cacaosd.sample1.IotCoreCommunicator;
import com.google.android.things.pio.Gpio;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class MainActivity extends Activity {
AccelerometerActivity mAccelerometerActivity = new AccelerometerActivity();
private IotCoreCommunicator communicator;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the communication with your Google IoT Core details
communicator = new IotCoreCommunicator.Builder()
.withContext(this)
.withCloudRegion("us-central1") // ex: europe-west1
.withProjectId("my-first-project-198704") // ex: supercoolproject23236
.withRegistryId("vibration") // ex: my-devices
.withDeviceId("my-device") // ex: my-test-raspberry-pi
.withPrivateKeyRawFileId(R.raw.rsa_private)
.build();
HandlerThread thread = new HandlerThread("MyBackgroundThread");
thread.start();
handler = new Handler(thread.getLooper());
handler.post(connectOffTheMainThread); // Use whatever threading mechanism you want
}
private final Runnable connectOffTheMainThread = new Runnable() {
#Override
public void run() {
communicator.connect();
handler.post(sendMqttMessage);
}
};
private final Runnable sendMqttMessage = new Runnable() {
private int i;
/**
* We post 100 messages as an example, 1 a second
*/
#Override
public void run() {
if (i == 100) {
return;
}
SensorEvent event = null;
// events is the default topic for MQTT communication
String subtopic = "events";
// Your message you want to send
String message = "Hello World " + i++;
communicator.publishMessage(subtopic, message);
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(1));
}
};
#Override
protected void onDestroy() {
communicator.disconnect();
super.onDestroy();
}
MainActivity class:
package com.cacaosd.sample1;
import android.app.Activity;
import android.hardware.SensorEvent;
import android.os.Bundle;
import android.os.HandlerThread;
import android.os.Handler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import com.cacaosd.sample.AccelerometerActivity;
import com.cacaosd.sample.R;
import com.cacaosd.sample1.IotCoreCommunicator;
import com.google.android.things.pio.Gpio;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class MainActivity extends Activity {
AccelerometerActivity mAccelerometerActivity = new AccelerometerActivity();
private IotCoreCommunicator communicator;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the communication with your Google IoT Core details
communicator = new IotCoreCommunicator.Builder()
.withContext(this)
.withCloudRegion("us-central1") // ex: europe-west1
.withProjectId("my-first-project-198704") // ex: supercoolproject23236
.withRegistryId("vibration") // ex: my-devices
.withDeviceId("my-device") // ex: my-test-raspberry-pi
.withPrivateKeyRawFileId(R.raw.rsa_private)
.build();
HandlerThread thread = new HandlerThread("MyBackgroundThread");
thread.start();
handler = new Handler(thread.getLooper());
handler.post(connectOffTheMainThread); // Use whatever threading mechanism you want
}
private final Runnable connectOffTheMainThread = new Runnable() {
#Override
public void run() {
communicator.connect();
handler.post(sendMqttMessage);
}
};
private final Runnable sendMqttMessage = new Runnable() {
private int i;
/**
* We post 100 messages as an example, 1 a second
*/
#Override
public void run() {
if (i == 100) {
return;
}
SensorEvent event = null;
// events is the default topic for MQTT communication
String subtopic = "events";
// Your message you want to send
String message = "Hello World " + i++;
communicator.publishMessage(subtopic, message);
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(1));
}
};
#Override
protected void onDestroy() {
communicator.disconnect();
super.onDestroy();
}
}
Update:
I added a third input (int acceleration) on publishMessage() method inside IotCoreCommunicator class like below:
public void publishMessage(String subtopic, String message, int acceleration) {
String topic = "/devices/" + deviceId + "/" + subtopic;
String payload = "{msg:\"" + message + "\"}";
MqttMessage mqttMessage = new MqttMessage(payload.getBytes());
mqttMessage.setQos(1);
try {
client.publish(topic, mqttMessage);
Log.d("TUT", "IoT Core message published. To topic: " + topic);
} catch (MqttException e) {
throw new IllegalStateException(e);
}
}
Then I call it on run() method inside the MainActivity class like below:
public void run() {
if (i == 100) {
return;
}
SensorEvent event = null;
// events is the default topic for MQTT communication
String subtopic = "events";
// Your message you want to send
String message = "Hello World " + i++;
int acceleration = mAccelerometerActivity.onSensorChanged(SensorEvent event.values);
communicator.publishMessage(subtopic, message, acceleration);
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(1));
}
};
But I still have this error in the below screenshot:
(';' or ) expected)
Also the third input I added is shown like never been used as you see in the screenshot below, is this has any effect?
Thank you.

get latitude and longitude of current location blackberry

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 .

Blackberry BarcodeScanner - barcodeDecode switch to MainScreen

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;
}
});
}
}
}

How can I get latitude and longitude of the current location in Blackberry?

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());
}
});
}

Launch the video recorder from BlackBerry app

Are there any APIs to launch the video recording app? I want to invoke the video recorder through my app, record a video, then save that video to the server.
ApplicationManager.getApplicationManager().launch("net_rim_bb_videorecorder");
This will help you open the application. If you want to start recording, you may need to simulate a key input.
btw: CameraArguments(ARG_VIDEO_RECORDER) is introduced since jde4.7, so it's not compatible with the previous OS's. So the previous method is better.
Finally find the solution from BB docs .
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.system.*;
import java.lang.*;
import javax.microedition.media.*;
import java.io.*;
import javax.microedition.media.control.*;
public class VideoRecordingDemo extends UiApplication
{
public static void main(String[] args)
{
VideoRecordingDemo app = new VideoRecordingDemo();
app.enterEventDispatcher();
}
public VideoRecordingDemo()
{
pushScreen(new VideoRecordingDemoScreen());
}
private class VideoRecordingDemoScreen extends MainScreen
{
private VideoRecorderThread _recorderThread;
public VideoRecordingDemoScreen()
{
setTitle("Video recording demo");
addMenuItem(new StartRecording());
addMenuItem(new StopRecording());
}
private class StartRecording extends MenuItem
{
public StartRecording()
{
super("Start recording", 0, 100);
}
public void run()
{
try
{
VideoRecorderThread newRecorderThread = new VideoRecorderThread();
newRecorderThread.start();
_recorderThread = newRecorderThread;
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
}
}
private class StopRecording extends MenuItem
{
public StopRecording()
{
super("Stop recording", 0, 100);
}
public void run()
{
try
{
if (_recorderThread != null)
{
_recorderThread.stop();
}
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
}
}
private class VideoRecorderThread extends Thread implements javax.microedition.media.PlayerListener
{
private Player _player;
private RecordControl _recordControl;
VideoRecorderThread()
{
}
public void run()
{
try
{
_player = javax.microedition.media.Manager.createPlayer("capture://video?encoding=video/3gpp");
_player.addPlayerListener(this);
_player.realize();
VideoControl videoControl = (VideoControl) _player.getControl("VideoControl");
_recordControl = (RecordControl) _player.getControl( "RecordControl" );
Field videoField = (Field) videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
try
{
videoControl.setDisplaySize( Display.getWidth(), Display.getHeight() );
}
catch( MediaException me )
{
// setDisplaySize is not supported
}
add(videoField);
_recordControl.setRecordLocation("file:///store/home/user/VideoRecordingTest.3gpp" );
_recordControl.startRecord();
_player.start();
}
catch( IOException e )
{
Dialog.alert(e.toString());
}
catch( MediaException e )
{
Dialog.alert(e.toString());
}
}
public void stop()
{
if (_player != null)
{
_player.close();
_player = null;
}
if (_recordControl != null)
{
_recordControl.stopRecord();
try
{
_recordControl.commit();
}
catch (Exception e)
{
Dialog.alert(e.toString());
}
_recordControl = null;
}
}
public void playerUpdate(Player player, String event, Object eventData)
{
Dialog.alert("Player " + player.hashCode() + " got event " + event + ": " + eventData);
}
}
}
}

Resources