How to get user position by GPS in Sencha - android

I'm trying to get user position in Sencha Touch 2:
var geo = new Ext.util.Geolocation({
autoUpdate: true,
allowHighAccuracy: true,
listeners: {
locationupdate: function(geo) {
lat = geo.getLatitude();
lon = geo.getLongitude();
// here comes processing the coordinates
}
}
});
But I've got coordinates only from network. There's no GPS icon on Android device, pointing that I'm using GPS. Also it doesn't work when I turn off internet connection. How can I enable GPS positioning? In Manifest file GPS is enabled.

I just got bit by this too.
It turns out there's a bug in Sencha: in Ext.util.Geolocation.parseOption they name the parameter allowHighAccuracy but the w3c specs name it enableHighAccuracy.
I added the following code to my application init to fix that:
var parseOptions = function() {
var timeout = this.getTimeout(),
ret = {
maximumAge: this.getMaximumAge(),
// Originally spells *allowHighAccurancy*
enableHighAccuracy: this.getAllowHighAccuracy()
};
//Google doesn't like Infinity
if (timeout !== Infinity) {
ret.timeout = timeout;
}
return ret;
};
Ext.util.Geolocation.override('parseOptions', parseOptions);
For the record: the bug has been reported over a year ago, and the fix was applied for TOUCH-2804 in a recent build. I don't know what that means, but sure enough the bug is still in 2.0
EDIT: using the approach mentioned above doesn't work well either. The GPS icon would turn on and off as Exts calls getCurrentPosition repeatedly using a setInterval. The reason for doing this is that The native watchPosition method is currently broken in iOS5. In my Android targeted application I ended up ditching Ext:util.Geolocation and directely used navigator.geolocation.watchPosition. After that it worked like a charm.

GPS location provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix.
Requires the permission android.permission.ACCESS_FINE_LOCATION.

Hey I think you need updated longitude and latitude values .
follow this link.. Click Here
I already tried it and test it in android mobile phone.. Its working.
Note : Must and should test in android mobile phone with on GPS status. It will not show on eclipse emulator. But it will show in mobile phone try it..
have a nice.

Related

Avoiding Google's prompt when trying to get location

I am developing a simple app using Flutter's location plugin, with some code based on their sample code:
var location = new Location();
try {
_currentLocation = await location.getLocation();
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
_locationMsg = 'Permission denied';
}
_currentLocation = null;
}
As indicated in the plugin page, I added ACCESS_FINE_LOCATION to the Android manifest.
The problem is, when I test the app on a phone (with Android 9, in case it's relevant), even though location is enabled and I have a GPS signal, executing the above code results in the following prompt:
The prompt reads: "For a better experience, turn on device location, which uses Google's location service.", with two buttons: "NO THANKS" and "OK".
This is horribly user-unfriendly: location is already coming from the GPS, there is no need to further bother the user.
Where is the problem coming from, and how can I avoid that prompt? I prefer reporting "unknown location" than having the prompt displayed.
Edit: Note that the prompt is not related to notifying the user that the location will be used, but it is a Google privacy-invading feature that, when you click OK, enables Google Location Accuracy, as described below (hidden deep in a Settings menu):
The above image reads: "Improve Location Accuracy", with a toggle button. Google Location Accuracy: Google’s location service improves location accuracy by using Wi‑Fi and mobile networks to help estimate your location. Anonymous location data will be sent to Google when your device is on.
Clicking on the first prompt enables this, which the user then has to manually disable if they don't want to send their location data to Google. Disabling it and trying to get the location again results in the same prompt, so it is definitely not related to warning the user about the usage of location data. Also, if Google Location Accuracy is enabled before using the app, the prompt never appears in the first place, which is probably why most developers never notice it.
I know it is possible to get location data without enabling Google Location Accuracy, since most apps do it. But I don't know where the prompt comes from: is it Flutter's location plugin? The fact that I am using an Android 9 SDK? Or the sample code?
It seems the issue is coming from the location plugin. I tried replacing it with geolocator, and modifying the caller code, and this time no such prompt appears.
I tried lowering the accuracy before asking for location, but the location plugin still displays the prompt. There must be some underlying code which is hardwired to request Google Location Accuracy in all cases.
If only Google would provide a way to permanently disable the prompt with a systematic
"no" (this has been an issue for several Android releases), I might have given them the benefit of doubt.
I was having this same issue today but solved it by locating the offending expression and added an if statement to check whether the app's location permission was granted.
Here is my code in Kotlin and the offending expression is under the note in all caps:
private fun checkLocationPermission() : Boolean = (ContextCompat.checkSelfPermission(
requireContext(), ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
private fun startLocationRequests() {
val locationRequest = LocationRequest.create()?.apply {
interval = 10000
fastestInterval = 5000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest!!)
val client: SettingsClient = LocationServices.getSettingsClient(requireActivity())
val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build())
task.addOnSuccessListener { locationSettingsResponse ->
// All location settings are satisfied. The client can initialize
// location requests here.
// ...
if (checkLocationPermission()) {
locationPermissionGranted = true
fusedLocationProviderClient.requestLocationUpdates(
locationRequest, locationCallback, Looper.getMainLooper())
}
}
task.addOnFailureListener { exception ->
if (exception is ResolvableApiException){
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
// IF STATEMENT THAT PREVENTS THE DIALOG FROM PROMPTING.
if (checkLocationPermission()) {
exception.startResolutionForResult(
requireActivity(),
REQUEST_CHECK_SETTINGS
)
}
} catch (sendEx: IntentSender.SendIntentException) {
// Ignore the error.
}
}
Timber.i("Location Listener failed")
}
}
Now my solution may not exactly apply to your problem but I think it should be enough to learn from to solve your problem. However, you may need to redo your code when it comes to requesting a user's location, though.
Also, I'm not so sure about using Flutter's plugin for location but in your case and others, I would recommend following the developer documentation when it comes to requesting a user's location. Perhaps it's applicable to Flutter too:
https://developer.android.com/training/location/change-location-settings

Detecting Mock Location Not Working (Android)

I'm trying to set some protection against people using mock locations to manipulate my app. I realise that it's impossible to prevent 100%... I'm just trying to do what I can.
The app uses Google location services (part of play services) in its main activity.
The onLocationChanged() method is:
public void onLocationChanged(Location location) {
this.mCurrentLocation = location;
if (Build.VERSION.SDK_INT > 17 && mCurrentLocation.isFromMockProvider()) {
Log.i(TAG, "QQ Location is MOCK");
// TODO: add code to stop app
// otherwise, currently, location will never be updated and app will never start
} else {
Double LAT = mCurrentLocation.getLatitude();
Double LON = mCurrentLocation.getLongitude();
if ((LAT.doubleValue() > 33.309171) || (LAT.doubleValue() < 33.226442) || (LON.doubleValue() < -90.790165) || (LON.doubleValue() > -90.707081)) {
buildAlertMessageOutOfBounds();
} else if (waiting4FirstLocationUpdate) {
Log.i(TAG, "YYY onLocationChanged() determines this is the FIRST update.");
waiting4FirstLocationUpdate = false;
setContentView(R.layout.activity_main);
startDisplayingLists();
}
}
}
The location services work perfectly and all is well with the app in general, but when I run the app in an emulator with Android Studio (Nexus One API 23), and I set the location using extended controls (mock), the app just continues to work as normal, and so it seems that the condition:
if (Build.VERSION.SDK_INT > 17 && mCurrentLocation.isFromMockProvider())
Is returning false.
This doesn't make any sense to me. Does anyone know why this would happen?
Thanks!
The short answer: .isFromMockProvider is unreliable. Some fake locations are not properly detected as such.
I have spent an extensive amount of time researching this and written a detailed blog post about it.
I also spent time to find a solution to reliably suppress mock locations across all recent/relevant Android versions and made a utility class, called the LocationAssistant, that does the job.
In a nutshell (using the aforementioned LocationAssistant):
Set up permissions in your manifest and Google Play Services in your gradle file.
Copy the file LocationAssistant.java to your project.
In the onCreate() method of your Activity, instantiate a LocationAssistant with the desired parameters. For example, to receive high-accuracy location updates roughly every 5 seconds and reject mock locations, call new LocationAssistant(this, this, LocationAssistant.Accuracy.HIGH, 5000, false). The last argument specifies that mock locations shouldn't be allowed.
Start/stop the assistant with your Activity and notify it of permission/location settings changes (see the documentation for details).
Enjoy location updates in onNewLocationAvailable(Location location). If you chose to reject mock locations, the callback is only invoked with non-mock locations.
There are some more methods to implement, but essentially this is it. Obviously, there are some ways to get around mock provider detection with rooted devices, but on stock, non-rooted devices the rejection should work reliably.

How to get only gps location using sencha touch?

I have created sencha touch application and i want to try get the current location of android device using below code.
Ext.create('Ext.util.Geolocation',
autoUpdate: true,
allowHighAccuracy: true,
listeners: {
locationupdate: function(geo) {
latitude=geo.position.coords.latitude;
longitude=geo.position.coords.longitude;
if(Global.currentUserPositionMarker)
{
latlng1=new google.maps.LatLng(latitude, longitude);
currentPosMarker.setPosition(latlng1);
}
}
}
});
In my device the gps icon will be blinking but Couldn't get the current location of device gps position.
It always get current location from my network provider.
I want frequently update current location from the device gps possition.
Like the google map app for android the gps icon is always stable, i want to like that in my application.
start your Device WI-FI and then try to load your app.
Because It will work for me to get the current location from gps.
I have face the same problem to get the current location from gps.
I am also add question for releated these problem See The Question.
Add Frequency parameter in GeoLocation object.
Ext.create('Ext.util.Geolocation',
autoUpdate: true,
frequency:1000,
allowHighAccuracy: true,
listeners: {
locationupdate: function(geo) {
latitude=geo.position.coords.latitude;
longitude=geo.position.coords.longitude;
if(Global.currentUserPositionMarker)
{
latlng1=new google.maps.LatLng(latitude, longitude);
currentPosMarker.setPosition(latlng1);
}
}
}
});
Frequency value is in milliseconds and it is used to update Geo location by given time.

Flex mobile: remove GeolocationEvent.UPDATE does not work

I can't seem to remove the listener for the update event for geolocation on Android.
I wanna stop the Geolocation on deactivate:
NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, onAppDeactivate);
private function onAppDeactivate(e:Event):void {
if (Geolocation.isSupported) {
if (geolocation != null) {
geolocation.removeEventListener(GeolocationEvent.UPDATE, onGeolocationUpdate);
geolocation.setRequestedUpdateInterval(0);
geolocation = null;
}
}
}
I started with just removing the listener, but since that didn't work I also tried removing the geolocation all together. Still no luck..
Any hints?
I had an app that uses Geolocation too, and if what you want is to save the battery from draining fast, you have to call the geolocation.setRequestedUpdateInterval(INTERVAL_MILLIS) method with a high value for INTERVAL_MILLIS (in my case i use 60000 that is 1 min).
But as the (documentation) says, the OS will decide the update interval for the GPS, ant the value we pass serves a a "hint" to the update interval.
And specifically on Android, the GPS icon will stay on as long as you have the GPS enabled (and it will consume power) but will no drain you battery fast as the update interval will be high.
So the best thing you can do is actually request a large update interval when you app deactivates.

Send GPS coordinates to Android emulator using DDMS, telnet or any other means

DDMS is not able to send location to the emulator. I have tried sending just the location from DDMS but still the emulator is not able to receive location. Nothing appears on the DDMS log when I click the Send button.
I tried sending geo fix from telnet which returns OK but doesn't actually update the location, or if it does I can't read it via my application.
The application works properly in the device, is able to capture test location details but not able to capture location data sent to the emulator either via DDMS or telnet.
I am testing on Android 2.2 emulator. Can anyone let me know what is wrong?
My app (below) is written in C# using Mono for Android and may need fixing (I'm a newbie to all things Android so I could have missed something). OnLocationChanged(Location location) just doesn't seem to fire at all, as if the listener isn't properly defined. Any help appreciated.
Note: The first time I run this Activity the LocationManager.GetLastKnownLocation is null but the test provider stuff isn't accessed. When I run it again GetLastKnowLocation is still null but the test provider stuff is accessed and set. Weird.
[Activity(Label = "Location Demo")]
public class LocationActivity : Activity, ILocationListener
{
private TextView _locationText;
private LocationManager _locationManager;
private StringBuilder _builder;
private Geocoder _geocoder;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.LocationActivity);
_geocoder = new Geocoder(this);
_locationText = FindViewById<TextView>(Resource.Id.TextView1);
_locationManager = (LocationManager)GetSystemService(LocationService);
if (_locationManager.GetLastKnownLocation("gps") == null)
{
_locationManager.AddTestProvider("gps", false, false, false, false, false, false, false, 0, 5);
_locationManager.SetTestProviderEnabled("gps", true);
Location loc = new Location("gps");
loc.Latitude = 50;
loc.Longitude = 50;
_locationManager.SetTestProviderLocation("gps", loc);
}
Location lastKnownLocation = _locationManager.GetLastKnownLocation("gps");
if (lastKnownLocation != null)
{
_locationText.Text += string.Format("Last known location, lat: {0}, long: {1}", lastKnownLocation.Latitude, lastKnownLocation.Longitude);
}
else
{
_locationText.Text += string.Format("Last location unknown");
}
_locationManager.RequestLocationUpdates("gps", 5000, 2, this);
}
public void OnLocationChanged(Location location)
{
_locationText.Text += string.Format("Location updated, lat: {0}, long: {1}", location.Latitude, location.Longitude);
}
public void OnProviderDisabled(string provider){}
public void OnProviderEnabled(string provider){}
public void OnStatusChanged(string provider, Android.Locations.Availability availability, Bundle extras){}
}
Kudos to https://stackoverflow.com/users/170333/greg-shackles for getting me this far.
I think the problem may be with how you're calling RequestLocationUpdates(). That third parameter is the minimum distance the device needs to move before you get updates, so you're telling the system to only send updates after the device has moved 2 meters. If it works on a real device, it's probably because you moved more than 6 feet. :)
Try starting with RequestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this). That will start a stream of updates on a real device, but only one when you press 'Send' in DDMS. Once that works, I would work back from there on how often you get updates.
Also, GetLastKnownLocation() is always null when you start the emulator. It's better for devices since it can send you the network location as a starting estimate, or the GPS location if another program was using it recently.
EDIT
It could also be a permissions issue. Normally you need to alter AndroidManifest.xml to get GPS access. The line is
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
See the docs here.
Call
_locationManager.RequestLocationUpdates("gps", 5000, 2, this);
function before doing any location operations, like below:
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.LocationActivity);
_geocoder = new Geocoder(this);
_locationText = FindViewById<TextView>(Resource.Id.TextView1);
_locationManager = (LocationManager)GetSystemService(LocationService);
_locationManager.RequestLocationUpdates("gps", 5000, 2, this); //this will cause updated location to be retrieved from telnet
Note: Its normal that program works after the first run, so that after the first run your application could get the initial updated location from telnet and that will be enough to not throws an exception
Finally resolved this. When the emulator is launched by VS2010 (i.e. F5, start debugging) it does not behave as expected. Launch the emulator externally using AVD.exe, start a virtual device and deploy the app. to it (using F5, start debugging) and everything works fine.
Why starting the emulator from within or outside VS2010 should make any difference is a mystery I am able to live with. Thanks to everyone for their helpful suggestions.
Does your emulated android image have GPS hardware? The description in the emulator should have "hw.gps=yes".
I had the same symptoms before recreating a new image with the right (emulated) hardware. I found a simple web page that displays the current location was handy when debugging the emulation environment.

Categories

Resources