Location Updates Not Working On Allowing Runtime Permission
I've written code for app that shows phone's latitude and longitude and displays it on the screen, but after granting location permission it doesn't show anything, only when I reop
Solution 1:
Try this complete solution
in onCreate()
do this
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLatitudeText = (TextView) findViewById(R.id.latitude);
mLongitudeText = (TextView) findViewById(R.id.longitude);
checkAndroidVersion();
}
this method checkAndroidVersion();
public void checkAndroidVersion() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkAndRequestPermissions()) {
buildClient();
mGoogleApiClient.connect();
} else
{
}
} else {
if (checkPlayServices()) {
// Building the GoogleApi clientbuildClient();
mGoogleApiClient.connect();
}
// write your logic here
}
}
this method
public boolean checkAndRequestPermissions() {
int location = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (location != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(MainActivity.this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
returnfalse;
}
returntrue;
}
publicstatic final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
then in onRequestPermission()
@OverridepublicvoidonRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.d("in main on request", "Permission callback called-------");
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = newHashMap<>();
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from userif (grantResults.length > 0) {
for (inti=0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for both permissionsif (perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Log.d("in main on request", "location services permission granted");
// process the normal flow//else any one or both the permissions are not granted
buildClient();
mGoogleApiClient.connect();
} else {
Log.d("in fragment on request", "Some permissions are not granted ask again ");
//permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission// // shouldShowRequestPermissionRationale will return true//show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
showDialogOK("Location services services are required for this app",
newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.break;
}
}
});
}
//permission is denied (and never ask again is checked)//shouldShowRequestPermissionRationale will return falseelse {
Toast.makeText(MainActivity.this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
.show();
// //proceed with logic by disabling the related features or quit the app.
}
}
}
}
}
}
publicvoidshowDialogOK(String message, DialogInterface.OnClickListener okListener) {
newAlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
then
publicvoidbuildClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
then do this
@OverridepublicvoidonStop() {
super.onStop();
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected() && mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
}
}
and then
/**
* Method to verify google play services on the device
*/public boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(MainActivity.this,
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
returnfalse;
}
returntrue;
}
and then add this
@OverridepublicvoidonConnected(@Nullable Bundle bundle) {
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;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation == null) {
startLocationUpdates();
}
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
} else {
// Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
/**
* This library works in release mode only with the same JKS key used for
* your Previous Version
*/
}
protectedvoidstartLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(5000)
.setFastestInterval(5000);
// Request location updatesif (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;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
Log.d("reque", "--->>>>");
}
@OverridepublicvoidonConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
@OverridepublicvoidonConnectionFailed(@NonNull ConnectionResult connectionResult) {
try {
if (checkAndRequestPermissions()) {
buildClient();
mGoogleApiClient.connect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@OverridepublicvoidonLocationChanged(Location location) {
current_location = location;
SharedPrefsUtils.setStringPreference(MainActivity.this, "user_current_latitude", current_location.getLatitude() + "");
SharedPrefsUtils.setStringPreference(MainActivity.this, "user_current_longitude", current_location.getLongitude() + "");
System.out.println("sjkbd jdsbj");
}
in the Activity or fragment
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager locationManager;
private LocationRequest mLocationRequest;
publicclassMainActivityextendsAppCompatActivityimplementsView.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
Post a Comment for "Location Updates Not Working On Allowing Runtime Permission"