1

我有一个每 10 秒调用一次的 web 服务调用,并且应该使用 web 服务回复更新一个 TextView(或至少每 10 秒显示一条 toast 消息)

但是用户界面根本没有更新。

请在下面找到代码。

public class MessagesRequestActivity extends Activity  {
    /** Called when the activity is first created. */
    String currentMsg="Default";
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //Calling the webservice
        getMessage();
    }
    public void getMessage(){

        try
        {
        SoapObject request = new SoapObject("http://tempuri.org/", "getMessage");

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);

        //Web method call
        HttpTransportSE androidHttpTransport = new HttpTransportSE("http://192.168.4.50/WebService.asmx");
        androidHttpTransport.call("http://tempuri.org/"+ "getMessage", envelope);
        //get the response
        SoapPrimitive response = (SoapPrimitive)envelope.getResponse();

        //the response object can be retrieved by its name: result.getProperty("objectName");
        String message = (String)response.toString();
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();

        }
        catch (Exception e)
        {
        e.printStackTrace();
        }
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
}
4

2 回答 2

4

正如每个人都提到的,您正在 UI 线程中进行网络调用并执行 Thread.Sleep() 冻结您的 UI。

我会尝试这样的 AsyncHttpClient 类,它具有您需要的所有功能,您必须在回调中执行 UI 更新。

http://loopj.com/android-async-http/

于 2013-03-08T16:00:21.203 回答
1

这是一个示例AsyncTask

public class TalkToServer extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);

}

@Override
protected String doInBackground(String... params) {
//do your work here
    return something;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
       // do something with data here-display it or send to mainactivity
}

然后你可以通过调用访问

TalksToServer varName = new TalkToServer(); //pass parameters if you need to the constructor
varName.execute();

异步文档 进度对话框示例

你不想做网络sleep的事情或调用UI线程。如果它是一个内部类,那么您将可以访问外部类的成员变量。否则,如果要更新 from或其他方法,请在AsyncTask类中创建一个构造函数以传递。contextonPostExecutedoInBackground()

于 2013-03-08T16:01:00.357 回答