Search code examples
androidandroid-asynctaskandroid-permissionsandroid-location

Android: Requesting location permission from AsyncTask


I have created a class LocationProcess that extends AsyncTask in a separate Java file.

With the doInBackground() method, I am trying to fetch the location coordinates (latitude and longitude) of the device. How and where to ask for permission, send location settings intent, etc. Please help.


Solution

  • You should ask for permission from your Activity before starting the AsyncTask. Execute the AsyncTask only if the permissions are granted and location is enabled.

    Refrain from temptation to pass Activity reference to the AsyncTask, since it could cause memory leaks if not handled properly.

    Its good practice to check whether permission is granted at lower level i.e. before accessing the API related to location, you can add simple check to verify if the permissions are granted.