2017-03-31 18 views
0
The following is my example code. 

private class PostLikes extends AsyncTask<Integer, Void, Void> { 
String type_id, msg; 

@Override 
protected Void doInBackground(Integer... params) { 
//.... 
//.... 
    type_id = jsonobject2.getString("type_id"); 
    msg = jsonobject2.getString("msg"); 
    return null; 
} 

@Override 
protected void onPostExecute(Void result) { 
    if (type_id.equals("1")) { 
    Toast.makeText(getApplicationContext(), "error, Toast.LENGTH_SHORT).show(); 
    } else { 
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); 
    } 
} 

} 

使用AsyncTask的標準方法是使doInBackground函數返回一些後臺線程的結果給onPostExecute函數。 該代碼運行良好,但我想知道上述代碼中是否存在任何問題。 謝謝。在Android的AsyncTask的doInBackground和onPostExecute上是否有共享類成員的問題?

回答

1

我相信你確定這是如何設置的。您的成員變量type_idmsgonPostExecute()一樣引用,與其他任何成員變量一樣。 doInBackground()將在onPostExecute()運行時完成,所以不會有線程衝突。

+0

感謝您的回答。如果返回值是多數組(String,int,boolean),我認爲它比使用複雜參數要好。但是我無法在這裏找到這樣的示例代碼。 – bb14816

+0

我想知道您的意見。 – bb14816

+0

從技術上講,文檔指出後臺計算的結果被傳遞給'onPostExecute()'。所以,這就是模式。問題是可讀性和可維護性 - 構造一次性使用結構以滿足模式或使用成員變量?我想無論如何,但我確信意見會有所不同。 – Cheticamp

相關問題