我需要在Kotlin的Asynctask替代方案,我知道使用Caroutines,执行者,处理程序,但不确定如何在Google Maps Koltin App中实现
我正在构建一个Google Maps路由应用程序,并且无法构建Asynctask的弃用,我知道使用caroutines/opecuter/handlers,但我不知道如何在我的代码中实现它们,因为我遵循了几个教程并且不确定。我正在使用地图和Directions API构建Google Maps应用程序,并且与ASynctask折旧有问题。
这是我的下载任务功能:
inner class DownloadTask :
AsyncTask<String?, Void?, String>(){
override fun onPostExecute(result: String) {
super.onPostExecute(result)
val parserTask = ParserTask()
parserTask.execute(result)
}
override fun doInBackground(vararg url: String?): String {
var data = ""
try{
data = downloadUrl(url[0].toString()).toString()
} catch (e: java.lang.Exception) {
Log.d("Background Task", e.toString())
}
return data
}
}
这是我的解析器任务,可以通过数据解析器类解析JSON,
//parsing into JSON format
inner class ParserTask :
AsyncTask<String?, Int?, List<List<HashMap<String, String>>>?> () {
override fun doInBackground(vararg jsonData: String?): List<List<HashMap<String, String>>>? {
val jObject: JSONObject
var routes: List<List<HashMap<String, String>>>? =
null
try {
jObject = JSONObject(jsonData[0])
val parser = DataParser()
routes = parser.parse(jObject)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
return routes
}
override fun onPostExecute(result: List<List<HashMap<String, String>>>?) {
val points = ArrayList<LatLng?>()
val lineOptions = PolylineOptions()
for (i in result!!.indices) {
val path =
result[i]
for (j in path.indices) {
val point = path[j]
val lat = point["lat"]!!.toDouble()
val lng = point["lng"]!!.toDouble()
val position = LatLng(lat, lng)
points.add(position)
}
lineOptions.addAll(points)
lineOptions.width(8f)
lineOptions.color(Color.RED)
lineOptions.geodesic(true)
}
if (points.size != 0) mMap!!.addPolyline(lineOptions)
}
}
如果有人可以帮助我使用该代码使用executor and Handler,这将非常感谢!
这是我的完整MainActivity文件供参考。
class MainActivity : AppCompatActivity(), OnMapReadyCallback
//, LocationListener, GoogleMap.OnCameraMoveListener, GoogleMap.OnCameraMoveStartedListener, GoogleMap.OnCameraIdleListener
{
private var mMap: GoogleMap? = null
lateinit var mapView: MapView
private val MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey"
private val DEFAULT_ZOOM = 15f
lateinit var B_search: Button
lateinit var tvCurrentAddress: TextView
private var fusedLocationProviderClient : FusedLocationProviderClient? = null
var end_latitude = 0.0
var end_longitude = 0.0
lateinit var origin: MarkerOptions
lateinit var destination:MarkerOptions
var latitude = 0.0
var longitude = 0.0
private val myExecutor = Executors.newSingleThreadExecutor()
private val myHandler = Handler(Looper.getMainLooper())
override fun onMapReady(googleMap: GoogleMap) {
mapView.onResume()
mMap = googleMap
askPermissionLocation()
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
return
}
mMap!!.setMyLocationEnabled(true)
// mMap!!.setOnCameraMoveListener (this)
// mMap!!.setOnCameraMoveStartedListener(this)
// mMap!!.setOnCameraIdleListener(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mapView = findViewById<MapView>(R.id.map1)
tvCurrentAddress = findViewById<TextView>(R.id.tvAdd)
B_search = findViewById(R.id.B_search)
askPermissionLocation()
var mapViewBundle: Bundle? = null
if(savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY)
}
mapView.onCreate(mapViewBundle)
mapView.getMapAsync(this)
B_search.setOnClickListener {
searchArea()
}
}
private fun searchArea() {
val tf_location =
findViewById<View>(R.id.TF_location) as EditText
val location = tf_location.text.toString()
var addressList: List<Address>? = null
val markerOptions = MarkerOptions()
if (location != "") {
val geocoder = Geocoder (applicationContext)
try {
addressList = geocoder.getFromLocationName(location, 5)
} catch (e: IOException) {
e.printStackTrace()
}
if (addressList != null) {
for (i in addressList.indices) {
val myAddress = addressList[i]
val latLng =
LatLng(myAddress.latitude, myAddress.longitude)
markerOptions.position(latLng)
mMap!!.addMarker(markerOptions)
end_latitude = myAddress.latitude
end_longitude = myAddress.longitude
mMap!!.animateCamera(CameraUpdateFactory.newLatLng(latLng))
val mo = MarkerOptions()
mo.title("Distance")
val results = FloatArray(10)
Location.distanceBetween(
latitude,
longitude,
end_latitude,
end_longitude,
results
)
val s =
String.format("%.1f", results[0] / 1000)
//Setting marker to draw route between these two points
origin = MarkerOptions().position(LatLng(latitude, longitude))
.title("HSR Layout").snippet("origin")
destination =
MarkerOptions().position(LatLng(end_latitude, end_longitude))
.title(tf_location.text.toString())
.snippet("Distance = $s KM")
mMap!!.addMarker(destination)
mMap!!.addMarker(origin)
Toast.makeText(
this@MainActivity,
"Distance = $s KM",
Toast.LENGTH_SHORT
) .show()
tvCurrentAddress!!.setText("Distance = $s KM")
//getting URL to the google Directions API
val url: String=
getDirectionsUrl(origin!!.getPosition(), destination!!.getPosition())!!
val downloadTask: DownloadTask = DownloadTask()
//start downloading the json data from google directions API
downloadTask.execute(url)
}
}
}
}
@Throws(IOException::class)
private fun downloadUrl(strUrl: String) : String?{
var data = ""
var iStream: InputStream? = null
var urlConnection: HttpURLConnection? = null
try{
val url = URL(strUrl)
urlConnection = url.openConnection() as HttpURLConnection
urlConnection.connect()
iStream = urlConnection!!.inputStream
val br =
BufferedReader(InputStreamReader(iStream))
val sb = StringBuffer()
var line: String? = ""
while (br.readLine().also { line = it } != null) {
sb.append(line)
}
data = sb.toString()
br.close()
} catch (e: java.lang.Exception) {
Log.d("Exception", e.toString())
} finally {
iStream!!.close()
urlConnection!!.disconnect()
}
return data
}
inner class DownloadTask :
AsyncTask<String?, Void?, String>(){
override fun onPostExecute(result: String) {
super.onPostExecute(result)
val parserTask = ParserTask()
parserTask.execute(result)
}
override fun doInBackground(vararg url: String?): String {
var data = ""
try{
data = downloadUrl(url[0].toString()).toString()
} catch (e: java.lang.Exception) {
Log.d("Background Task", e.toString())
}
return data
}
}
//parsing into JSON format
inner class ParserTask :
AsyncTask<String?, Int?, List<List<HashMap<String, String>>>?> () {
override fun doInBackground(vararg jsonData: String?): List<List<HashMap<String, String>>>? {
val jObject: JSONObject
var routes: List<List<HashMap<String, String>>>? =
null
try {
jObject = JSONObject(jsonData[0])
val parser = DataParser()
routes = parser.parse(jObject)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
return routes
}
override fun onPostExecute(result: List<List<HashMap<String, String>>>?) {
val points = ArrayList<LatLng?>()
val lineOptions = PolylineOptions()
for (i in result!!.indices) {
val path =
result[i]
for (j in path.indices) {
val point = path[j]
val lat = point["lat"]!!.toDouble()
val lng = point["lng"]!!.toDouble()
val position = LatLng(lat, lng)
points.add(position)
}
lineOptions.addAll(points)
lineOptions.width(8f)
lineOptions.color(Color.RED)
lineOptions.geodesic(true)
}
if (points.size != 0) mMap!!.addPolyline(lineOptions)
}
}
private fun getDirectionsUrl(origin: LatLng, dest: LatLng): String?{
//Origin of route
val str_origin = "origin=" + origin.latitude + "," + origin.longitude
//Destination of Route
val str_destination = "destination" + dest.latitude + "," + dest.longitude
//transportation mode
val mode = "mode=walking"
//building parameters of webservice
val parameters = "$str_origin&$str_destination&$mode"
//output format
val output = "json"
//building the url to the web service
return "https://maps.googleapis.com/maps/api/directions/$output?$parameters&key=AIzaSyCgraKSwPfUIyZLOmEDh_ptAbfRRAj7y1g"
}
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
askPermissionLocation()
var mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY)
if (mapViewBundle == null){
mapViewBundle = Bundle()
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle)
}
mapView.onSaveInstanceState(mapViewBundle)
}
private fun askPermissionLocation(){
askPermission(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
){
getCurrentLocation()
// mapView.getMapAsync(this@MyNavigationActivity)
}
}
private fun askPermission(accessFineLocation: String, accessCoarseLocation: String, function: () -> Unit) {
}
private fun getCurrentLocation() {
fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(this@MainActivity)
try {
@SuppressLint ("MissingPermission")
val location =
fusedLocationProviderClient!!.getLastLocation()
location.addOnCompleteListener(object : OnCompleteListener<Location> {
override fun onComplete(loc: Task<Location>) {
if (loc.isSuccessful) {
val currentLocation = loc.result as Location?
if (currentLocation != null) {
moveCamera(
LatLng(currentLocation.latitude, currentLocation.longitude),
DEFAULT_ZOOM
)
latitude = currentLocation.latitude
longitude = currentLocation.longitude
}
} else {
askPermissionLocation()
}
}
})
} catch (se: Exception) {
Log.e("TAG", "Security Exception")
}
}
private fun moveCamera(latLng: LatLng, zoom: Float) {
// mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom))
}
// override fun onLocationChanged(location: Location?) {
// val geocoder = Geocoder (this, Locale.getDefault())
// var addresses: List<Address>? = null
// try {
// addresses = geocoder.getFromLocation(location!!.latitude, location.longitude, 1)
// } catch (e: IOException) {
// e.printStackTrace()
// }
// setAddress(addresses!![0])
// }
//
// private fun setAddress(addresses: Address) {
// if (addresses != null) {
//
// if (addresses.getAddressLine(0) != null) {
// tvCurrentAddress!!.setText(addresses.getAddressLine(0))
// }
// if (addresses.getAddressLine(1) != null) {
// tvCurrentAddress!!.setText(
// tvCurrentAddress.getText().toString() + addresses.getAddressLine(1)
// )
// }
// }
// }
//
//
//
// override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
//
// }
//
// override fun onProviderEnabled(p0: String?) {
//
// }
//
// override fun onProviderDisabled(p0: String?) {
//
// }
//
// override fun onCameraMove() {
//
// }
//
// override fun onCameraMoveStarted(p0: Int) {
//
// }
//
// override fun onCameraIdle() {
// var addresses: List<Address>? = null
// val geocoder = Geocoder (this, Locale.getDefault())
// try {
// addresses = geocoder.getFromLocation( mMap!!.getCameraPosition().target.latitude, mMap!!.getCameraPosition().target.longitude, 1)
//
// setAddress(addresses!![0])
//
// } catch (e: IndexOutOfBoundsException) {
// e.printStackTrace()
// } catch (e: IOException) {
// e.printStackTrace()
// }
// }
}
I am building a google maps routing app and i cant build as AsyncTask is depreceiated, I know to use caroutines/executers/handlers but I dont know how to implement them in my code as I have followed several tutorials and unsure. I am building a google maps app using maps and directions API's and I am having an issue with AsyncTask being depreciated.
Here is My download task function:
inner class DownloadTask :
AsyncTask<String?, Void?, String>(){
override fun onPostExecute(result: String) {
super.onPostExecute(result)
val parserTask = ParserTask()
parserTask.execute(result)
}
override fun doInBackground(vararg url: String?): String {
var data = ""
try{
data = downloadUrl(url[0].toString()).toString()
} catch (e: java.lang.Exception) {
Log.d("Background Task", e.toString())
}
return data
}
}
and here is my parser task for parsing into JSON with data parser class
//parsing into JSON format
inner class ParserTask :
AsyncTask<String?, Int?, List<List<HashMap<String, String>>>?> () {
override fun doInBackground(vararg jsonData: String?): List<List<HashMap<String, String>>>? {
val jObject: JSONObject
var routes: List<List<HashMap<String, String>>>? =
null
try {
jObject = JSONObject(jsonData[0])
val parser = DataParser()
routes = parser.parse(jObject)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
return routes
}
override fun onPostExecute(result: List<List<HashMap<String, String>>>?) {
val points = ArrayList<LatLng?>()
val lineOptions = PolylineOptions()
for (i in result!!.indices) {
val path =
result[i]
for (j in path.indices) {
val point = path[j]
val lat = point["lat"]!!.toDouble()
val lng = point["lng"]!!.toDouble()
val position = LatLng(lat, lng)
points.add(position)
}
lineOptions.addAll(points)
lineOptions.width(8f)
lineOptions.color(Color.RED)
lineOptions.geodesic(true)
}
if (points.size != 0) mMap!!.addPolyline(lineOptions)
}
}
if anybody could help me with how I can use Executor and Handler with this code, that would be greatly appreciated!
Here is my full MainActivity file for reference.
class MainActivity : AppCompatActivity(), OnMapReadyCallback
//, LocationListener, GoogleMap.OnCameraMoveListener, GoogleMap.OnCameraMoveStartedListener, GoogleMap.OnCameraIdleListener
{
private var mMap: GoogleMap? = null
lateinit var mapView: MapView
private val MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey"
private val DEFAULT_ZOOM = 15f
lateinit var B_search: Button
lateinit var tvCurrentAddress: TextView
private var fusedLocationProviderClient : FusedLocationProviderClient? = null
var end_latitude = 0.0
var end_longitude = 0.0
lateinit var origin: MarkerOptions
lateinit var destination:MarkerOptions
var latitude = 0.0
var longitude = 0.0
private val myExecutor = Executors.newSingleThreadExecutor()
private val myHandler = Handler(Looper.getMainLooper())
override fun onMapReady(googleMap: GoogleMap) {
mapView.onResume()
mMap = googleMap
askPermissionLocation()
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
return
}
mMap!!.setMyLocationEnabled(true)
// mMap!!.setOnCameraMoveListener (this)
// mMap!!.setOnCameraMoveStartedListener(this)
// mMap!!.setOnCameraIdleListener(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mapView = findViewById<MapView>(R.id.map1)
tvCurrentAddress = findViewById<TextView>(R.id.tvAdd)
B_search = findViewById(R.id.B_search)
askPermissionLocation()
var mapViewBundle: Bundle? = null
if(savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAP_VIEW_BUNDLE_KEY)
}
mapView.onCreate(mapViewBundle)
mapView.getMapAsync(this)
B_search.setOnClickListener {
searchArea()
}
}
private fun searchArea() {
val tf_location =
findViewById<View>(R.id.TF_location) as EditText
val location = tf_location.text.toString()
var addressList: List<Address>? = null
val markerOptions = MarkerOptions()
if (location != "") {
val geocoder = Geocoder (applicationContext)
try {
addressList = geocoder.getFromLocationName(location, 5)
} catch (e: IOException) {
e.printStackTrace()
}
if (addressList != null) {
for (i in addressList.indices) {
val myAddress = addressList[i]
val latLng =
LatLng(myAddress.latitude, myAddress.longitude)
markerOptions.position(latLng)
mMap!!.addMarker(markerOptions)
end_latitude = myAddress.latitude
end_longitude = myAddress.longitude
mMap!!.animateCamera(CameraUpdateFactory.newLatLng(latLng))
val mo = MarkerOptions()
mo.title("Distance")
val results = FloatArray(10)
Location.distanceBetween(
latitude,
longitude,
end_latitude,
end_longitude,
results
)
val s =
String.format("%.1f", results[0] / 1000)
//Setting marker to draw route between these two points
origin = MarkerOptions().position(LatLng(latitude, longitude))
.title("HSR Layout").snippet("origin")
destination =
MarkerOptions().position(LatLng(end_latitude, end_longitude))
.title(tf_location.text.toString())
.snippet("Distance = $s KM")
mMap!!.addMarker(destination)
mMap!!.addMarker(origin)
Toast.makeText(
this@MainActivity,
"Distance = $s KM",
Toast.LENGTH_SHORT
) .show()
tvCurrentAddress!!.setText("Distance = $s KM")
//getting URL to the google Directions API
val url: String=
getDirectionsUrl(origin!!.getPosition(), destination!!.getPosition())!!
val downloadTask: DownloadTask = DownloadTask()
//start downloading the json data from google directions API
downloadTask.execute(url)
}
}
}
}
@Throws(IOException::class)
private fun downloadUrl(strUrl: String) : String?{
var data = ""
var iStream: InputStream? = null
var urlConnection: HttpURLConnection? = null
try{
val url = URL(strUrl)
urlConnection = url.openConnection() as HttpURLConnection
urlConnection.connect()
iStream = urlConnection!!.inputStream
val br =
BufferedReader(InputStreamReader(iStream))
val sb = StringBuffer()
var line: String? = ""
while (br.readLine().also { line = it } != null) {
sb.append(line)
}
data = sb.toString()
br.close()
} catch (e: java.lang.Exception) {
Log.d("Exception", e.toString())
} finally {
iStream!!.close()
urlConnection!!.disconnect()
}
return data
}
inner class DownloadTask :
AsyncTask<String?, Void?, String>(){
override fun onPostExecute(result: String) {
super.onPostExecute(result)
val parserTask = ParserTask()
parserTask.execute(result)
}
override fun doInBackground(vararg url: String?): String {
var data = ""
try{
data = downloadUrl(url[0].toString()).toString()
} catch (e: java.lang.Exception) {
Log.d("Background Task", e.toString())
}
return data
}
}
//parsing into JSON format
inner class ParserTask :
AsyncTask<String?, Int?, List<List<HashMap<String, String>>>?> () {
override fun doInBackground(vararg jsonData: String?): List<List<HashMap<String, String>>>? {
val jObject: JSONObject
var routes: List<List<HashMap<String, String>>>? =
null
try {
jObject = JSONObject(jsonData[0])
val parser = DataParser()
routes = parser.parse(jObject)
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
return routes
}
override fun onPostExecute(result: List<List<HashMap<String, String>>>?) {
val points = ArrayList<LatLng?>()
val lineOptions = PolylineOptions()
for (i in result!!.indices) {
val path =
result[i]
for (j in path.indices) {
val point = path[j]
val lat = point["lat"]!!.toDouble()
val lng = point["lng"]!!.toDouble()
val position = LatLng(lat, lng)
points.add(position)
}
lineOptions.addAll(points)
lineOptions.width(8f)
lineOptions.color(Color.RED)
lineOptions.geodesic(true)
}
if (points.size != 0) mMap!!.addPolyline(lineOptions)
}
}
private fun getDirectionsUrl(origin: LatLng, dest: LatLng): String?{
//Origin of route
val str_origin = "origin=" + origin.latitude + "," + origin.longitude
//Destination of Route
val str_destination = "destination" + dest.latitude + "," + dest.longitude
//transportation mode
val mode = "mode=walking"
//building parameters of webservice
val parameters = "$str_origin&$str_destination&$mode"
//output format
val output = "json"
//building the url to the web service
return "https://maps.googleapis.com/maps/api/directions/$output?$parameters&key=AIzaSyCgraKSwPfUIyZLOmEDh_ptAbfRRAj7y1g"
}
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
askPermissionLocation()
var mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY)
if (mapViewBundle == null){
mapViewBundle = Bundle()
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle)
}
mapView.onSaveInstanceState(mapViewBundle)
}
private fun askPermissionLocation(){
askPermission(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
){
getCurrentLocation()
// mapView.getMapAsync(this@MyNavigationActivity)
}
}
private fun askPermission(accessFineLocation: String, accessCoarseLocation: String, function: () -> Unit) {
}
private fun getCurrentLocation() {
fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(this@MainActivity)
try {
@SuppressLint ("MissingPermission")
val location =
fusedLocationProviderClient!!.getLastLocation()
location.addOnCompleteListener(object : OnCompleteListener<Location> {
override fun onComplete(loc: Task<Location>) {
if (loc.isSuccessful) {
val currentLocation = loc.result as Location?
if (currentLocation != null) {
moveCamera(
LatLng(currentLocation.latitude, currentLocation.longitude),
DEFAULT_ZOOM
)
latitude = currentLocation.latitude
longitude = currentLocation.longitude
}
} else {
askPermissionLocation()
}
}
})
} catch (se: Exception) {
Log.e("TAG", "Security Exception")
}
}
private fun moveCamera(latLng: LatLng, zoom: Float) {
// mMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom))
}
// override fun onLocationChanged(location: Location?) {
// val geocoder = Geocoder (this, Locale.getDefault())
// var addresses: List<Address>? = null
// try {
// addresses = geocoder.getFromLocation(location!!.latitude, location.longitude, 1)
// } catch (e: IOException) {
// e.printStackTrace()
// }
// setAddress(addresses!![0])
// }
//
// private fun setAddress(addresses: Address) {
// if (addresses != null) {
//
// if (addresses.getAddressLine(0) != null) {
// tvCurrentAddress!!.setText(addresses.getAddressLine(0))
// }
// if (addresses.getAddressLine(1) != null) {
// tvCurrentAddress!!.setText(
// tvCurrentAddress.getText().toString() + addresses.getAddressLine(1)
// )
// }
// }
// }
//
//
//
// override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {
//
// }
//
// override fun onProviderEnabled(p0: String?) {
//
// }
//
// override fun onProviderDisabled(p0: String?) {
//
// }
//
// override fun onCameraMove() {
//
// }
//
// override fun onCameraMoveStarted(p0: Int) {
//
// }
//
// override fun onCameraIdle() {
// var addresses: List<Address>? = null
// val geocoder = Geocoder (this, Locale.getDefault())
// try {
// addresses = geocoder.getFromLocation( mMap!!.getCameraPosition().target.latitude, mMap!!.getCameraPosition().target.longitude, 1)
//
// setAddress(addresses!![0])
//
// } catch (e: IndexOutOfBoundsException) {
// e.printStackTrace()
// } catch (e: IOException) {
// e.printStackTrace()
// }
// }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以轻松地使用Coroutines来做到这一点。我无法在我这边执行您的代码,但我试图将其转换为Coroutine。
请注意,我正在使用GlobalsCope,如果您将添加此代码,则必须使用其他相关范围。您可以创建自定义范围。
You can do this easily with coroutines. I cannot execute you code on my side but i tried to converted it into Coroutine.
Please note here i am using GLobalScope you must need to use other relevant scope if this code you will add in Activity you can create custom scope.