374

我有这两个课。我的主要活动和扩展的AsyncTask活动,现在在我的主要活动中,我需要OnPostExecute()AsyncTask. 如何将结果传递或获取到我的主要活动?

这是示例代码。

我的主要活动。

public class MainActivity extends Activity{

    AasyncTask asyncTask = new AasyncTask();

    @Override
    public void onCreate(Bundle aBundle) {
        super.onCreate(aBundle);            

        //Calling the AsyncTask class to start to execute.  
        asyncTask.execute(a.targetServer); 

        //Creating a TextView.
        TextView displayUI = asyncTask.dataDisplay;
        displayUI = new TextView(this);
        this.setContentView(tTextView); 
    }

}

这是 AsyncTask 类

public class AasyncTask extends AsyncTask<String, Void, String> {

TextView dataDisplay; //store the data  
String soapAction = "http://sample.com"; //SOAPAction header line. 
String targetServer = "https://sampletargeturl.com"; //Target Server.

//SOAP Request.
String soapRequest = "<sample XML request>";    



@Override
protected String doInBackground(String... string) {

String responseStorage = null; //storage of the response

try {


    //Uses URL and HttpURLConnection for server connection. 
    URL targetURL = new URL(targetServer);
    HttpURLConnection httpCon = (HttpURLConnection) targetURL.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setDoInput(true);
    httpCon.setUseCaches(false); 
    httpCon.setChunkedStreamingMode(0);

    //properties of SOAPAction header
    httpCon.addRequestProperty("SOAPAction", soapAction);
    httpCon.addRequestProperty("Content-Type", "text/xml; charset=utf-8"); 
    httpCon.addRequestProperty("Content-Length", "" + soapRequest.length());
    httpCon.setRequestMethod(HttpPost.METHOD_NAME);


    //sending request to the server.
    OutputStream outputStream = httpCon.getOutputStream(); 
    Writer writer = new OutputStreamWriter(outputStream);
    writer.write(soapRequest);
    writer.flush();
    writer.close();


    //getting the response from the server
    InputStream inputStream = httpCon.getInputStream(); 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(50);

    int intResponse = httpCon.getResponseCode();

    while ((intResponse = bufferedReader.read()) != -1) {
        byteArrayBuffer.append(intResponse);
    }

    responseStorage = new String(byteArrayBuffer.toByteArray()); 

    } catch (Exception aException) {
    responseStorage = aException.getMessage(); 
    }
    return responseStorage;
}

protected void onPostExecute(String result) {

    aTextView.setText(result);

}       

}   
4

17 回答 17

774

简单的:

  1. 创建interface类,其中String output是可选的,或者可以是您想要返回的任何变量。

     public interface AsyncResponse {
         void processFinish(String output);
     }
    
  2. 转到您的AsyncTask班级,并将接口声明AsyncResponse为字段:

     public class MyAsyncTask extends AsyncTask<Void, Void, String> {
       public AsyncResponse delegate = null;
    
         @Override
         protected void onPostExecute(String result) {
           delegate.processFinish(result);
         }
      }
    
  3. 在您的主要活动中,您需要implements接口AsyncResponse

     public class MainActivity implements AsyncResponse{
       MyAsyncTask asyncTask =new MyAsyncTask();
    
       @Override
       public void onCreate(Bundle savedInstanceState) {
    
          //this to set delegate/listener back to this class
          asyncTask.delegate = this;
    
          //execute the async task 
          asyncTask.execute();
       }
    
       //this override the implemented method from asyncTask
       @Override
       void processFinish(String output){
          //Here you will receive the result fired from async class 
          //of onPostExecute(result) method.
        }
      }
    

更新

我不知道这是你们许多人的最爱。所以这里是简单方便的使用方式interface

仍在使用相同interface的 . 仅供参考,您可以将其结合到AsyncTask课堂中。

AsyncTask课堂上:

public class MyAsyncTask extends AsyncTask<Void, Void, String> {

  // you may separate this or combined to caller class.
  public interface AsyncResponse {
        void processFinish(String output);
  }

  public AsyncResponse delegate = null;

    public MyAsyncTask(AsyncResponse delegate){
        this.delegate = delegate;
    }

    @Override
    protected void onPostExecute(String result) {
      delegate.processFinish(result);
    }
}

在你的Activity课堂上做这个

public class MainActivity extends Activity {
  
   MyAsyncTask asyncTask = new MyAsyncTask(new AsyncResponse(){
    
     @Override
     void processFinish(String output){
     //Here you will receive the result fired from async class 
     //of onPostExecute(result) method.
     }
  }).execute();

 }

或者,再次在Activity上实现接口

public class MainActivity extends Activity 
    implements AsyncResponse{
      
    @Override
    public void onCreate(Bundle savedInstanceState) {

        //execute the async task 
        new MyAsyncTask(this).execute();
    }
      
    //this override the implemented method from AsyncResponse
    @Override
    void processFinish(String output){
        //Here you will receive the result fired from async class 
        //of onPostExecute(result) method.
    }
}

上面有两种解决方案,第一种和第三种,需要创建方法processFinish,另一种,方法在调用者参数里面。第三个更整洁,因为没有嵌套的匿名类。

提示:将 、 和 更改String outputString response不同String result的匹配类型以获得不同的对象。

于 2012-09-25T02:08:04.227 回答
25

有几个选项:

  • 将课程嵌套AsyncTask在您的Activity课程中。假设您不在多个活动中使用相同的任务,这是最简单的方法。您的所有代码都保持不变,您只需将现有任务类移动为活动类中的嵌套类。

    public class MyActivity extends Activity {
        // existing Activity code
        ...
    
        private class MyAsyncTask extends AsyncTask<String, Void, String> {
            // existing AsyncTask code
            ...
        }
    }
    
  • 为您创建一个自定义构造函数,该构造函数AsyncTask引用您的Activity. 你会用类似的东西来实例化任务new MyAsyncTask(this).execute(param1, param2)

    public class MyAsyncTask extends AsyncTask<String, Void, String> {
        private Activity activity;
    
        public MyAsyncTask(Activity activity) {
            this.activity = activity;
        }
    
        // existing AsyncTask code
        ...
    }
    
于 2012-09-25T01:35:01.000 回答
19

我觉得下面的方法很简单。

我已经声明了一个回调接口

public interface AsyncResponse {
    void processFinish(Object output);
}

然后创建异步任务来响应所有类型的并行请求

 public class MyAsyncTask extends AsyncTask<Object, Object, Object> {

    public AsyncResponse delegate = null;//Call back interface

    public MyAsyncTask(AsyncResponse asyncResponse) {
        delegate = asyncResponse;//Assigning call back interfacethrough constructor
    }

    @Override
    protected Object doInBackground(Object... params) {

      //My Background tasks are written here

      return {resutl Object}

    }

    @Override
    protected void onPostExecute(Object result) {
        delegate.processFinish(result);
    }

}

然后在活动类中单击按钮时调用异步任务。

public class MainActivity extends Activity{

    @Override
    public void onCreate(Bundle savedInstanceState) {

    Button mbtnPress = (Button) findViewById(R.id.btnPress);

    mbtnPress.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                MyAsyncTask asyncTask =new MyAsyncTask(new AsyncResponse() {

                    @Override
                    public void processFinish(Object output) {
                        Log.d("Response From Asynchronous task:", (String) output);

                        mbtnPress.setText((String) output);
                   }
                });

                asyncTask.execute(new Object[] { "Your request to aynchronous task class is giving here.." });


            }
        });

    }



}

谢谢

于 2015-02-14T07:39:03.787 回答
18

您可以在 Main 类中尝试此代码。这对我有用,但我已经以其他方式实现了方法

try {
    String receivedData = new AsyncTask().execute("http://yourdomain.com/yourscript.php").get();
} 
catch (ExecutionException | InterruptedException ei) {
    ei.printStackTrace();
}
于 2015-05-27T14:23:41.697 回答
17

这个答案可能会迟到,但是当您Activity依赖AsyncTask. 这将帮助您防止崩溃和内存管理。正如上面答案中已经提到的那样interface,我们也说它们是回调。他们将充当告密者,但在这些情况下永远不会发送引用Activityinterface总是使用弱引用。

请参阅下面的屏幕截图以了解这如何导致问题。

在此处输入图像描述

正如你所看到的,如果我们从AsyncTask一个引用开始,那么在我们获得数据之前不能保证我们的Activity/Fragment会一直存在,所以WeakReference在这些情况下使用会更好,这也将有助于内存管理,因为我们永远不会持有我们的强引用Activity那么它将在其失真后有资格进行垃圾收集。

检查下面的代码片段以了解如何使用很棒的 WeakReference -

MyTaskInformer.java将作为告密者工作的接口。

public interface MyTaskInformer {

    void onTaskDone(String output);

}

MySmallAsyncTask.javaAsyncTask 执行长时间运行的任务,它将使用WeakReference.

public class MySmallAsyncTask extends AsyncTask<String, Void, String> {

    // ***** Hold weak reference *****
    private WeakReference<MyTaskInformer> mCallBack;

    public MySmallAsyncTask(MyTaskInformer callback) {
        this.mCallBack = new WeakReference<>(callback);
    }

    @Override
    protected String doInBackground(String... params) {

        // Here do whatever your task is like reading/writing file
        // or read data from your server or any other heavy task

        // Let us suppose here you get response, just return it
        final String output = "Any out, mine is just demo output";

        // Return it from here to post execute
        return output;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        // Here you can't guarantee that Activity/Fragment is alive who started this AsyncTask

        // Make sure your caller is active

        final MyTaskInformer callBack = mCallBack.get();

        if(callBack != null) {
            callBack.onTaskDone(s);
        }
    }
}

MainActivity.java此类用于在此类和此强制方法上启动我的AsyncTask实现。interfaceoverride

public class MainActivity extends Activity implements MyTaskInformer {

    private TextView mMyTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mMyTextView = (TextView) findViewById(R.id.tv_text_view);

        // Start your AsyncTask and pass reference of MyTaskInformer in constructor
        new MySmallAsyncTask(this).execute();
    }

    @Override
    public void onTaskDone(String output) {

        // Here you will receive output only if your Activity is alive.
        // no need to add checks like if(!isFinishing())

        mMyTextView.setText(output);
    }
}
于 2017-08-04T07:36:35.100 回答
7

您可以在几行中完成,只需在调用 AsyncTask 时覆盖 onPostExecute。这是一个例子:

new AasyncTask()
{
    @Override public void onPostExecute(String result)
    {
       // do whatever you want with result 
    }
}.execute(a.targetServer);

我希望它对你有帮助,快乐编码:)

于 2015-03-17T16:00:41.143 回答
6

在您的 Oncreate() 中:

`

myTask.execute("url");
String result = "";
try {
      result = myTask.get().toString();
} catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
}catch (ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();

}`

于 2014-05-30T14:43:46.063 回答
4

您可以调用(或重载的)的get()方法。此方法将阻塞,直到完成其工作,此时它将返回您的.AsyncTaskget(long, TimeUnit)AsyncTaskResult

在异步任务的创建/启动和调用方法之间做其他工作是明智的get,否则你不能非常有效地利用异步任务。

于 2012-09-25T01:30:03.820 回答
4

人为什么那么难。

这应该足够了。

不要在异步任务上实现 onPostExecute,而是在 Activity 上实现:

public class MainActivity extends Activity 
{

@Override
public void onCreate(Bundle savedInstanceState) {

    //execute the async task 
    MyAsyncTask task = new MyAsyncTask(){
            protected void onPostExecute(String result) {
                //Do your thing
            }       

    }

    task.execute("Param");

}


}
于 2017-07-26T19:12:04.083 回答
3

您可以编写自己的侦听器。这与HelmiB的答案相同,但看起来更自然:

创建监听接口:

public interface myAsyncTaskCompletedListener {
    void onMyAsynTaskCompleted(int responseCode, String result);
}

然后编写你的异步任务:

public class myAsyncTask extends AsyncTask<String, Void, String> {

    private myAsyncTaskCompletedListener listener;
    private int responseCode = 0;

    public myAsyncTask() {
    }

    public myAsyncTask(myAsyncTaskCompletedListener listener, int responseCode) {
        this.listener = listener;
        this.responseCode = responseCode;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }


    @Override
    protected String doInBackground(String... params) {
        String result;
        String param = (params.length == 0) ? null : params[0];
        if (param != null) {
            // Do some background jobs, like httprequest...
            return result;
        }
        return null;
    }

    @Override
    protected void onPostExecute(String finalResult) {
        super.onPostExecute(finalResult);
        if (!isCancelled()) {
            if (listener != null) {
                listener.onMyAsynTaskCompleted(responseCode, finalResult);
            }
        }
    }
}

最后在活动中实现监听器:

public class MainActivity extends AppCompatActivity implements myAsyncTaskCompletedListener {

    @Override
    public void onMyAsynTaskCompleted(int responseCode, String result) {

        switch (responseCode) {
            case TASK_CODE_ONE: 
                // Do something for CODE_ONE
                break;
            case TASK_CODE_TWO:
                // Do something for CODE_TWO
                break;
            default: 
                // Show some error code
        }        
    }

这就是调用 asyncTask 的方式:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Some other codes...
        new myAsyncTask(this,TASK_CODE_ONE).execute("Data for background job");
        // And some another codes...
}
于 2016-10-16T20:51:42.077 回答
2

嗨,你可以做这样的事情:

  1. 创建实现 AsyncTask 的类

    // TASK 
    public class SomeClass extends AsyncTask<Void, Void, String>>
    {
    
        private OnTaskExecutionFinished _task_finished_event;
    
        public interface OnTaskExecutionFinished
        {
            public void OnTaskFihishedEvent(String Reslut);
        }
    
        public void setOnTaskFinishedEvent(OnTaskExecutionFinished _event)
        {
            if(_event != null)
            {
                this._task_finished_event = _event;
            }
        }
    
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
    
        }
    
        @Override
        protected String doInBackground(Void... params)
        {
            // do your background task here ...
    
            return "Done!";
        }
    
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            if(this._task_finished_event != null)
            {
                this._task_finished_event.OnTaskFihishedEvent(result);
            }
            else
            {
                Log.d("SomeClass", "task_finished even is null");
            }
        }
    }
    
  2. 添加主活动

    // MAIN ACTIVITY
    public class MyActivity extends ListActivity
    {
       ...
        SomeClass _some_class = new SomeClass();
        _someclass.setOnTaskFinishedEvent(new _some_class.OnTaskExecutionFinished()
        {
        @Override
        public void OnTaskFihishedEvent(String result)
        {
            Toast.makeText(getApplicationContext(),
                    "Phony thread finished: " + result,
                    Toast.LENGTH_SHORT).show();
        }
    
       });
       _some_class.execute();
       ...
     }
    
于 2014-07-23T08:29:48.443 回答
1

在 Activity 类中创建一个静态成员。然后在onPostExecute

例如,如果 AsyncTask 的结果是一个字符串,则在 Activity 中创建一个公共静态字符串

public static String dataFromAsyncTask;

然后,在onPostExecuteAsyncTask 中,只需对主类进行静态调用并设置值。

MainActivity.dataFromAsyncTask = "result blah";

于 2012-09-25T01:38:08.873 回答
0

我通过使用线程和处理程序/消息使其工作。步骤如下: 声明进度对话框

ProgressDialog loadingdialog;

创建一个函数以在操作完成时关闭对话框。

   private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        loadingdialog.dismiss();

    }
    };

编码你的执行细节:

 public void startUpload(String filepath) {
    loadingdialog = ProgressDialog.show(MainActivity.this, "Uploading", "Uploading Please Wait", true);
    final String _path = filepath;
    new Thread() {
        public void run() {
            try {
                UploadFile(_path, getHostName(), getPortNo());
                handler.sendEmptyMessage(0);

            } catch (Exception e) {
                Log.e("threadmessage", e.getMessage());
            }
        }
    }.start();
}
于 2016-10-09T13:37:06.227 回答
0

您需要使用“协议”来委托或提供数据给AsynTask.

代表和数据源

委托是一个对象,当该对象遇到程序中的事件时,该对象代表另一个对象或与该对象协作。(苹果定义

协议是定义一些方法来委托某些行为的接口。

这是一个完整的例子!!!

于 2018-04-26T15:36:00.220 回答
0

试试这个:

public class SomAsyncTask extends AsyncTask<String, Integer, JSONObject> {

    private CallBack callBack;

    public interface CallBack {
        void async( JSONObject jsonResult );
        void sync( JSONObject jsonResult );
        void progress( Integer... status );
        void cancel();
    }

    public SomAsyncTask(CallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected JSONObject doInBackground(String... strings) {

        JSONObject dataJson = null;

        //TODO query, get some dataJson

        if(this.callBack != null)
            this.callBack.async( dataJson );// asynchronize with MAIN LOOP THREAD

        return dataJson;

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);

        if(this.callBack != null)
            this.callBack.progress(values);// synchronize with MAIN LOOP THREAD

    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        super.onPostExecute(jsonObject);

        if(this.callBack != null)
            this.callBack.sync(jsonObject);// synchronize with MAIN LOOP THREAD
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();

        if(this.callBack != null)
            this.callBack.cancel();

    }
}

以及用法示例:

public void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         final Context _localContext = getContext();
         SomeAsyncTask.CallBack someCallBack = new SomeAsyncTask.CallBack() {

                @Override
                public void async(JSONObject jsonResult) {//async thread
                    //some async process, e.g. send data to server...
                }

                @Override
                public void sync(JSONObject jsonResult) {//sync thread
                    //get result...

                    //get some resource of Activity variable...
                    Resources resources = _localContext.getResources();
                }

                @Override
                public void progress(Integer... status) {//sync thread
                    //e.g. change status progress bar...
                }

                @Override
                public void cancel() {

                }

            };

            new SomeAsyncTask( someCallBack )
                                .execute("someParams0", "someParams1", "someParams2");

    }
于 2018-12-19T10:07:56.807 回答
0

可能有点过火了,但我为执行代码和结果提供了回调。显然,为了线程安全,您要小心在执行回调中访问的内容。

AsyncTask 实现:

public class AsyncDbCall<ExecuteType,ResultType> extends AsyncTask<ExecuteType, Void,  
ResultType>
{
    public interface ExecuteCallback<E, R>
    {
        public R execute(E executeInput);
    }
    public interface PostExecuteCallback<R>
    {
        public void finish(R result);
    }

    private PostExecuteCallback<ResultType> _resultCallback = null;
    private ExecuteCallback<ExecuteType,ResultType> _executeCallback = null;


    AsyncDbCall(ExecuteCallback<ExecuteType,ResultType> executeCallback, PostExecuteCallback<ResultType> postExecuteCallback)
    {
        _resultCallback = postExecuteCallback;
        _executeCallback = executeCallback;
    }

    AsyncDbCall(ExecuteCallback<ExecuteType,ResultType> executeCallback)
    {
        _executeCallback = executeCallback;
    }

    @Override
    protected ResultType doInBackground(final ExecuteType... params)
    {
        return  _executeCallback.execute(params[0]);
    }

    @Override
    protected void onPostExecute(ResultType result)
    {
        if(_resultCallback != null)
            _resultCallback.finish(result);
    }
}

回调:

 AsyncDbCall.ExecuteCallback<Device, Device> updateDeviceCallback = new 
 AsyncDbCall.ExecuteCallback<Device, Device>()
    {
        @Override
        public Device execute(Device device)
        {
            deviceDao.updateDevice(device);
            return device;
        }
    };

最后执行异步任务:

 new AsyncDbCall<>(addDeviceCallback, resultCallback).execute(device);
于 2019-02-18T01:52:32.250 回答
0

希望你经历过这个,如果没有,请阅读。

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

根据结果​​数据的性质,您应该选择您能想到的最佳选项。

使用接口是一个很好的选择

其他一些选择是..

  • 如果 AsyncTask 类是在您要在其中使用结果的类中定义的。使用静态全局变量或 get() ,请从外部类中使用它(必要时使用volatile 变量)。但应该知道 AsyncTask 的进度,或者至少应该确保它已经完成了任务并且结果可以通过全局变量 / get() 方法获得。您可以使用 轮询、onProgressUpdate(Progress...)、同步或接口(哪个最适合您)

  • 如果 Result 与 sharedPreference 条目兼容,或者可以作为文件保存在内存中,您甚至可以从后台任务本身保存它,并且可以使用onPostExecute()方法
    在结果可用时收到通知记忆。

  • 如果字符串足够小,并且要与活动的开始一起使用。可以在 onPostExecute() 中使用意图 ( putExtra() ) 记住 ,静态上下文 处理起来并不安全。

  • 如果可能,您可以从 onPostExecute() 方法调用静态方法,结果是您的参数

于 2019-12-09T22:00:36.767 回答