Error in startlocation update in request permissions - android

i have an error that i cant fix and when i press alt+enter nothing
happens, i already added permission.ACCESS_FINE_LOCATION etc in the
manifest, can someone please help me ? i tried everything but nothing
seems to work
private void startLocationUpdates(){
String[] PERMISSIONS = {android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this, PERMISSIONS[0])
!= PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, PERMISSIONS[1])
!= PackageManager.PERMISSION_GRANTED
) {
//gives me error in this activity.compat.request
ActivityCompat.requestPermissions((Activity) this, PERMISSIONS, 0 );
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);// and error in this line too
Toast.makeText(this, "sinal pedido", Toast.LENGTH_SHORT).show();
}
}

Try this
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
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)) {
// Show an explanation 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.
new AlertDialog.Builder(this)
.setTitle(R.string.title_location_permission)
.setMessage(R.string.text_location_permission)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
Then you would just modify your onResume() override to call checkLocationPermission():
#Override
protected void onResume() {
super.onResume();
if (checkLocationPermission()) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
}
}
Source: this

Related

Accessing GPS coordinates in same application session in which permission was provided by the user via popup window

I'd like for a user who starts the application for the first time on a device to be able to access GPS data in that session. Currently, the user must close and then restart the application after providing location permission for the location data to show in the application.
I have tried a variety of methods to resolve this. Most recently, I have moved requestPermission into Fragment1 which is also where locationManager is located.
public class Fragment1 extends Fragment {
public static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.data_capture, container, false);
requestPermission(v);
permissionAssessment(v);
...
return (v);
}
public void requestPermission(View v) {//This works, only poulates after restart...
int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);
//conditional here so that if conditionals granted do below, if refused, go away...
}else{
mGpsLocationListener = new GpsLocationListener();
lm = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
mGpsStatus = lm.getGpsStatus(mGpsStatus);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, mGpsLocationListener);
}
}
In addition, I took the caveman approach, and created "permissionAssessment()" that would run immediately following requestPermission() assuming that perhaps since permissions were likely granted by the user in requestPermission(), I could run checkSelfPermission and force location services to start that way. No cigar. See below.
public void permissionAssessment(View v){
int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
mGpsLocationListener = new GpsLocationListener();
lm = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
mGpsStatus = lm.getGpsStatus(mGpsStatus);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, mGpsLocationListener);
}
}
Note that permissionAssessment() works fine if the device already has ACCESS_FINE_LOCATION permissions granted. It just does not work following the newly installed permissions from requestPermission() when that is used and there were no pre-existing permissions on the device.
Furthermore, fyi this application starts on the tab associated with Fragment1 and has constantly updated gps satellite time displayed. Satellite/GPS data shows fine AFTER the application has been restarted following the session where the user granted location permissions. I'd strongly prefer that the GPS "go-live" in the session where the user sets permissions. Constructive suggestions would be appreciated. Thanks in advance.
Update, 5/14/2021: This is what ended up working for me,
public class MainActivity extends AppCompatActivity {
...
private boolean requestPermissions() {
int iExtStorage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
int iCoarseLocation = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION);
int iFineLocation = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (iExtStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (iFineLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
}
if (iCoarseLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (!listPermissionsNeeded.isEmpty())
{
ActivityCompat.requestPermissions(this,listPermissionsNeeded.toArray
(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
getLocation();
return true;
}
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
getLocation();
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
return;
}
}
}
...
}
Update #2, 5/14/2021: Per Sasaki's additional comment. This is from the fragment.
public class dataCapture extends Fragment {
...
private boolean requestPermission(View v) {
int iExtStorage = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
int iCoarseLocation = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION);
int iFineLocation = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (iExtStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (iFineLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
}
if (iCoarseLocation != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (!listPermissionsNeeded.isEmpty())
{
requestPermissions(listPermissionsNeeded.toArray
(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
getLocation();
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
getLocation();
}
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
}
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
}
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
return;
}
}
}
...
}
In addition, I took the caveman approach, and created "permissionAssessment()" that would run immediately following requestPermission() assuming that perhaps since permissions were likely granted by the user in requestPermission().
This approach will not work the first time when the permissions are granted by user.
This is because a prompt is shown to user for requesting permission using ActivityCompat.requestPermissions(...).
The actual granting/denial of permission would be done on a later stage when the user interacts with the prompt.
This means that the function permissionAssessment(...) which is being immediately run after the ActivityCompat.requestPermission(...) will not have the permissions hence wont run successfully for the first time and will require a Fragment "reload".
To ensure a successful run, you'll have to call the permissionAssessment(...) in the "success" callback of ActivityCompat.requestPermission(...). This is done using the function onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults).
Here's my implementation :-
public class Fragment1 extends Fragment {
public static final int REQUEST_FINE_LOCATION_CODE = 1;
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.data_capture, container, false);
permissionAssessment(v);
...
return (v);
}
public void permissionAssessment(View v){
int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
// Permission is granted, proceed to get location.
getLocation()
} else {
// Permission is not granted, request permissions.
// Only the prompt is shown here, nothing else will happen.
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION_CODE);
}
}
/**
* This Function is responsible for handling what happens when permissions are granted by the user.
*/
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_FINE_LOCATION_CODE) {
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permissions Granted!
// Get Location as soon as the permissions are granted.
getLocation();
}
} else {
// Permission Denied by the user
// Show a prompt or do nothing as per your use case.
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
public void getLocation() {
mGpsLocationListener = new GpsLocationListener();
lm = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
mGpsStatus = lm.getGpsStatus(mGpsStatus);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, mGpsLocationListener);
}
Please refer to this
https://developer.android.com/guide/topics/permissions/overview and
https://developer.android.com/training/permissions/requesting

How to Re-Check Permissions on Resume

My application crashes if users enable the location permission through the app, then head to their phone's settings and disable the permission there. I have tried fixing this by checking the permissions through onResume but can't seem to get it right. Other solutions on StackOverflow haven't worked.
The following code runs within my onCreate() and checks for location permissions:
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
//check which API users are running.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//location permission dialog
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
}
}
My onRequestPermissionsResult():
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSION_FINE_LOCATION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(getContext(), "The app requires location permissions", Toast.LENGTH_LONG).show();
getActivity().finish();
}
break;
}
}
Here is my onResume() code within the same fragment:
#Override
public void onResume() {
super.onResume();
updatePermissions();
if (googleApiClient.isConnected()) {
requestLocationUpdates();
}
}
public void updatePermissions(){
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// mMap.setMyLocationEnabled(true);
} else {
//check which API users are running.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//location permission dialog
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
}
}
}
The app crashes with the error:
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 at fluo.tuki10.fragments.MapFragment.onRequestPermissionsResult(MapFragment.java:232)
which is the line
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
I feel like the solution is to implement a better onResume() that checks for permissions after users modify them outside the app. Unfortunately my code falls short
An advice, before comparing it with a head that is not without elements:
if (grantResults.length> 0)

Runtime permission (requestPermissions) is not working

I have to check permission in Fragment at the runtime for getting Location.
Here is a function for checking permission.
public void weather() {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
try {
if (checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 123);
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
syncData(latitude, longitude);
}
}
});
return;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 123) {
weather();
}
}
The issue is that my code stuck in this like a loop. It does not grant permissions and every time this if check return true and my code back and forth like a loop between override permission and if statement. And one thing more do we need this two permssion in the manifest as well?
if (checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 123);
return;
}
Try this
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[],
#NonNull int[] grantResults) {
if (requestCode == 123) {
if (grantResults.length == 1 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
weather();
} else {
Toast.makeText(getActivity(), "Permission denied", oast.LENGTH_SHORT).show();
}
}
}
Try below condition in onRequestPermissionsResult
if (requestCode == 123 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
weather();
}
And you can remove and condition of ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTEDas it belongs to same permission group with ACCESS_FINE_LOCATION

Code for retrieving location not executing even after asking for permission in android marshmallow

I'm trying to retrieve user's current location using this library.
The code is fetching the location successfully in versions below android M, but when I am launching the app on devices with Android Marshmallow, the piece of code is not getting executed even!
I have written this code in the onCreate() method:
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(getBaseContext());
locationProvider.getLastKnownLocation()
.subscribe(new Action1<Location>() {
#Override
public void call(Location location) {
currentLatDouble = location.getLatitude();
currentLngDouble = location.getLongitude();
Toast.makeText(getBaseContext(), "User's location retrieved using library", Toast.LENGTH_SHORT).show();
}
});
Upon running the app on android marshmallow devices, I'm not getting this toast: Toast.makeText(getBaseContext(), "User's location retrieved using library", Toast.LENGTH_SHORT).show(); which means that this code is not getting executed!
Before writing this code, I have asked for permission using the code below:
int hasWriteContactsPermission = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
& ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
& ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
& ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_SETTINGS);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getBaseContext(), Manifest.permission.WRITE_SETTINGS) != 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.
if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
&& !ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
&& !ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
&& !ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_SETTINGS)) {
showMessageOKCancel("You need to allow access to few permissions so that the app can work as expected.",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.WRITE_SETTINGS},
REQUEST_RUNTIME_PERMISSION);
}
});
return;
}
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.WRITE_SETTINGS},
REQUEST_RUNTIME_PERMISSION);
return;
}
}
Here's onRequestPermissionsResult()'s code:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_RUNTIME_PERMISSION:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(getBaseContext());
locationProvider.getLastKnownLocation()
.subscribe(new Action1<Location>() {
#Override
public void call(Location location) {
currentLatDouble = location.getLatitude();
currentLngDouble = location.getLongitude();
Toast.makeText(getBaseContext(), "User's location retrieved using library", Toast.LENGTH_SHORT).show();
}
});
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (currentLatDouble != null || currentLngDouble != null ) {
retrieveHRequests();
retrieveUserCounterA();
retrieveUserCounterP();
} else {
ifLocationAvailable();
}
}
}, 2000);
} else {
// Permission Denied
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT)
.show();
//helpRequestsLoadingDialog.dismiss();
progressBarLoadingRequests.setVisibility(View.INVISIBLE);
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(getBaseContext());
locationProvider.getLastKnownLocation()
.subscribe(new Action1<Location>() {
#Override
public void call(Location location) {
currentLatDouble = location.getLatitude();
currentLngDouble = location.getLongitude();
Toast.makeText(getBaseContext(), "User's location retrieved using library", Toast.LENGTH_SHORT).show();
}
});
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (currentLatDouble != null || currentLngDouble != null ) {
retrieveHRequestWrapper();
retrieveUserInfo();
} else {
ifLocationAvailable();
}
}
}, 2000);
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
I have written the location retrieving code even in onRequestPermissionResult()'s PERMISSION_GRANTED case, but nothing is happening and no location getting retrieved in android marshmallow version!
Please let me know what's going wrong here!

added location permission check on run time still gives error

I have added in my activity -location permission check on run time- but I still get the error that tell me to add the permission check...
here is my code. In Oncreate () I have added:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
bPermissionGranted = checkLocationPermission();
}
In on onConnected:
public void onConnected(Bundle bundle) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (bPermissionGranted) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
handleNewLocation(location);
} else {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
handleNewLocation(location);
}
}
}
And the two method:
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
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)) {
// 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.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
handleNewLocation(location);
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
And it still mark the follow with red error:
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Well your code is somewhat fine. Don't check for permission in onCreate. Check it in your onConnected() method because its possible that the user has not granted the permission yet and onConnected() is executed before.
Then when you receive the permission result in onRequestPermissionsResult(), then start fetching the location updates if the result is positive.
Also an advice -
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
This piece of code is redundant. Android only requires run time permissions in Android M and above so your permission check code would only be executed if the Android version is above M else it won't execute.

Categories

Resources