更新UI异步Android中(Update UI Asynchronously in Android

2019-08-17 10:10发布

我有一个Web服务调用被称为每10秒,应该更新与web服务回复一个TextView(或者至少表现出每10秒举杯消息)

但用户界面是没有得到所有更新。

请从下面的代码。

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

Answer 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线程。 如果它是一个内部类,那么你将有机会获得外部类的成员变量。 否则,创建在一个构造器AsyncTask类传递context ,如果你想从更新onPostExecute或其他方法besids doInBackground()



Answer 2:

正如大家所说,你在UI线程进行网络调用和执行Thread.sleep代码(),它冻结您的UI。

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

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



文章来源: Update UI Asynchronously in Android