简体   繁体   English

如何知道何时异步任务在android studio中完全完成?

[英]How to know when async task is completely finished in android studio?

Solved: I had a problem with concurrent modification which I thought was due to calling my filter before the task was done, what ended up working for me was adding a call to an outside method in the onPostExecute that copied values to a copyonwritearraylist. 解决了: 我遇到了并发修改的问题,我认为这是由于在完成任务之前调用了过滤器,最终对我有用的是在onPostExecute中添加了对外部方法的调用,该方法将值复制到了copyonwritearraylist中。

So I have an AsyncTask that parses json from a website and initializes a list when its done. 所以我有一个AsyncTask,它解析来自网站的json并在完成时初始化一个列表。

    inner class GetSchoolAsync : AsyncTask<String, String, String>() {
    lateinit var list: MutableList<Info>
    override fun onPreExecute() {
        // Before doInBackground
    }

    override fun doInBackground(vararg urls: String?): String {
        var urlConnection: HttpURLConnection? = null

        try {
            val url = URL(urls[0])

            urlConnection = url.openConnection() as HttpURLConnection
            urlConnection.connectTimeout = CONNECTON_TIMEOUT_MILLISECONDS
            urlConnection.readTimeout = CONNECTON_TIMEOUT_MILLISECONDS

            val inString = urlConnection.inputStream.bufferedReader().readText()

            publishProgress(inString)
        } catch (ex: Exception) {
            println("HttpURLConnection exception" + ex)
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect()
            }
        }

        return " "
    }

    override fun onProgressUpdate(vararg values: String?) {
        try {
            var list = mutableListOf<Info>()
            var data = Gson().fromJson(values[0], Read::class.java)

            for(item in data.schools){
                list.add(item)
               // println(item)
            }
            this.list = list



        } catch (ex: Exception) {
            println("JSON parsing exception" + ex.printStackTrace())
        }
    }

    override fun onPostExecute(result: String?) {
        // Done
        schoolList = this.list

    }
}

It is being executed in the mainactivity OnCreate along with another async function that renders a map. 它在mainActivity OnCreate中与另一个呈现地图的异步函数一起执行。 School list is a private lateinit var in the main activity. 学校名单是主要活动中的私人Lateinit变量。

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps)
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
    GetSchoolAsync().execute("https://code.org/schools.json")
    mapFragment.getMapAsync(this)
}

I need to know when the json part is finished and the list is initialized so that I can add markers to the map. 我需要知道json部分何时完成以及列表是否已初始化,以便可以将标记添加到地图。 Any time I have tried to check the status of the Async task in the debugger its always showing that its either pending or running. 每当我尝试在调试器中检查Async任务的状态时,它总是显示其未决或正在运行。 When can I be certain that its finished? 我什么时候可以确定完成?

You should better to use Interface for your case 您最好为您的案例使用Interface

 interface ReturnListener {
            fun result(result:String)
        }



  inner class GetSchoolAsync : AsyncTask<Object, String, String>() {
    lateinit var list: MutableList<Info>
    override fun onPreExecute() {
        // Before doInBackground
    }

    override fun doInBackground(vararg urls: Object?): String {
        var urlConnection: HttpURLConnection? = null
        var listener: ReturnListener? = null

        try {
            val url = URL(urls[0] as String)
            listener = urls[1] as ReturnListener

            urlConnection = url.openConnection() as HttpURLConnection
            urlConnection.connectTimeout = CONNECTON_TIMEOUT_MILLISECONDS
            urlConnection.readTimeout = CONNECTON_TIMEOUT_MILLISECONDS

            val inString = urlConnection.inputStream.bufferedReader().readText()

            publishProgress(inString)
        } catch (ex: Exception) {
            println("HttpURLConnection exception" + ex)
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect()
            }
        }

        return " "
    }

    override fun onProgressUpdate(vararg values: String?) {
        try {
            var list = mutableListOf<Info>()
            var data = Gson().fromJson(values[0], Read::class.java)

            for(item in data.schools){
                list.add(item)
               // println(item)
            }
            this.list = list



        } catch (ex: Exception) {
            println("JSON parsing exception" + ex.printStackTrace())
        }
    }

    override fun onPostExecute(result: String?) {
        // Done
        schoolList = this.list
     if (listener!=null)
       listener.result(result)

    }

and under OnCreate: 在OnCreate下:

      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_maps)
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        val mapFragment = supportFragmentManager
                .findFragmentById(R.id.map) as SupportMapFragment
        GetSchoolAsync().execute("https://code.org/schools.json", object: ReturnListener{
 override fun result(result:String) {

                 //ToDo: .......

             }
       })
        mapFragment.getMapAsync(this)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM