ello, i am trying to code the following function:
private int GetTwoLocationsAndDistance(Location location1, Location location2) {
if (location1 == null) {
location1 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
location 2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
else {
location1 = location2;
location2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
return int Distance;
}
(both location1 and location2 are initalized as null)
here, an error message comes up saying that a permission might need to happen.
but i already asked for permission onCreate(); with
eif (pm.checkPermission(permission.ACCESS_FINE_LOCATION, getPackageName()) == PackageManager.PERMISSION_DENIED) {
alertboxGPS();
}
(alertboxGPS is a box that pops up when permission is denied)
how do i fix this error?
The user can deny you the permission, that's why android studio suggests that you need to check if it's granted.
You can ensure that your app has the permission by adding this line in the manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Or continue with the request/check permission method, however, let the user retry if the permission is not granted but is crucial.
Related
So I have the following error:
√ Built build\app\outputs\flutter-apk\app-debug.apk.
D/FlutterLocationService( 6191): Creating service.
D/FlutterLocationService( 6191): Binding to location service.
Lost connection to device.
I also don't know why it says D/FlutterLocationService, instead of D/FlutterGeolocator.
I heard you now need to manually ask for permission, but have zero clue how to do that. How should I add the code for Geolocator permissions to this code?
AppStateProvider() {
_saveDeviceToken();
FirebaseMessaging.onMessage;
FirebaseMessaging.onMessageOpenedApp;
_setCustomMapPin();
_getUserLocation();
_listemToDrivers();
Geolocator.getPositionStream().listen(_updatePosition);
}
// ANCHOR: MAPS & LOCATION METHODS
_updatePosition(Position newPosition) {
position = newPosition;
notifyListeners();
}
Future<Position> _getUserLocation() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
position = await Geolocator.getCurrentPosition();
List<Placemark> placemark =
await placemarkFromCoordinates(position.latitude, position.longitude);
you simply add permission request before you get user location
so inside the _getUserLocation() and before
position = await Geolocator.getCurrentPosition();
add below code.
final permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
And you can probably check https://pub.dev/packages/geolocator as well
As i am using MapBox in my application .i don't know how to get the current position to open Navigation_MapBox for start navigation with the current position as origin to the destination .thanks
Use geolcator library
add it to pubspec yaml file
import it
import 'package:geolocator/geolocator.dart';
then
Position position = await Geolocator().getLastKnownPosition(desiredAccuracy: LocationAccuracy.high);
print("my location is ${position.latitude} ${position.longitude} ");
To get user location you need to run this
import 'package:geolocator/geolocator.dart';
/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> _determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
return await Geolocator.getCurrentPosition();
}
I have a problem with setting current location with GPS.
It works like it should(notification about finding location, then set it properly) on Android 5.0.1(Xiaomi Redmi Note 3)
But for example on Android 6.0 (Sony Xperia Z5 Compact) it doesn't work at all. No notification, GPS position set never. On Xperia I even don't have button on the right of map which is showed by line in code(mMap.setMyLocationEnabled(true);)
On Android 4.4.2(Gigabyte GsMart Roma R2plus) also no notification comes up, but I can see button of current location on right on top of screen. But still doesn't work like it should.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
}
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
emailicek = user.getEmail();
emailicek = emailicek.replace(".", "");
mDatabase = FirebaseDatabase.getInstance().getReference();
if (latitude != 0) {
if (longitude != 0) {
mDatabase.child("userdata/" + email + "/latitude").setValue(latitude);
mDatabase.child("userdata/" + email + "/longitude").setValue(longitude);
}
}
LatLng latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
if (latitude != 0) {
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
} else {
mMap.animateCamera(CameraUpdateFactory.zoomTo(1));
}
}
Did you make sure you requested the right permissions in the Manifest?
to get the last known location you'll need
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
for network based location, or:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
for GPS based location.
By the way there are a lot of good reasons why you should consider moving to Play Services to get your location, I strongly suggest you to read this:
Getting the Last Known Location - Android Developers
This is not working:
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
After this code, it goes to catch statement.
Another issue is that the solving statement is giving me error. A red line under it.
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Hint for the above error is that in the Android Studio:
Call requires permission which may be rejected by user: code should
explicitly check to see if permission is available (with
checkPermission) or explicitly handle a potential
SecurityException
This is my whole code to get gps coordinates from Android phone.
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
Toast.makeText(getApplicationContext(), "1111", Toast.LENGTH_LONG).show();
// no network provider is enabled
} else {
this.canGetLocation = true;
Toast.makeText(getApplicationContext(), "2222", Toast.LENGTH_LONG).show();
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
In according to Requesting Permission :
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.
There are 2 difference:
System permissions are divided into two categories, normal and dangerous:
Normal permissions do not directly risk the user's privacy. If your app lists a normal permission in its manifest, the system grants the permission automatically.
Dangerous permissions can give the app access to the user's confidential data. If your app lists a normal permission in its manifest, the system grants the permission automatically. If you list a dangerous permission, the user has to explicitly give approval to your app.
So if you are using API 23 you must check explicit permission if you would access to location service so add this:
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
//DO OP WITH LOCATION SERVICE
}
I suggest you to check also if app is running on device with API >= 23 with this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
//DO CHECK PERMISSION
}
You should add following line to your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
please include your manifest code too ,have you added those permissions ?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
My code is taking coordinates of a position at one given time, and then displaying Lat/Long coordinates. I think my code is right, but where the problem lies is giving GPS permission to the phone. I am using a Samsung Nexus S, and I have all proper drivers installed, but there is no network on the phone. I was told that GPS should still work and should be able to retrieve coordinates. I have the, "Use GPS Satellites" setting enabled, and have given the permission in the manifest, as seen here in the manifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"></uses-permission>
I threw in all possible location permissions just in case I was missing something, hopefully that isn't a problem.
As for my code I have this in the onCreate method (class? I'm not sure of its proper name)
double[] gps = getGPS();
TextView tv = (TextView) this.findViewById(R.id.gpsCoordinates);
tv.setText("Latitude: " + gps[0] + "\nLongitude: " + gps[1]);
And then a private method in the GPS class to actually get the coordinates
private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
I believe I pulled this code off of stackoverflow and a few other forums and then tweaked it a bit.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.LOCATION"></uses-permission>
Add above permissions.May be this will help you.
You need to put the following permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
Ref:
http://developer.android.com/reference/android/Manifest.permission.html#ACCESS_FINE_LOCATION