异步任务(Android)中的多个操作
问题描述:
可以在一个asynctask中拥有多个httpclient吗?在我的代码如下..它检索用户的信息,然后将其显示到一个新的活动..但我也想获得追随者的数量和用户时ProfileAsync执行..我有单独的PHP文件的的用户信息和追随者及以下的号码检索..异步任务(Android)中的多个操作
class ProfileAsync extends AsyncTask<String, String, String>{
private Dialog loadingDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(HomePageActivity.this, "Please wait", "Loading...");
}
@Override
protected String doInBackground(String... params) {
String json=null;
String json2=null;
byte[] data;
StringBuffer buffer = null;
InputStream is = null;
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", uname));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(PROFILE_URL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
Log.e("Profile JSON: ", json.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
@Override
protected void onPostExecute(String json){
super.onPostExecute(json);
loadingDialog.dismiss();
try
{
jsonobject = new JSONObject(json);
jsonarray = jsonobject.getJSONArray("user");
JSONObject jb= jsonarray.getJSONObject(0);
//Username = jb.getString("Username");
Password = jb.getString("Password");
Fullname = jb.getString("Fullname");
Email = jb.getString("Email");
Bio = jb.getString("Bio");
Location = jb.getString("Location");
fn.setText(Fullname);
em.setText(Email);
loc.setText(Location);
b.setText(Bio);
if(json!=null)
{
Intent i = new Intent(HomePageActivity.this,ProfileActivity.class);
i.putExtra(u.username(), u.getUsername());
i.putExtra("password",Password);
i.putExtra("fullname",Fullname);
i.putExtra("email", Email);
i.putExtra("bio", Bio);
i.putExtra("location", Location);
startActivity(i);
finish();
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}//end of profileasynctask
答
是的,你可以发送多个URL作为参数,可以将所有网址将可作为参数数组一样PARAMS [0],则params [1]和你可以通过它循环发送多个请求,但我建议不要在单个AyncTask中执行该操作,因为这需要大量时间,并且如Android Developer指南中所述,AsyncTask应该用于需要工作线程的短操作,您可以在这里阅读 - https://developer.android.com/reference/android/os/AsyncTask.html
如果您想要发送多个请求,请尝试使用着名的网络库(如翻新),或者如果您想使用AsynTask,则为每个请求编写一个单独的任务。