我有一个每10秒调用一次的webservice调用,应该使用webservice回复更新TextView(或者至少每10秒显示一次toast消息)
但是UI根本没有得到更新。
请找到以下代码。
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();
}
}
}
答案 0 :(得分:4)
正如大家所提到的,你在UI线程中进行网络调用并执行Thread.Sleep(),冻结你的UI。
我尝试使用类似AsyncHttpClient的类,它具有您需要的所有功能,您必须在回调中执行UI更新。
答案 1 :(得分: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();
Async Docs Progress Dialog Example
您不想在sleep
主题上执行网络内容或致电UI
。如果它是内部类,那么您将可以访问外部类的成员变量。否则,如果要从AsyncTask
或其他方法besids context
进行更新,请在onPostExecute
类中创建一个传递doInBackground()
的构造函数。