0

Google is deprecating Android AsyncTask API in Android 11

Google is deprecating Android AsyncTask API in Android 11 and suggesting to use java.util.concurrent instead

My question is that what should be proper replacement of the code snippet shown below using java.util.concurrent

package gaspriceinegypt.gaspriceegypt.gaspriceinegypt


import android.os.AsyncTask
import com.google.android.gms.maps.GoogleMap
import gaspriceinegypt.gaspriceegypt.gaspriceinegypt.DownloadUrl
import org.json.JSONObject
import org.json.JSONArray
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.CameraUpdateFactory
import org.json.JSONException
import java.io.IOException

class FetchData : AsyncTask<Any?, String?, String?>() {
    var googleNeatByPlacesData: String? = null
    var googleMap: GoogleMap? = null
    var url: String? = null


    override fun onPostExecute(s: String?) {
        try {
            val jsonObject = JSONObject(s)
            val jsonArray = jsonObject.getJSONArray("results")
            for (i in 0 until jsonArray.length()) {
                val jsonObject1 = jsonArray.getJSONObject(i)
                val getLocation = jsonObject1.getJSONObject("geometry").getJSONObject("location")
                val lat = getLocation.getString("lat")
                val lng = getLocation.getString("lng")
                val getName = jsonArray.getJSONObject(i)
                val name = getName.getString("name")
                val latLng = LatLng(lat.toDouble(), lng.toDouble())
                val markerOptions = MarkerOptions()
                markerOptions.title(name)
                markerOptions.position(latLng)
                googleMap!!.addMarker(markerOptions)
                googleMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f))
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

    override fun doInBackground(vararg objects: Any?): String? {
        try {
            googleMap = objects[0] as GoogleMap
            url = objects[1] as String
            val downloadUrl = DownloadUrl()
            googleNeatByPlacesData = downloadUrl.retireveUrl(url)
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return googleNeatByPlacesData
    }
}

1 Answers1

1

As you know Google is deprecating Android AsyncTask API in Android 11.

Alternatives in my mind are:

  1. kotlin coroutines
  2. use self Executor interface implemetion which is a Java standard lib interface
  3. WorkManager which is a android lib
Se ven
  • 377
  • 2
  • 11