0

It will be a great help if someone can give a bit working demonstration with proper code. I want to fetch the background location every 2-3 minutes.

I have tried this below code, but it is showing toast message Permission Denied every time.

I have written this code inside a fragment,I have tried to search on medium, other sites, and youtube, all are showing the demonstration for foreground location,please help me.

 private var mFusedLocationClient: FusedLocationProviderClient? = null
    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            mFusedLocationClient=LocationServices.getFusedLocationProviderClient(requireContext())

        if(ActivityCompat.checkSelfPermission(requireContext(),Manifest.permission.ACCESS_BACKGROUND_LOCATION)==PackageManager.PERMISSION_GRANTED)
        {
            Toast.makeText(requireContext(),"IF",Toast.LENGTH_SHORT).show()
            getTheCurrentLocation()
        }
        else
        {
            Toast.makeText(requireContext(),"Else",Toast.LENGTH_SHORT).show()
            requestPermissions(arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
                ,100)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if(requestCode==100 && grantResults.size>0 && (grantResults[0]==PackageManager.PERMISSION_GRANTED))
            getTheCurrentLocation()
        else
        {
            Toast.makeText(requireContext(),"Permission Denied",Toast.LENGTH_SHORT).show()
        }
    }

    private fun getTheCurrentLocation()
    {
        Toast.makeText(requireContext(),"In GetCurrentLocation Fun",Toast.LENGTH_SHORT).show()
       var locationManager:LocationManager?=null
        locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager

        if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
        {
            //when location service is enabled
            //Get the last location
            if (ActivityCompat.checkSelfPermission(
                    requireContext(),
                    Manifest.permission.ACCESS_FINE_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
            }
            mFusedLocationClient?.lastLocation?.addOnCompleteListener(OnCompleteListener {
               var location:android.location.Location?=null
                location=it.result
                if(location!=null)
                {
                    println("Location is  ${location.latitude}  ${location.longitude}")
                }
                else
                {

                   var locationRequest:LocationRequest=LocationRequest().
                       setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                       .setInterval(1000)
                       .setFastestInterval(100)
                       .setNumUpdates(1)

                     var locationCallback:LocationCallback=object:LocationCallback()
                     {
                         override fun onLocationResult(locationResult: LocationResult) {
                             var location1:android.location.Location?=null
                             location1=locationResult.lastLocation
                             println("else Location is  ${location1.latitude}  ${location1.longitude}")
                         }
                     }

                    mFusedLocationClient!!.requestLocationUpdates(locationRequest,locationCallback,
                        Looper.myLooper())
                }

            })
        }
    }
Lavish Garg
  • 235
  • 2
  • 9
  • Thanks for the reply Selvin,None of the answer on Stackoverflow are working,by this mean that that are not working as what I am expecting,and since background location permission is new in android 11,very few resources are out there on android official docs and other sites,and those given are also only theoretical one covering the topic from upper layer. – Lavish Garg Nov 03 '21 at 11:53
  • @Selvin yes that was asked previously before but in another manner and that issue was not also solved there. – Lavish Garg Nov 03 '21 at 11:55
  • It feels like you are asking for background permission before asking for the actual location permission. I think you need to request `ACCESS_FINE_LOCATION` first. See [the documentation](https://developer.android.com/training/location/permissions) for more. – CommonsWare Nov 03 '21 at 12:00
  • @CommonsWare this solution https://stackoverflow.com/q/64246883/11942531 solved my problem to a bit extent, can you please let help me, where to fetch the location of the user like what I have done in my above code by calling getTheCurrentLocation(). Thanks in Advance. – Lavish Garg Nov 03 '21 at 12:47

0 Answers0