How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

前端 未结 17 2149
鱼传尺愫
鱼传尺愫 2020-11-21 04:50

I have this two classes. My main Activity and the one that extends the AsyncTask, Now in my main Activity I need to get the result from the OnPostExecute(

17条回答
  •  礼貌的吻别
    2020-11-21 05:22

    Hope you been through this , if not please read.

    https://developer.android.com/reference/android/os/AsyncTask

    Depending on the nature of result data, you should choose best possible option you can think of.

    It is a great choice to use an Interface

    some other options would be..

    • If the AsyncTask class is defined inside the very class you want to use the result in.Use a static global variable or get() , use it from outer class (volatile variable if necessary). but should be aware of the AsyncTask progress or should at least make sure that it have finished the task and result is available through global variable / get() method. you may use polling, onProgressUpdate(Progress...), synchronization or interfaces (Which ever suits best for you)

    • If the Result is compatible to be a sharedPreference entry or it is okay to be saved as a file in the memory you could save it even from the background task itself and could use the onPostExecute() method
      to get notified when the result is available in the memory.

    • If the string is small enough, and is to be used with start of an activity. it is possible to use intents (putExtra()) within onPostExecute() , but remember that static contexts aren't that safe to deal with.

    • If possible, you can call a static method from the onPostExecute() method, with the result being your parameter

提交回复
热议问题