I have implemented the code to get the latitude and longitude it works fine for below version 23, but not working for android Marshmallow. I have set the run time permissions also but still not working, below is my code where I am calling method.
private void configureButton() {
get_gps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), 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,
Manifest.permission.INTERNET, Manifest.permission.ACCESS_NETWORK_STATE
}, 10);
}
}
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 10:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
configureButton();
return;
}
}
}
Related
I am trying to get runtime permissions on my app. However the app is not displaying the dialog to request the specific permission. The code below only works when the GPS is turned on on the phone manually.
I am running the app on Android 5.0.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_location = findViewById(R.id.get_location);
txt_latitude = findViewById(R.id.latitude);
txt_longitude = findViewById(R.id.longitude);
txt_timestamp = findViewById(R.id.timestamp);
btn_map = findViewById(R.id.map);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
btn_location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getLocation();
}
});
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, REQUEST_LOCATION_PERMISSION);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener < Location > () {
#Override
public void onSuccess(Location location) {
if (location != null) {
mLastLocation = location;
txt_latitude.setText(getString(R.string.location_latitude, mLastLocation.getLatitude()));
txt_longitude.setText(getString(R.string.location_longitude, mLastLocation.getLongitude()));
txt_timestamp.setText(getString(R.string.timestamp, mLastLocation.getTime()));
} else {
txt_latitude.setText(R.string.no_latitude);
txt_longitude.setText(R.string.no_longitude);
txt_timestamp.setText(R.string.no_timestamp);
}
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_LOCATION_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLocation();
} else {
Toast.makeText(this, R.string.location_permission_denied, Toast.LENGTH_SHORT).show();
}
}
}
}
Since you are run on Android 5.0 the Android runtime permission won't be shown. As runtime permission is only be shown starting from Android 6 (Marshmellow).
Please check the official documentation for the runtime permission details.
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)
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
I am developing an location app which is working fine in all devices except in Marshmallow.I have requested permission during runtime and when I grant permission longitude and latitude is not fetched,if i go to settings and change the location from high accuracy to battery saving,location is fetched and the app works.I want location to be fetched at high accuracy.
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.CAMERA,
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.INTERNET,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.WAKE_LOCK,
},
1);
try this
step 1 :- add this permission in manifiesr file
android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION,
step 2 : ask runtime permission
String permission = android.Manifest.permission.ACCESS_FINE_LOCATION;
if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.
checkSelfPermission(SearchCityClass.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
{permission}, PERMISSION_GPS_CODE);
}
step 3: handle permsiion result
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_GPS_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, location_permission_granted_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, location_permission_not_granted_msg, Toast.LENGTH_SHORT).show();
}
}
}
You have to give run time permission for android 6 like this
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) {
// Permission already Granted
//Do your work here
//Perform operations here only which requires permission
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
and if permission is not already granted override onRequestPermission Results like this
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Permission Granted
//Do your work here
//Perform operations here only which requires permission
}
}
}
Add this code your Activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
requestLocationPermission();
//your other codes
}
private void requestLocationPermission() {
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) {
} else {
ActivityCompat.requestPermissions(this, new String[]
{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
//If permission is granted
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can get the location", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
Add this on your Mainfest XML
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
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!