AsyncTask:从doInBackground中的接口回调返回

时间:2017-07-06 13:45:18

标签: android android-asynctask

我需要一些帮助来弄清楚如何在doInBackground()中返回AsyncTask哪个代码是一个接口。这是一个例子

         private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {

                    public MyAsyncTask() {
                        super();
                        // do stuff
                    }

                    @Override
                    protected Boolean doInBackground(Void... void) {

                     checkIfContentAvailable(new interfaceMediaAvailableToDownload() {
                            @Override
                            public void onComplete(boolean resutl) {
                                    return result; //This must be doInBackground return value, not onSuccess which is Void
                            }

                            @Override
                            public void onInternetError() {
                                return false; //This must be doInBackground return value, not onSuccess which is Void
                            }
                        };
                    }

                @Override
                protected void onPostExecute(Boolean result) {
                     if (result){
                        //Do stuff
                     }else{
                        //Do stuff
                     }



                }
        }

显然,上面的代码无效,因为我不知道如何将onSuccess()值返回doInBackground()

我希望这很清楚......

修改

好吧我的不好,我认为隐藏MyInterface的使用会更具可读性,但我知道通过你的答案它不是。所以我完成了代码以添加更多细节。

请问好吗? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

  1. 在执行AsyncTask的位置创建Mynterface的对象。

  2. AsyncTask ans中创建MyInterface的对象引用,设置您的界面对象。

  3. 然后调用onSuccess方法,如下所示

    `
        private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
    
         MyInteface myInterface;
         setMyInterface(MyInterface interface){this.myInterface = interface;}
    
                    public MyAsyncTask() {
                        super();
                        // do stuff
                    }
    
                    @Override
                    protected Boolean doInBackground(Void... void) {
                     this.myInterface.onSuccess(); // or call on failure if failure happened
    
                    }
    
          @Override
                protected void onPostExecute(Boolean result) {
        //Do stuff with result
    
    
                }
        }
    

    `

  4. 像......一样使用

    MyAsyncTask async = new MyAsyncTask();
    async.setMyInterface(this);
    async.execute();
    

    在您正在执行的地方实施界面。

    你可以这样做。