我正在实现一个类,extends AsyncTask
我在这个类中执行一个 http 请求。该类不是一个Activity
并且位于一个单独的 java 文件中,因为我想多次使用这个类。
我在我的 中实例化了这个类的一个对象Activity
,以在单独的线程中执行 http 请求。当线程执行时,我想调用我的Activity
.
我该如何实施?我需要http请求的结果,Activity
但到目前为止我无法处理。
这是线程任务的代码...
public class PostRequest extends AsyncTask<String, Void, String> {
public String result = "";
@Override
protected String doInBackground(String... urls) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://bla/index.php?" + urls[0]);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
// convert response to string
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
}
}
这是我Activity
创建线程类的代码的一部分......
public class ListActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
PostRequest task = new PostRequest();
task.execute(new String[] { "action=getUsers" });
task.onPostExecute(task.result) {
}
}
public void Display(String result) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(0);
String value = json_data.getString("name");
TextView text = (TextView) findViewById(R.id.value);
text.setText(value);
} catch (JSONException e) {
e.printStackTrace();
}
}
}