java - AsyncTask 显示 WCF 的响应

标签 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());
    }


}

在代码中,我将响应写入一个字符串,并尝试在执行后显示它。对于某些回声,当我运行程序时,我没有得到响应,我得到一个空白的 TextView,但消息显示在 Eclipse LogCat 中。我找不到问题,是什么原因造成的?

最佳答案

AsyncTask 与启动它的 Activity 相关联。如果旋转设备或应用程序进入后台、添加到扩展坞或从扩展坞中删除,则原始 Activity 将被破坏。但 AsyncTask 仍会继续并响应不再可见的原始 Activity 。

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

关于java - AsyncTask 显示 WCF 的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24918974/

相关文章:

Android - 如何为具有自定义适配器的 GridView 中的第一个项目添加背景图像?

java - okhttp中的多个连接websocket

java - ArrayList 实现在 Java 中的最低级别是如何工作的?

java - 通过 ExecutorCompletionService 中的 Callable 获取 Future

java - 使用 lambda 将对象列表转换为 Guava Table 数据结构

c# - 命名空间 'System' 中无法识别 System.DirectoryServices

c# - 我应该如何调用与我的主应用程序一起分发的 .NET exe

c# - 关闭表单时如何关闭所有打开的 MessageBoxes

java - 0 和 0. 在 Java 中有什么区别?

android - 如何添加“保存到手机谷歌”按钮并通过 xamarin 移动应用添加支付通行证