您好我已经创建了一个示例android项目,以了解android如何在后台线程中访问网络任务以及它将如何更新UI线程。 我已经在MainActivity.java
中成功完成了它package com.example.wcfconsumer;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.concurrent.ExecutionException;
import com.example.wcfconsumer.R;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button button;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
try {
getdata();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private void getdata() throws InterruptedException, ExecutionException,
MalformedURLException {
String url = "GetNoPara";
String toaststring = new String("");
// AsyncTask<String, Integer, String> theString;
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(url);
toaststring = ((TextView) findViewById(R.id.text_wcfconsumer_response))
.getText().toString();
Toast.makeText(this, toaststring + "\n", Toast.LENGTH_LONG).show();
}
private class DownloadWebPageTask extends
AsyncTask<String, Integer, String> {
private final static String SERVICE_URI = "http://192.168.0.104:80/Service1.svc/";
protected void onPostExecute(String result) {
((TextView) findViewById(R.id.text_wcfconsumer_response))
.setText(result);
}
@Override
protected String doInBackground(String... params) {
String response = "";
HttpGet httpGet = new HttpGet(SERVICE_URI + params[0].toString());
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
// JSONArray jsaPersons = null ;
// String theString = new String("");
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
}
但我现在正试图这样做,以便我可以调用不同的服务方法,后台结果将返回UI线程,我可以根据项目要求使用结果。我曾想过在不同的文件中定义这个后台任务(比如BackgroundTask.java),但是我不知道如何将结果返回给Main_Activity.java(从那里调用BackgroundTask.execute)?
请帮帮我... 谢谢你的回复。
此致 Sourabh
答案 0 :(得分:1)
我找到了在非UI线程中执行后台任务的方法。为此你必须扩展AsyncTask并且必须实现doInBackground方法。要了解更多AsyncTask,您可以参考android开发者网站。
这是我完成的代码。
public class BackgroundTask extends AsyncTask<Object, Integer, String> {
private final static String SERVICE_URI = "http://192.168.0.105:80/Service1.svc/";
//runs after doInBackground completed
protected void onPostExecute(String result) {
Register_activity.emailV.setText(result);
}
@Override
protected String doInBackground(Object... params) {
Bitmap image = (Bitmap)params[1];
String msg = new String();
String methodname = params[0].toString();
try {
byte[] data = SaveImage.toByteArray(image);
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(SERVICE_URI+methodname);
postRequest.setHeader("Content-type","application/octet-stream");
ByteArrayBody bab = new ByteArrayBody(data, Register_activity.mobileV.getText().toString()+".jpg");
// File file= new File("/mnt/sdcard/forest.png");
// FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded", bab);
reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
System.out.println("Response: " + s);
msg = s.toString();
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
return msg;
}
}
这里AsyncTask有3种数据类型:
Object表示将传递给doInBackground方法的数组数据的类型
整数表示将用于传递到onProgressUpdate方法的数据类型
String表示将用于传递到onPostExecute方法的数据类型
有很多选项可以在NonUI线程上执行任务,比如java thred。选项是你的。
快乐的编码...
问候,
Sourabh