Android, can I put AsyncTask in a separate class and have a callback?

前端 未结 3 1031
一整个雨季
一整个雨季 2020-12-03 02:02

I\'m just learning about AsyncTask and want to use it as a separate class, rather then a subclass.

For example,

class inetloader extends AsyncTask&l         


        
相关标签:
3条回答
  • 2020-12-03 02:15
    inetloader il = new inetloader();
    il.execute("http://www.google.com");
    
    String result = il.get();//put it in try-catch
                    ^^^^^^^^ 
    

    here you get result which is in onPostExecute(String result)

    0 讨论(0)
  • 2020-12-03 02:27

    you can pass the activity instance to constructor and call activity function from there...
    Like use interface :

    public interface ResultUpdatable {
    
       public void setResult(Object obj);
       }
    

    Implement this in the Activity and pass in the constructor of Async task and update the result from onPostExecute using setResult function.

    0 讨论(0)
  • 2020-12-03 02:30

    Use a interface. Something like:

    interface CallBackListener{
      public void callback();
    }
    

    Then do this in your UI thread:

    inetloader il = new inetloader();
    li.setListener(this);
    il.execute("http://www.google.com");
    

    In inetloader, add:

       CallBackListener mListener;
    
       public void setListener(CallBackListener listener){
         mListener = listener;
       }
    

    then In postExecute(), do:

       mListener.callback();
    
    0 讨论(0)
提交回复
热议问题