2017-07-06 39 views
0

我需要一些幫助來弄清楚如何在AsyncTask中返回doInBackground()值,哪個代碼是一個接口。下面是一個例子AsyncTask:從doInBackground中的接口回調返回

  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的用法,但我意識到,通過你的答案是不。所以我完成了代碼以添加更多細節。

有什麼想法嗎? 預先感謝您。

+0

你爲什麼要'myInterface'? –

+1

doInBackground方法內創建的「myInterface」實例未使用 –

+1

它也不起作用,因爲您只是創建myInterface的實例。沒有代碼運行。什麼是myInerface的puropose?你爲什麼試圖使用AsyncTask?它可能不是您的問題的好辦法。 –

回答

0
  1. 在你執行AsyncTask的地方創建Mynterface的對象。

  2. AsyncTask裏面創建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 
    
    
          } 
        } 
    

    `

使用它就像...

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

在地方實現接口的正在執行。

這個你怎麼做到的。

+0

通常返回doInBackground中的結果並在postExecute中調用接口方法以與調用方進行通信。 – PranavKAndro

相關問題