AsyncTask显示响应表单WCF

时间:2014-07-23 19:12:32

标签: java c# android wcf android-asynctask

我写了一个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());
    }


}

在代码中,我将响应写入String,并尝试在执行后显示它。对于一些人来说,当我运行程序时我没有得到响应,我得到一个空白的TextView但消息显示在Eclipse LogCat中。我找不到问题,是什么原因引起的?

1 个答案:

答案 0 :(得分:0)

AsyncTask与踢它的活动联系在一起。如果您旋转设备或应用程序进入后台,添加或从Dock中删除,原始活动将被销毁。 AsyncTask会继续,并响应不再可见的原始活动。

最好使用IntentService或Service调用Web服务,这是一种更可靠的模式。