我编写了一个Restful WCF服务,并将其部署在IIS上。我一直在尝试使用 AsyncTask 线程来使用 WCF 服务。我将线程内置到主 UI 类中,以便可以更新 GUI。
public class ServiceRunning extends AsyncTask<String, Void, String>{
private Exception exception;
String line = "";
public void setLine(String line)
{
this.line = line;
}
public String getLine()
{
return line;
}
@Override
protected String doInBackground(String... url) {
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri = new URI(url[0]);
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json; charset=utf-8");
HttpResponse response = httpClient.execute(httpget);
HttpEntity responseEntity = response.getEntity();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// while ((line = rd.readLine()) != null) {
// Log.d("****Status Line***", "Webservice: " + line);
// }
while((line = rd.readLine()) != null)
{
setLine(line);
Log.d("****Status Line***", "Webservices: " + getLine());
}
}
catch (Exception e)
{
e.printStackTrace();
}
return "String :" + line;
}
protected void onPostExecute(String result) {
TextView txt = (TextView)findViewById(R.id.textView1);
txt.setText(getLine());
}
}
在代码中,我将响应写入一个字符串,并尝试在执行后显示它。对于某些回声,当我运行程序时,我没有得到响应,我得到一个空白的 TextView,但消息显示在 Eclipse LogCat
中。我找不到问题,是什么原因造成的?
最佳答案
AsyncTask 与启动它的 Activity 相关联。如果旋转设备或应用程序进入后台、添加到扩展坞或从扩展坞中删除,则原始 Activity 将被破坏。但 AsyncTask 仍会继续并响应不再可见的原始 Activity 。
您最好使用 IntentService 或 Service 来调用 Web 服务,这是一种更可靠的模式。
关于java - AsyncTask 显示 WCF 的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24918974/