I want to get location from GPS provider and network provider. I wrote below code and works correct in android below 6 and i checked in android 4.2 and everything is correct but when i checked in android 8 till GPS is on, everything is worked and i get location by network or GPS. but when GPS is off, i can't get location by Network provider. What is my problem and How can i solved this? Do on API 23+, needs enable GPS for get location? Do i need enable an option in settings of my device?
public void createLocation(){
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
gpsLocListener = new MyLocationListener();
networkLocListener = new MyLocationListener();
}
...
public static void checkLocation() {
if (Build.VERSION.SDK_INT >= 23) {
if ((ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) && ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, networkLocListener);
}
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, networkLocListener);
}
if (!FIND_LOC_ByY_GPS) {
if (Build.VERSION.SDK_INT >= 23) {
if ((ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)&& ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocListener); }
} else {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocListener); }
//locationManager.requestLocationUpdates(locationManager.PASSIVE_PROVIDER,0,0,passiveLocListener);
}
}
public static class MyLocationListener implements LocationListener {
public MyLocationListener() {
}
#Override
public void onLocationChanged(Location location) {
if (location != null && !callLocationUpdate) {
//Speed
//if (calculateSpeedUser(location) < 13.8889) {
try {
removeLocationUpdate();
callLocationUpdate = true;
if (DEBUG_BASEACTIVITY)
Log.e("GPS Location Changed!", "onLocationChanged/BaseActivity");
} catch (SecurityException e) {
Log.e("PERMISSION_EXCEPTION", "PERMISSION_NOT_GRANTED");
}
//}
get_location_by_LocationUpdate_method = true;
doLocationUpdate(location, true);
getByLocationUpdate = true;
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Related
I'm using this What is the simplest and most robust way to get the user's current location on Android? to get my current location and list nearby restaurants when i click on swith button.It works before i remove the app and install it again.
this is my implementation of gotLocation method
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
MyLocationManager.LocationResult locationResult= new MyLocationManager.LocationResult() {
#Override
public void gotLocation(final Location location) {
//Got the location!
currentLocation = location;
browseNearbyBusinessesList(currentLocation);
}
};
MyLocationManager myLocationManager = new MyLocationManager();
myLocationManager.getLocation(getBaseContext(), locationResult);
}else {
searchDefaultList();
}
}
});
I got not null LocationResult Object but the gotLocation method was not executed . Can any one tell me where is exactly the problem please?
this is the code of MyLocationManager Class
public class MyLocationManager {
public LocationResult locationResult;
public Context context;
Timer timer1;
LocationManager lm;
boolean gps_enabled = false;
boolean network_enabled = false;
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private boolean isPermessed = false;
public MyLocationManager() {
}
public MyLocationManager(boolean isPermessed) {
this.isPermessed = isPermessed;
}
public boolean getLocation(Context context, LocationResult result) {
//I use LocationResult callback class to pass location value from MyLocation to user code.
this.context = context;
locationResult = result;
if (lm == null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
//don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
isPermessed = false;
return false;
} else {
isPermessed = true;
}
if (isPermessed)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if (network_enabled) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
isPermessed = false;
return false;
} else {
isPermessed = true;
}
if (isPermessed)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
}
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 4000);
return true;
}
public static abstract class LocationResult {
public abstract void gotLocation(final Location location);
}
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
isPermessed = false;
return;
} else {
isPermessed = true;
}
if (isPermessed)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if (network_enabled) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
isPermessed = false;
return;
} else {
isPermessed = true;
}
if (isPermessed)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
System.out.println(isPermessed);
//if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
}
The problem was isPermissed returns always false. I created a method getLocationPermissions() to grant permissions.
private final static String FINE_LOCATION= Manifest.permission.ACCESS_FINE_LOCATION;
private final static String COARSE_LOCATION= Manifest.permission.ACCESS_COARSE_LOCATION;
private final static int LOCATION_PERMISSION_REQUEST_CODE=1234;
--------------------------------------
if (gps_enabled) {
getLocationPermission();
if (((ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) && (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED))) {
isPermessed = true;
Log.i("isPermessed = ", isPermessed+"");
} else {
isPermessed = false;
Log.i("isPermessed = ", isPermessed+"");
return false;
}
--------------------------------------
private void getLocationPermission() {
String[] permissions = {android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(context,
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(context,
COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
} else {
ActivityCompat.requestPermissions((Activity) context,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions((Activity) context,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
With this code I'm trying to get get the location this code only works the first time I execute the emulator the Ihave to close the emulator in order to work again ,and it doesn't launch any error
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
myContext = this;
position =(TextView)findViewById(R.id.position);
locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(android.location.Location location) {
double latitude=location.getLatitude();
double longitude=location.getLongitude();
position.setText("lat:"+latitude+" lon:"+longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
101);
}
else{
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
}
else{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0, locationListener);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
try {
switch (requestCode) {
case 101: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
}
return;
}
}
}
catch(SecurityException err_permission) {
}
}
}
and this permision on manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
But the position is not shown on the textview, I think I don't missed anything,Do I?Maybe coarse_location permission ?I don'k know what is wrong on this code it has the locationmanager and the listener, and aks form permission...
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
}
else{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0, locationListener);
}
If you have the location you are not starting periodic updates, you may be looking for this:
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0, locationListener);
if(location != null){
//Do things with the first location
}
So you start with something and keep updating with the listener
If there is a last known location from locationManager.getLastKnownLocation then you don't request location updates.
Hey I am trying to get a phone location using GPS and I tried this code but it doesn't show anything (I am running it on the simulator and changing the location there) but it seems that it doesn't even enter the location change method..
Here is the activity code:
private BroadcastReceiver broadcastReceiver;
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver==null)
{
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(),"cor",Toast.LENGTH_LONG).show();
// Log.d("cors:",""+intent.getExtras().get("cordinates"));
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
#Override
protected void onDestroy() {
super.onDestroy();
if(broadcastReceiver!=null)
unregisterReceiver(broadcastReceiver);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Log.d("oncraet","oncreate");
setSize();
if(!runtime_permissions())
{
enable_buttons();
}
}
private boolean runtime_permissions() {
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}
,100);
return true;
}
return false;
}
public void enable_buttons()
{
Intent i =new Intent(getApplicationContext(), GPS_Service.class);
startService(i);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
enable_buttons();
} else {
runtime_permissions();
}
}
}
and here is the Service class code:
public class GPS_Service extends Service {
private LocationListener listener;
private LocationManager locationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("coordinates",location.getLongitude()+" "+location.getLatitude());
sendBroadcast(i);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//noinspection MissingPermission
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);
}
#Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
//noinspection MissingPermission
locationManager.removeUpdates(listener);
}
}
}
the manifest is all good..
what is the problem? and how can I make the app get the first location without it has to move first?
look at my example here
private LocationManager locationManager;
private double lastKnownStartLatitude, lastKnownStartLongtitude;
locationManager = (LocationManager) getSystemService(serviceString);
String serviceString = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(serviceString);
String provider = LocationManager.GPS_PROVIDER;
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) {
return;
}
// if lastKnownLocation is not null
lastKnownLocation = locationManager.getLastKnownLocation(provider);
if (lastKnownLocation != null) {
lastKnownStartLatitude = lastKnownLocation.getLatitude();
lastKnownStartLongtitude = lastKnownLocation.getLongitude();
}
// if lastKnownLocation is null
LocationListener myLocationListener = new LocationListener() {
public void onLocationChanged(Location locationListener) {
Location location;
// using gps
if (isGPSEnabled(YourClassName.this)) {
if (locationListener != null) {
if (ActivityCompat.checkSelfPermission(YourClassName.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(TestWithLocationListener.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
System.out.println("Hello isGPSEnabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
} else if (isInternetConnected(TestWithLocationListener.this)) {
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
Hope this helps
Try to use Google's fused location provider API as it is now the new best practice to fetch location.
You get updates for best location available from all sources according to your location request.
This tutorial on developer's site is really good.
I am creating a map application, which gets location from GPS, i'm finding location from requestLocationUpdates(), but i'm not getting any response from GPS provider, however when i'am using network provider i'am getting location, can anyone help where i'm wrong,
Also i'am new to android app development, so i'll appreciate any tips to optimize my code(make more efficient with less mess),
Here's my code :
public void trackLocation(){
if (ContextCompat.checkSelfPermission(activity.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
boolean flag;
Boolean dlg;
flag = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (flag) {
Log.v("function", "onClick");
myLocationListener = new MyLocationListener();
dlg = true;
} else {
dlg = gpsDialog();
progressBar.setVisibility(View.GONE);
}
Log.d("maps", "Requesting location updates");
if(dlg) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLocationListener);
}
}
}
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Log.d("maps", "on location changed : "+location.getLatitude() + "---"+ location.getLongitude());
locationManager.removeUpdates(myLocationListener);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Log.d("maps" , "Status Changed");
}
#Override
public void onProviderEnabled(String s) {
Log.d("maps" , "Provider Enabled");
}
#Override
public void onProviderDisabled(String s) {
Log.d("maps" , "Provider Disabled");
}
}
public Boolean gpsDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("Do you want to start GPS?")
.setCancelable(false)
.setTitle("GPS DISABLED")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
activity.startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
progressBar.setVisibility(View.GONE);
return false;
}
Google maps uses user's lastKnownLocation for location, If the lastknownLocation is unknown it takes time to fetch location through different provider say GPS or Network, whichever is easy. I would suggest to use lastKnownLocation as base location and update it with LocationListener. It is most optimized way of processing location.
if (ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
}
else {
// enable location buttons
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// fetch last location if any from provider - GPS.
final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
final Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//if last known location is not available
if (loc == null) {
final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
// getting location of user
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
//do something with Lat and Lng
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
//when user enables the GPS setting, this method is triggered.
}
#Override
public void onProviderDisabled(String provider) {
//when no provider is available in this case GPS provider, trigger your gpsDialog here.
}
};
//update location every 10sec in 500m radius with both provider GPS and Network.
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10*1000, 500, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 500, locationListener);
}
else {
//do something with last known location.
// getting location of user
final double latitude = loc.getLatitude();
final double longitude = loc.getLongitude();
}
}
Permission handling:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults[0] != PackageManager.PERMISSION_GRANTED){
//do something
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Your code is correct. GPS usually doesn't give you any info within the building, if you try to test the app outside, you will get the results.
firstly check gps_enabled return true or not.
LocationManager lm = (LocationManager) mCtx
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
By this code you get accurate lat , long
Location net_loc = null, gps_loc = null, finalLoc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gps_loc != null && net_loc != null) {
if (gps_loc.getAccuracy() >= net_loc.getAccuracy())
finalLoc = gps_loc;
else
finalLoc = net_loc;
// I used this just to get an idea (if both avail, its upto you which you want to take as I taken location with more accuracy)
} else {
if (gps_loc != null) {
finalLoc = net_loc;
} else if (net_loc != null) {
finalLoc = gps_loc;
}
}
i want to use GPS in my App. but when i tried to retrieve GPS readings as shown belwo in the code, Android studio gave me the belwo mentioned error
despit all the required permissions are added to manifest file
code:
LocationManager lm = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.w(TAG, "onLocationChanged");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.w(TAG, "onStatusChanged");
}
#Override
public void onProviderEnabled(String provider) {
Log.w(TAG, "onProviderEnabled");
}
#Override
public void onProviderDisabled(String provider) {
Log.w(TAG, "onProviderDisabled");
}
};
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll);//error at this line
This is due to in Marshmallow (Android version 6.0) Users can choose to turn off permissions. Simply wrap this check to see if the permission is enabled before your location code.
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
}
You should also write in an else statement request code which will request the permission from the user if they haven't got it.
Here's a nice request permissions method:
public void requestPermissions(List<String> permissions, ActivityCompat.OnRequestPermissionsResultCallback onRequestPermissionsResultCallback) {
String[] params = permissions.toArray(new String[permissions.size()]);
requestPermissions(params, onRequestPermissionsResultCallback);
}
In your case you will have to pass it the Location permissions which you can get with this method:
private List<String> getRequiredLocationPermissions() {
String accessCoarsePermission = android.Manifest.permission.ACCESS_COARSE_LOCATION;
String accessFineLocationPermission = android.Manifest.permission.ACCESS_FINE_LOCATION;
int hasCoarsePermission = ContextCompat.checkSelfPermission(getActivity(), accessCoarsePermission);
int hasFineLocationPermission = ContextCompat.checkSelfPermission(getActivity(), accessFineLocationPermission);
List<String> permissions = new ArrayList<>();
if (hasCoarsePermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(accessCoarsePermission);
}
if (hasFineLocationPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(accessFineLocationPermission);
}
return permissions;
}