簡體   English   中英

Android中具有返回接口的AsyncTask

[英]AsyncTask in Android with return interface

我在android中使用AsyncTask向服務器發出請求,然后將數據重新接收到另一個類。 我知道AsyncTask不會返回任何內容,因此我使用了其他人編寫的代碼來通過接口返回字符串。

這里有AsyncTask類代碼:

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

//Data
public String mFileContents = "false";

//API-Info
public WebRequestResponse delegate = null;

public WebRequest(WebRequestResponse asyncResponse) {
    delegate = asyncResponse;//Assigning call back interfacethrough constructor
}


@Override
protected String doInBackground(String... params) {
    mFileContents = downloadFile(params[0]);
    if(mFileContents == null) {
        Log.d("DownloadData", "Error Downloading");
    }
    return mFileContents;
}

protected void oonPostExecute(String result) {
    super.onPostExecute(result);
    delegate.processFinish(mFileContents);
    Log.d("DownloadData", "Result was: " + result); //result
}

private String downloadFile(String urlPath) {
    StringBuilder tempBuffer = new StringBuilder();
    try {
        URL url = new URL(urlPath);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();
        Log.d("DownloadData", "The response code was " + response);
        InputStream is  = connection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        int charRead;
        char[] inputBuffer = new char[500];
        while(true){
            charRead = isr.read(inputBuffer);
            if(charRead <=0) {
                break;
            }
            tempBuffer.append(String.copyValueOf(inputBuffer, 0, charRead));
        }

        return tempBuffer.toString();

    } catch(IOException e) {
        Log.d("DownloadData", "IO Exception reading data: " + e.getMessage());
        e.printStackTrace();
    } catch(SecurityException e) {
        Log.d("DownloadData", "Security exception. Needs permissions? " + e.getMessage());
    }
    return null;
}

}

現在,界面:

public interface WebRequestResponse {
void processFinish(String output);
}

在同步類中,我有這個:

public class API implements WebRequestResponse {

我將執行如下:

    public static void StartRequest(String url) {
    String response = null;
    WebRequest Request = new WebRequest(new WebRequestResponse() {

        @Override
        public void processFinish(String output) {
            Test(output); //Testing the response code
        }
    });
    Request.execute(url);
}

問題在於代碼永遠不會被調用,也永遠不會返回任何東西。 使用Log.d,我發現這里沒有任何作用:“ delegate.processFinish(mFileContents);” 在AsyncTask類中分配。 我究竟做錯了什么?

謝謝

多虧了Rucsi,我發現我在寫DoublePost的onPostExecute時

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM