java-在Android中异步更新UI
作者:互联网
我有一个每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();
}
}
}
解决方法:
这是一个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
您不想做网络工作或不想在UI线程上调用sleep.如果它是内部类,那么您将可以访问外部类的成员变量.否则,如果要从onPostExecute或其他方法dosBacks doInBackground()更新,请在AsyncTask类中创建构造函数以传递上下文.
标签:android-sdk-2-3,android,java 来源: https://codeday.me/bug/20191013/1906279.html