Get GPS location on BlackBerry - blackberry

I can't read location with this function. When I try to get location information, it always returns altitude 0, longitude 0.
void getirGps(){
Criteria myCriteria = new Criteria();
myCriteria.setCostAllowed(false);
try
{
LocationProvider myLocationProvider =
LocationProvider.getInstance(myCriteria);
try
{
Location myLocation = myLocationProvider.getLocation(300);
seTLatitude(myLocation.getQualifiedCoordinates().getLatitude());// sunlarıda bir public statıc dene..
seTLongitude(myLocation.getQualifiedCoordinates().getLongitude());
Dialog.alert("latitude = "+GPSThread.latitude +" longi"+GPSThread.longitude);
velocity = myLocation.getSpeed();
heading = myLocation.getCourse();
timeStamp = myLocation.getTimestamp();
nmeaString = myLocation.getExtraInfo
("application/X-jsr179-location-nmea");
}
catch ( InterruptedException iex )
{
Dialog.alert("InterruptedException");
return;
}
catch ( LocationException lex )
{
Dialog.alert("LocationException lex");
return;
}
}
catch ( LocationException lex )
{
Dialog.alert("LocationException lex2");
return;
}
}
public void doThis(){
MapView mapView = new MapView();
mapView.setLatitude( (int) Threads.latitude);//39.9208, Longitude = 32.8541
mapView.setLongitude((int) Threads.longitude);
mapView.setZoom(10);
MapsArguments mapsArgs = new MapsArguments(mapView);
Invoke.invokeApplication(Invoke.APP_TYPE_MAPS, mapsArgs);
Dialog.alert("latitude = "+Threads.latitude +" longi"+Threads.longitude);

Make sure the GPS functionality is enabled on the device.

Related

manipulate JavaCamera2View to set Parameters for Camera Device - OpenCV in Android

Software: Android 4.1.1, OpenCV 4.5.0
To briefly summarize my project. i want to continuously monitor the 'frequency' of a flickering led light source using the rolling shutter effect based on a cmos camera of an android smartphone. in the video/'image stream' a light dark stripe pattern should be visible, which i want to analize with opencv.
if you are interested in the method, you can find more information here:
RollingLight: Light-to-Camera Communications
now the actual problem: i need to set the camera parameters to fixed values before i start analizing with opencv. the exposure time should be as short as possible, the iso (sensitivity) should get a medium value and the focus should be set as close as possible.
for this i made the following changes (marked as comments //) in the methods initializeCamera() and createCameraPreviewSession() from the opencv's JavaCamera2View.java file.
initializeCamera() - from JavaCamera2View.java
public int minExposure = 0;
public int maxExposure = 0;
public long valueExposure = minExposure;
public float valueFocus = 0;
public int minIso = 0;
public int maxIso = 0;
public int valueIso = minIso;
public long valueFrameDuration = 0;
protected boolean initializeCamera() {
Log.i(LOGTAG, "initializeCamera");
CameraManager manager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
try {
String camList[] = manager.getCameraIdList();
if (camList.length == 0) {
Log.e(LOGTAG, "Error: camera isn't detected.");
return false;
}
if (mCameraIndex == CameraBridgeViewBase.CAMERA_ID_ANY) {
mCameraID = camList[0];
} else {
for (String cameraID : camList) {
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraID);
if ((mCameraIndex == CameraBridgeViewBase.CAMERA_ID_BACK &&
characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) ||
(mCameraIndex == CameraBridgeViewBase.CAMERA_ID_FRONT &&
characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT)
) {
mCameraID = cameraID;
break;
}
}
}
if (mCameraID != null) {
Log.i(LOGTAG, "Opening camera: " + mCameraID);
//I added this code to get the parameters---------------------------------------------------------------------------
CameraManager mCameraManager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
try {
CameraCharacteristics mCameraCharacteristics = mCameraManager.getCameraCharacteristics(mCameraID);
valueFocus = mCameraCharacteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE);
Range<Integer> rangeExposure = mCameraCharacteristics.get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE);
minExposure = rangeExposure.getLower();
maxExposure = rangeExposure.getUpper();
Range<Integer> rangeIso = mCameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_SENSITIVITY_RANGE);
minIso = rangeIso.getLower();
maxIso = rangeIso.getUpper();
valueFrameDuration = mCameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_MAX_FRAME_DURATION);
} catch (CameraAccessException e) {
Log.e(LOGTAG, "calcPreviewSize - Camera Access Exception", e);
} catch (IllegalArgumentException e) {
Log.e(LOGTAG, "calcPreviewSize - Illegal Argument Exception", e);
} catch (SecurityException e) {
Log.e(LOGTAG, "calcPreviewSize - Security Exception", e);
}
//end of code-------------------------------------------------------------------------------------------------------
manager.openCamera(mCameraID, mStateCallback, mBackgroundHandler);
} else { // make JavaCamera2View behaves in the same way as JavaCameraView
Log.i(LOGTAG, "Trying to open camera with the value (" + mCameraIndex + ")");
if (mCameraIndex < camList.length) {
mCameraID = camList[mCameraIndex];
manager.openCamera(mCameraID, mStateCallback, mBackgroundHandler);
} else {
// CAMERA_DISCONNECTED is used when the camera id is no longer valid
throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED);
}
}
return true;
} catch (CameraAccessException e) {
Log.e(LOGTAG, "OpenCamera - Camera Access Exception", e);
} catch (IllegalArgumentException e) {
Log.e(LOGTAG, "OpenCamera - Illegal Argument Exception", e);
} catch (SecurityException e) {
Log.e(LOGTAG, "OpenCamera - Security Exception", e);
}
return false;
}
createCameraPreviewSession() - from JavaCamera2View.java
private void createCameraPreviewSession() {
final int w = mPreviewSize.getWidth(), h = mPreviewSize.getHeight();
Log.i(LOGTAG, "createCameraPreviewSession(" + w + "x" + h + ")");
if (w < 0 || h < 0)
return;
try {
if (null == mCameraDevice) {
Log.e(LOGTAG, "createCameraPreviewSession: camera isn't opened");
return;
}
if (null != mCaptureSession) {
Log.e(LOGTAG, "createCameraPreviewSession: mCaptureSession is already started");
return;
}
mImageReader = ImageReader.newInstance(w, h, mPreviewFormat, 2);
mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = reader.acquireLatestImage();
if (image == null)
return;
// sanity checks - 3 planes
Image.Plane[] planes = image.getPlanes();
assert (planes.length == 3);
assert (image.getFormat() == mPreviewFormat);
JavaCamera2Frame tempFrame = new JavaCamera2Frame(image);
deliverAndDrawFrame(tempFrame);
tempFrame.release();
image.close();
}
}, mBackgroundHandler);
Surface surface = mImageReader.getSurface();
mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_MANUAL);
mPreviewRequestBuilder.addTarget(surface);
mCameraDevice.createCaptureSession(Arrays.asList(surface),
new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(CameraCaptureSession cameraCaptureSession) {
Log.i(LOGTAG, "createCaptureSession::onConfigured");
if (null == mCameraDevice) {
return; // camera is already closed
}
mCaptureSession = cameraCaptureSession;
try {
//I added this code to set the parameters---------------------------------------------------------------------------
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_OFF);
mPreviewRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, valueFocus);
mPreviewRequestBuilder.set(CaptureRequest.SENSOR_EXPOSURE_TIME, valueExposure);
mPreviewRequestBuilder.set(CaptureRequest.SENSOR_SENSITIVITY, valueIso);
mPreviewRequestBuilder.set(CaptureRequest.SENSOR_FRAME_DURATION, valueFrameDuration);
//end of code-------------------------------------------------------------------------------------------------------
mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
Log.i(LOGTAG, "CameraPreviewSession has been started");
} catch (Exception e) {
Log.e(LOGTAG, "createCaptureSession failed", e);
}
}
#Override
public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
Log.e(LOGTAG, "createCameraPreviewSession failed");
}
},
null
);
} catch (CameraAccessException e) {
Log.e(LOGTAG, "createCameraPreviewSession", e);
}
}
unfortunately, the above editing does not work. console shows:
java.lang.NullPointerException: Attempt to invoke virtual method 'float java.lang.Float.floatValue()' on a null object reference
maybe not the only problem i guess.
i have already read numerous posts about the interaction between opencv and androids camera 2 (camerax) api. regarding my question, however, this post unfortunately sums it up: "OpenCV will not work with android.camera2" but, the post is a few years old and i hope there is a workaround for the problem by now.
1.) do you know how i can set fix camera parameters and then do an analysis in opencv? could you explain the steps to me?
2.) are there any existing available projects as reference?
3.) i need the highest possible frame rate of the camera. otherwise i would have thought that i could work with getbitmap(); and forward the image to opencv. but the frame rate is really bad and besides i'm not sure here either how to set the camera parameters fix before taking the photo. or do you know any alternatives?
thanks in advance for your support. if you need more info, i will be happy to share it with you.
--
2021 arpil: the questions are still unanswered. if someone doesn't answer them in detail but has links that could help me, i would really appreciate it.

Draw rectangle in MKMapView

I am trying to draw a red rectangle in my MKMapView. I see the map, but not the rectangle. My code:
public override void ViewDidLoad()
{
base.ViewDidLoad();
var areaMapView = new AreaMapView();
areaMapView.SetTarget(45.5399396, -73.6534612);
areaMapView.AddZone(new List<Geolocation>()
{
new Geolocation() { Latitude = 25.774, Longitude = -80.190},
new Geolocation() { Latitude = 18.466, Longitude = -66.118},
new Geolocation() { Latitude = 32.321, Longitude = -64.757},
new Geolocation() { Latitude = 25.774, Longitude = -80.190},
});
View = areaMapView;
}
public class AreaMapView : MKMapView
{
public AreaMapView() : base(UIScreen.MainScreen.Bounds)
{
this.ShowsUserLocation = true;
this.MapType = MKMapType.Satellite;
}
public void SetTarget(double longitude, double latitude)
{
this.AddAnnotations(new MKPointAnnotation()
{
Title = "Target",
Coordinate = new CLLocationCoordinate2D(longitude, latitude)
});
}
public void AddZone(List<Geolocation> longitudeAndLatitudePoints)
{
var coords = new CLLocationCoordinate2D[longitudeAndLatitudePoints.Count];
for (int i = 0; i < longitudeAndLatitudePoints.Count; i++)
{
double longitude = longitudeAndLatitudePoints[i].Longitude;
double latitude = longitudeAndLatitudePoints[i].Latitude;
coords[i] = new CLLocationCoordinate2D(longitude, latitude);
}
this.AddOverlay(MKPolyline.FromCoordinates(coords));
}
}
I think you should use MKPolygon and MKPolygonRenderer to add a rectangle.
refer to here: https://developer.xamarin.com/recipes/ios/content_controls/map_view/add_an_overlay_to_a_map/
Sample here: https://github.com/xamarin/recipes/tree/master/ios/content_controls/map_view/add_an_overlay_to_a_map
follow the sample and replace the code
mapView.OverlayRenderer = (m, o) =>
{
if (circleRenderer == null)
{
circleRenderer = new MKCircleRenderer(o as MKCircle);
circleRenderer.FillColor = UIColor.Purple;
circleRenderer.Alpha = 0.5f;
}
return circleRenderer;
};
circleOverlay = MKCircle.Circle(coords, 400);
mapView.AddOverlay(circleOverlay);
By
mapView.OverlayRenderer = (m, o) =>
{
if (polygonRenderer == null)
{
polygonRenderer = new MKPolygonRenderer(o as MKPolygon);
polygonRenderer.FillColor = UIColor.Red;
polygonRenderer.StrokeColor = UIColor.Black;
polygonRenderer.Alpha = 0.5f;
}
return polygonRenderer;
};
var coord = new CLLocationCoordinate2D[4];
coord[0] = new CLLocationCoordinate2D(29.976111, 31.132778);
coord[1] = new CLLocationCoordinate2D(29.976111, 31.032778);
coord[2] = new CLLocationCoordinate2D(29.876111, 31.032778);
coord[3] = new CLLocationCoordinate2D(29.876111, 31.132778);
mapView.AddOverlay(MKPolygon.FromCoordinates(coord));
This is the result

Monotouch : Get user current lcoation

How can i get use location in monotouch?
i'm trying with following code but any events does not fire(AuthorizationChanged & LocationsUpdated)
How should i do?please advise
public Task<CLLocation> test()
{
TaskCompletionSource<CLLocation> objTaskCompletionSource1 = new TaskCompletionSource<CLLocation> ();
CLLocation currentLocation = null;
CLLocationManager LocMgr = new CLLocationManager ();
if (CLLocationManager.LocationServicesEnabled)
{
LocMgr.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) =>
{
currentLocation = e.Locations [e.Locations.Length - 1];
locationUpdated = false;
if (currentLocation != null && AllAreas != null)
{
LocationDetector.Instance.UpdateCurrentArea (new RLatLng (currentLocation.Coordinate.Latitude, currentLocation.Coordinate.Longitude));
objTaskCompletionSource1.SetResult(currentLocation);
}
else
{
currentLocation = null;
objTaskCompletionSource1.SetResult(currentLocation);
}
};
LocMgr.AuthorizationChanged+= (object sender, CLAuthorizationChangedEventArgs e) => {
Console.WriteLine("AuthorizationChanged Fired");
};
LocMgr.Failed += (object sender, NSErrorEventArgs e) =>
{
};
LocMgr.StartUpdatingLocation ();
}
else
{
currentLocation = null;
objTaskCompletionSource1.SetResult (currentLocation);
Console.WriteLine ("Location services not enabled, please enable this in your Settings");
}
return objTaskCompletionSource1.Task;
}
Chances are you are testing this on iOS 8.
For iOS 8 you now need to request authorization.
So use something like the following in your ViewDidLoad (make LocMgr class scope level - so remove the local instance in your version):-
LocMgr = new CLLocationManager();
if (UIDevice.CurrentDevice.CheckSystemVersion(8,0))
{
LocMgr.RequestWhenInUseAuthorization();
}
Also, in order for the above to work, and for the dialog box to show you also need to add the following entry into your info.plist:-
<key>NSLocationWhenInUseUsageDescription</key>
<value>{some message that will be shown to the end-user}</value>
Update 1:-
Code that I am using:-
In ViewDidLoad:-
LocMgr = new CLLocationManager ();
if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) {
LocMgr.RequestWhenInUseAuthorization ();
}
UIButton objButton1 = new UIButton (UIButtonType.RoundedRect);
objButton1.SetTitle ("Click Me", UIControlState.Normal);
objButton1.TouchUpInside += (async (o2, e2) => {
CLLocation objLocationInfo = await Test1();
Console.WriteLine("Completed");
});
this.View = objButton1;
And the Test1 function:-
public Task<CLLocation> Test1()
{
TaskCompletionSource<CLLocation> objTaskCompletionSource1 = new TaskCompletionSource<CLLocation> ();
CLLocation currentLocation = null;
if (CLLocationManager.LocationServicesEnabled) {
LocMgr.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
currentLocation = e.Locations [e.Locations.Length - 1];
locationUpdated = false;
//if (currentLocation != null && AllAreas != null) {
if (currentLocation != null) {
//LocationDetector.Instance.UpdateCurrentArea (new RLatLng (currentLocation.Coordinate.Latitude, currentLocation.Coordinate.Longitude));
objTaskCompletionSource1.SetResult (currentLocation);
} else {
currentLocation = null;
objTaskCompletionSource1.SetResult (currentLocation);
}
};
LocMgr.AuthorizationChanged += (object sender, CLAuthorizationChangedEventArgs e) => {
Console.WriteLine ("AuthorizationChanged Fired");
};
LocMgr.Failed += (object sender, NSErrorEventArgs e) => {
Console.WriteLine("AHH Failed");
};
LocMgr.StartUpdatingLocation ();
} else {
currentLocation = null;
objTaskCompletionSource1.SetResult (currentLocation);
Console.WriteLine ("Location services not enabled, please enable this in your Settings");
}
return objTaskCompletionSource1.Task;
}
Your need these also at class level:-
private bool locationUpdated = false;
private CLLocation currentLocation = null;
private CLLocationManager LocMgr;
Remember you need to edit your info.plist as well.
If you then run the example putting a breakpoint at the Console.WriteLine("Completed"); you should then be able to inspect objLocationInfo and see that it has a location.

duplicate SSID in scanning wifi result

i'm trying to make an app that can create a list of available wifi access point. here's part of the code i used:
x = new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
if (results != null) {
for (int i=0; i<size; i++){
ScanResult scanresult = wifi.getScanResults().get(i);
String ssid = scanresult.SSID;
int rssi = scanresult.level;
String rssiString = String.valueOf(rssi);
textStatus.append(ssid + "," + rssiString);
textStatus.append("\n");
}
unregisterReceiver(x); //stops the continuous scan
textState.setText("Scanning complete!");
} else {
unregisterReceiver(x);
textState.setText("Nothing is found. Please make sure you are under any wifi coverage");
}
}
};
both textStatus and textState is a TextView.
i can get this to work but sometimes the result shows duplicate SSID but with different signal level, in a single scan. there might be 3-4 same SSIDs but with different signal level.
is it really different SSIDs and what differs them? can anyone explain?
Are you having several router modems for the same network? For example: A company has a big wireless network with multiple router modems installed in several places so every room has Wifi. If you do that scan you will get a lot of results with the same SSIDs but with different acces points, and thus different signal level.
EDIT:
According to Walt's comment you can also have multiple results despite having only one access point if your modem is dual-band.
use below code to to remove duplicate ssids with highest signal strength
public void onReceive(Context c, Intent intent) {
ArrayList<ScanResult> mItems = new ArrayList<>();
List<ScanResult> results = wifiManager.getScanResults();
wifiListAdapter = new WifiListAdapter(ConnectToInternetActivity.this, mItems);
lv.setAdapter(wifiListAdapter);
int size = results.size();
HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
try {
for (int i = 0; i < size; i++) {
ScanResult result = results.get(i);
if (!result.SSID.isEmpty()) {
String key = result.SSID + " "
+ result.capabilities;
if (!signalStrength.containsKey(key)) {
signalStrength.put(key, i);
mItems.add(result);
wifiListAdapter.notifyDataSetChanged();
} else {
int position = signalStrength.get(key);
ScanResult updateItem = mItems.get(position);
if (calculateSignalStength(wifiManager, updateItem.level) >
calculateSignalStength(wifiManager, result.level)) {
mItems.set(position, updateItem);
wifiListAdapter.notifyDataSetChanged();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is my simple Solution please and it is work for me
private void scanWifiListNew() {
wifiManager.startScan();
List<ScanResult> wifiList = wifiManager.getScanResults();
mWiFiList = new ArrayList<>();
for(ScanResult result: wifiList){
checkItemExists(mWiFiList, result);
}
setAdapter(mWiFiList);
}
private void printList(List<ScanResult> list){
for(ScanResult result: list){
int level = WifiManager.calculateSignalLevel(result.level, 100);
System.out.println(result.SSID + " Level is " + level + " out of 100");
}
}
private void checkItemExists(List<ScanResult> newWiFiList, ScanResult resultNew){
int indexToRemove = -1;
if(newWiFiList.size() > 0) {
for (int i = 0; i < newWiFiList.size(); i++) {
ScanResult resultCurrent = newWiFiList.get(i);
if (resultCurrent.SSID.equals(resultNew.SSID)) {
int levelCurrent = WifiManager.calculateSignalLevel(resultCurrent.level, 100);
int levelNew = WifiManager.calculateSignalLevel(resultNew.level, 100);
if (levelNew > levelCurrent) {
indexToRemove = i;
break;
}else indexToRemove = -2;
}
}
if(indexToRemove > -1){
newWiFiList.remove(indexToRemove);
newWiFiList.add(indexToRemove,resultNew);
}else if(indexToRemove == -1)newWiFiList.add(resultNew);
} else newWiFiList.add(resultNew);
}
private void setAdapter(List<ScanResult> list) {
listAdapter = new WifiListAdapter(getActivity().getApplicationContext(), list);
wifiListView.setAdapter(listAdapter);
}

setLocationListener not working in Blackberry gps programming

I am working on gps based application. I am using LocationProvider and calling setlocationListener through it code is like
LocationProvider lp = LocationProvider.getInstance(null);
if (lp != null) {
lp.setLocationListener(new LocationListenerImpl(), 2, 1, 1);
} else {
Dialog.alert("GPS NOT SUPPORTED!");
retval = false;
}
} catch (LocationException e) {
System.out.println("GPS 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();
System.out.println("Current latitude:"+latitude);
System.out.println("Current longitude:"+longitude);
System.out.println("Current speed:"+speed);
// 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();
}
}
it doesnt give an error but dont even work out so help with the same.the control dont get transferred to LocationListenerImpl()...
I am using BlackBerry_JDE_PluginFull_1.0.0.67 with eclipse-java-galileo-SR1-win32 on Blackberry 8800 simulator..
Any assistence is grately appreciated....
Thanking you in advance.
try this:
lp.setLocationListener(new LocationListenerImpl(), 2, -1, -1);
Acc to me
u set 2,1,1 which means that time interval is 2 sec after which location updation will be automatically called
1 sec indicates time out
1 sec indicates max age
ur gps times out before going ahead for gps location update method.so try it with setting it to default value = -1
You have to enable the GPS in the simulator, is it enabled when you try?
If you're getting a NullPointerException then you should check in the OS Options that the GPS has Location activated.

Resources