2017-03-31 55 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

相关问题