firebase – Coarse location misbehaves in Android 12

I had recently uploaded my app in play store and it was working fine up to android 11. When tested in devices with android 12 , app is misbehaving while fetching the coarse location, where fine location is working fine as expected. As we know in Android 12 user have the freedom to give permission for precise(fine) location or approximate (coarse) location. When user choose to give coarse location my app is behaving as permission are denied and give toast to go to application setting which I actually wrote to show when user deny location permission. I don’t know why this is happening. Please find the below code and help me in sorting the issue.

  LocationFetchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isConnected(this)) {

                Toast.makeText(getApplicationContext(), " Please connect to internet", Toast.LENGTH_SHORT).show();

            }else {


             new AlertDialog.Builder(BuyerAreaFinderActivity.this)
                        .setMessage(" Location fetch" ).
                        setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE
                                );
                                if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
                                        || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

                                    if (ActivityCompat.checkSelfPermission(BuyerAreaFinderActivity.this
                                            , Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                                            && ActivityCompat.checkSelfPermission(BuyerAreaFinderActivity.this
                                            , Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED){

                                        loadingBar.setTitle("Please wait "); 
                                        loadingBar.setMessage("please wait, while we are fetching the area details..."); 
                                        loadingBar.setCanceledOnTouchOutside(false); 
                                        loadingBar.show();

                                        getDCurrentLocation();

                                    }else {
                                        
                                        ActivityCompat.requestPermissions(BuyerAreaFinderActivity.this
                                                , new String[]{Manifest.permission.ACCESS_FINE_LOCATION
                                                        , Manifest.permission.ACCESS_COARSE_LOCATION}
                                                , 100);
                                    }

                                }else {
                                    Toast.makeText(getApplicationContext(), "Please switch on location ,  ", Toast.LENGTH_LONG).show();
                                    startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                                            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                }


                            }
                        }). setNegativeButton("Cancel", null)
                        .setCancelable(false)
                        .show();




            }
        }
    });


  @SuppressLint("MissingSuperCall")
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    //This method check whether permission is granted or not after requesting permission using the request code

    //here suppress error by right clicking.
    if(requestCode ==100 && grantResults.length>0&&(grantResults[0]+grantResults[1]
            ==PackageManager.PERMISSION_GRANTED)){
        //when permission granted
        // Call method
        getDCurrentLocation();


    }else {
        // This part is getting executed while allowing coarse permission , Actually I wrote this to show when permissions are denied.

        if (!ActivityCompat.shouldShowRequestPermissionRationale(BuyerAreaFinderActivity.this, Manifest.permission.ACCESS_FINE_LOCATION )
                && !ActivityCompat.shouldShowRequestPermissionRationale(BuyerAreaFinderActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
            //This block here means PERMANENTLY DENIED PERMISSION
            new AlertDialog.Builder(BuyerAreaFinderActivity.this)
                    .setMessage("You have permanently denied this permission, go to settings to enable this permission")
                    .setPositiveButton("Go to settings", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            gotoApplicationSettings();
                        }
                    })
                    .setNegativeButton("Cancel", null)
                    .setCancelable(false)
                    .show();
        }else{
            Toast.makeText(getApplicationContext(),"Location permission denied, Please click again to allow location permission.",Toast.LENGTH_LONG).show();
        }
    }
}

@SuppressLint("MissingPermission")

//Method for getting current location

    private void getDCurrentLocation() {

    fusedLocationProviderClient.flushLocations();// used by me for refreshing don't know correct or not

    CancellationTokenSource tokenSource = new CancellationTokenSource();
    CancellationToken token = tokenSource.getToken();

    fusedLocationProviderClient.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY,token).addOnCompleteListener(new OnCompleteListener<Location>() {
        @Override
        public void onComplete(@NonNull Task<Location> task) {

            Location location=task.getResult();

            if(location !=null){

                BuyerLatitude=String.valueOf(location.getLatitude());
                BuyerLongitude=String.valueOf(location.getLongitude());

                // ----------------- Geocoder is used to find the address if we dont address don't use this part -----------------

                Geocoder geocoder = new Geocoder(BuyerAreaFinderActivity.this, Locale.getDefault());
                try {

                    List<Address> addresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
                    String address = addresses.get(0).getAddressLine(0);
                    BuyerArea.setText(address);
                    BuyerAreaFetchBtn.setVisibility(View.INVISIBLE);

                    loadingBar.dismiss();

                } catch (IOException e) {
                    e.printStackTrace();
                    loadingBar.dismiss();
                }
                //------------------up to here for Geocoder-------------------------------------------------------------------------------


            }
            else {
                //Location update.. when location result is null , Initialize location update part
                // LocationRequest locationRequest = new LocationRequest() //deprecated so changed by me

                loadingBar.dismiss();

                LocationRequest locationRequest = LocationRequest.create()
                        .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                        .setInterval(10000)
                        .setFastestInterval(1000)
                        .setNumUpdates(1);

                //Initialize location call back

                LocationCallback locationCallback=new LocationCallback(){
                    @Override
                    public void onLocationResult(LocationResult locationResult) {
                        Location location1=locationResult.getLastLocation();

                        BuyerLatitude=String.valueOf(location1.getLatitude());
                        BuyerLongitude=String.valueOf(location1.getLongitude());
                    }
                };
                // Request location updates

                fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback, Looper.myLooper());
                Toast.makeText(getApplicationContext(),"We are collecting your location details. It may take up to 3 minutes, please wait for few minutes and press the button again",Toast.LENGTH_LONG).show();
                fusedLocationProviderClient.removeLocationUpdates(locationCallback);
            }

        }
    });


}

Method to go to application setting

    private void gotoApplicationSettings() {

    Intent intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    Uri uri = Uri.fromParts("package", this.getPackageName(), null);
    intent.setData(uri);
    startActivity(intent);

}

Manifest file (part for location)

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dxxxxst.brxxxx">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Leave a Comment