Call requires permissions that may be rejected by user - android

I am trying to make an application that sends location updates of a user after every five minutes. I suppose my code is working just fine but i get an error regarding the permissions that are being used by the application. I am pretty sure that i have added the permissions in the manifest file. Can someone tell me what's wrong? Here is my code.
MainActivity.java
LocationManager locationManager ;
String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting LocationManager object
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider,5*60*1000,0,this);
if(location!=null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// Getting reference to TextView tv_longitude
TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);
// Getting reference to TextView tv_latitude
TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);
// Setting Current Longitude
tvLongitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
tvLatitude.setText("Latitude:" + location.getLatitude() );
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
I am getting an error as Call requires permission which may be rejected by user in these lines-
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider,5*60*1000,0,this);
My AndroidManifest is like this
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

Which SDK do you use?
If you use Marshmallow, then you need to check that the user has granted permission for every location call.
Take a look Here.
You should do something like this:
if (ContextCompat.checkSelfPermission( this,android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED )
{
ActivityCompat.requestPermissions(
this,
new String [] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
LocationService.MY_PERMISSION_ACCESS_COURSE_LOCATION
);
}
request permission if you dont have it already.
check the link above for more info.

Try my code:
public class MainActivity extends AppCompatActivity {
/* GPS Constant Permission */
private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 12;
/* Position */
private static final int MINIMUM_TIME = 10000; // 10s
private static final int MINIMUM_DISTANCE = 50; // 50m
/* GPS */
private String mProviderName;
private LocationManager mLocationManager;
private LocationListener mLocationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Get the best provider between gps, network and passive
Criteria criteria = new Criteria();
mProviderName = mLocationManager.getBestProvider(criteria, true);
// API 23: we have to check if ACCESS_FINE_LOCATION and/or ACCESS_COARSE_LOCATION permission are granted
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// No one provider activated: prompt GPS
if (mProviderName == null || mProviderName.equals("")) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
// At least one provider activated. Get the coordinates
switch (mProviderName) {
case "passive":
mLocationManager.requestLocationUpdates(mProviderName, MINIMUM_TIME, MINIMUM_DISTANCE, this);
Location location = mLocationManager.getLastKnownLocation(mProviderName);
break;
case "network":
break;
case "gps":
break;
}
// One or both permissions are denied.
} else {
// The ACCESS_COARSE_LOCATION is denied, then I request it and manage the result in
// onRequestPermissionsResult() using the constant MY_PERMISSION_ACCESS_FINE_LOCATION
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSION_ACCESS_COARSE_LOCATION);
}
// The ACCESS_FINE_LOCATION is denied, then I request it and manage the result in
// onRequestPermissionsResult() using the constant MY_PERMISSION_ACCESS_FINE_LOCATION
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this,
new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
MY_PERMISSION_ACCESS_FINE_LOCATION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_ACCESS_COARSE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
} else {
// permission denied
}
break;
case MY_PERMISSION_ACCESS_FINE_LOCATION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
} else {
// permission denied
}
break;
}
}
}
}
Source: LINK

This worked for me
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) {
Toast.makeText(YourService.this, "First enable LOCATION ACCESS in settings.", Toast.LENGTH_LONG).show();
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, listener);

Here are the bunch of steps you need to perform to fix this
Main Activity .java
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates
(locationManager.requestLocationUpdates(provider,5*60*1000,0,this);
}//end of if
Now you also need to update your build.gradle
dependencies{
------------- //your pre-generated code
compile 'com.android.support:support-v4:23.0.1'
}
this is what Android.Developers say about it.
And don't forget to give permissions from application settings if you're using an emulator because it may not prompt for such

Related

How to gain permission to get GPS location in Android

I am new to Android and in my current project I am trying to retrieve location using GPS. The code for obtaining the location is in a separate non-activity class, because the fragment where I display the coordinates is crammed.
I have tried to use the guidelines from developer.android.com but I can't get any permission prompt, and when I press the button in the fragment, I only get the default 0-values for latitude and longitude.
I have provided the permissions in the manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
The GPS locator class:
public class LocationProvider implements ActivityCompat.OnRequestPermissionsResultCallback {
private static final int PERMISSION_REQUEST_LOCATION = 1;
private Activity activity;
Location gps_loc;
Location final_loc;
double longitude;
double latitude;
private LocationManager locationManager;
public LocationProvider(Activity activity) {
this.activity =activity;
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_LOCATION) {
// Request for permission.
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLocation();
} else {
requestLocationPermission();
}
}
}
private void getLocation() {
// Check if the permission has been granted
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (gps_loc != null) {
Log.v("Loc_provider",gps_loc.toString());
final_loc = gps_loc;
latitude = final_loc.getLatitude();
longitude = final_loc.getLongitude();
}
} else {
requestLocationPermission();
}
}
private void requestLocationPermission() {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_LOCATION);
}
public String getCoordinates() {
return latitude + " "+ longitude;
}
}
The code in the fragment:
FloatingActionButton fab=view.findViewById(R.id.floatingActionButton);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locProvider=new LocationProvider(requireActivity());
gpsCoordinates.setText(locProvider.getCoordinates());
}
});
Tips and solutions for fixing the code are most welcome.
UPDATE 1:
I moved the code in the fragment instead, so that it looks like below:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!checkIfAlreadyhavePermission()) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
gpsCoordinates.setText(getCoordinates());
}
}
});
private String getCoordinates() {
if (gps_loc != null) {
Log.v("Loc_provider", gps_loc.toString());
final_loc = gps_loc;
latitude = gps_loc.getLatitude();
longitude = gps_loc.getLongitude();
}
return latitude + " " + longitude;
}
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
return result == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Log.v("Grant_Results", String.valueOf(grantResults[0]));
Toast.makeText(getActivity(), "permission granted", Toast.LENGTH_LONG).show();
gpsCoordinates.setText(getCoordinates());
} else {
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
break;
}
}
}
I now get the permission prompt, but the location still doesn't update (I get 0).
Please note:
Saving an Activity object is not recommended this may cause memory leaks. Activity may be destroyed and recreated (for example when screen orientation changes). Holding a reference to the old activity will cause you problems.
Implementing the ActivityCompat.OnRequestPermissionsResultCallback interface does nothing. Your method will never be called. You will have to call it explicitly from the activity.
You have not requested permission, so your permission prompt will never be shown and the default value of double that is 0 will get returned. You need to call your getLocation() method so that the control falls on the else block and your permission prompt is shown
I recommend you handle permission in the activity. Have the activity get the coordinates for the location. You can have the activity implement an interface, say LocationFetcher, with a method getCoordinates(). You can then call this in the fragment like so:
LocationFetcher locationFetcher = (LocationFetcher) activity;
gpsCoordinates.setText(locationFetcher.getCoordinates());
Fixed by implementing LocationListener in Fragment and then adding
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 1, this);
in onRequestPermissionsResult().

Can't turn on location on android api23?

I have used the following code and the dialogue that asks for permission shows as expected. But when I click "allow" it doesn't do anything. The log message doesn't appear as if the permission wasn't granted so I went to my parameters to verify if location is "on" and it was "off". Wasn't it supposed to be on because I granted the app access to my location ?
If I manually turn it "on" and then run the app again, once it asks for my permission, it works and shows the log message but isn't the whole point of asking for permissions (via dialogue) to turn on location (when it's off) if the user clicks "allow" ?
Am I doing something wrong ? I should mention that I'm running the app on api23
is is the code in my Oncreate:
mApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mApiClient.connect();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
and this is my OnConnected method:
public void onConnected(#Nullable Bundle bundle) {
//start the service
//checking and asking for permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSION_ACCESS_FINE_LOCATION);
}
// 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;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mApiClient, mLocationRequest, this);
} else {
//If everything went fine lets get latitude and longitude
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Log.v("currentLatitude",currentLatitude + " WORKS " + currentLongitude + "");
}
}
try this code:
private LocationCoord gps = null;
private static final int PERMISSION_REQUEST_CODE = 1;
In OnCreate():
//GPS Manage
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Allow ImHere to access this device's location?");
dialog.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton("Deny", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
gps = new LocationCoord(this);
#Override
protected void onStart() {
super.onStart();
// permission android 6.0
if (!checkPermission()) {
requestPermission();
}
}
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
if (result == PackageManager.PERMISSION_GRANTED) return true;
else return false;
}
private void requestPermission(){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
You will need this permissions on the Manifest.xml:
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
You can get LoocationCord.java here: https://github.com/toomyy94/ImHere-Chatbot/blob/master/app/src/main/java/pt/ua/tomasr/imhere/modules/LocationCoord.java
you might have to add a dependency in your build.gradle:
compile 'com.google.android.gms:play-services-location:10.0.1

Adding location permissions on marshmallow

I am writing a code to get lastknownlocation from location manager and this prompted me to add runtime permissions.
Here is my code:
public class MainActivity extends AppCompatActivity implements LocationListener {
LocationManager locationManager;
String provider;
private final int MY_PERMISSIONS_REQUEST_CODE=1;
Location location;
Boolean isPermissionGranted=false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},MY_PERMISSIONS_REQUEST_CODE);
}
// return;
}
}
public void getlastknownposition()
{
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == MY_PERMISSIONS_REQUEST_CODE)
{
if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED){
Toast.makeText(MainActivity.this," granted "+grantResults[0]+"granted2"+grantResults[1], Toast.LENGTH_SHORT).show();
location = locationManager.getLastKnownLocation(provider);}
}
}
}
I am still getting an error "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
in onRequestPermissionsResult on line location = locationManager.getLastKnownLocation(provider);
Put some braces around the second if in onPermissionsResult =)
if(requestCode == MY_PERMISSIONS_REQUEST_CODE){
if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED){
Toast.makeText(MainActivity.this," granted "+grantResults[0]+"granted2"+grantResults[1], Toast.LENGTH_SHORT).show();
location = locationManager.getLastKnownLocation(provider);
} else {
//TODO handle user saying NO! :)
}
}
Tip: if you request FINE_LOCATION you don't need COARSE, it already includes it.
Replace the line
location = locationManager.getLastKnownLocation(provider);
with
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
location = locationManager.getLastKnownLocation(provider);
}

Get user's location in android API 23

I could write code that get user's location and that works fine in API < 23. But in API 23 and above, my code return nothing in Log.
More Details:
I enable manually device's GPS.
In the first run the app request permission and no log returns.
In the next running the app return my prepared Toast (Check your provider).
this is my wrote code:
public class MainActivity extends AppCompatActivity implements LocationListener {
private static final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION = 124;
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 123;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_FINE_LOCATION);
}
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_COARSE_LOCATION);
}
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), false);
Location location = locationManager.getLastKnownLocation(provider);
if (location == null) {
Toast.makeText(this, "Check your provider", Toast.LENGTH_SHORT).show();
} else {
Log.i("New Location", "lat: " + location.getLatitude());
Log.i("New Location", "lng: " + location.getLongitude());
}
}
#Override
public void onLocationChanged(Location location) {
Log.i("Location", "lat: " + location.getLatitude());
Log.i("Location", "lng: " + location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
In Android API 23+ there is a new way to handle permissions considered as "dangerous", that´s the case of android.permission.ACCESS_FINE_LOCATION and android.permission.ACCESS_COARSE_LOCATION among others.
You don´t need to handle android.permission.ACCESS_COARSE_LOCATION if you are already using the android.permission.ACCESS_FINE_LOCATION.
Please take a look at this link from the official documentation which shows you how to handle permissions at runtime in Android API 23+.
https://developer.android.com/training/permissions/requesting.html
This one might also help you.
https://developer.android.com/guide/topics/location/strategies.html
How to check for permissions:
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_FINE_LOCATION);
How to request for permissions:
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
// MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
Note that even if you request for permissions at runtime you will still have to keep the permission entry in the android manifest like this:
<manifest ... >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
...
<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />
...
</manifest>
After checking and granting permissions you should review the link with the location strategies above, there you can find the details of what you are missing.
Basically you are not registering the listener to receive the location updates. After adding this line at the end of the onCreate() method you should start seeing the location updates in your log.
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);

GPS reading cant be retrieved

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

Categories

Resources