[英]Update UI Asynchronously in Android
我有一個每10秒調用一次的Web服務調用,並且應該使用Web服務回復來更新TextView(或每10秒至少顯示一條祝酒消息)
但是,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();
}
}
}
正如每個人都提到的,您正在UI線程中進行網絡調用,並執行Thread.Sleep()凍結UI。
我會嘗試類似AsyncHttpClient類的東西,它具有您需要的所有功能,您必須在回調中執行UI更新。
這是一個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();
您不想做網絡工作或不想在UI
線程上調用sleep
。 如果它是內部類,那么您將可以訪問外部類的成員變量。 否則,如果要從onPostExecute
或其他方法dosBacks doInBackground()
更新,請在AsyncTask
類中創建構造onPostExecute
以傳遞context
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.