因为UI只能在主线程里更新,那在子线程中怎么事实更新呢?
一个简便的方法就是用Message的消息传递机制。
需要注意的是,Message导入的包一定要是android.os.Message,而不能是另外两个:
import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.TextView; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class MainActivity extends Activity { String result = "空"; private TextView textView; private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0x123: textView.setText(result); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.textView); new Thread(new Runnable() { @Override public void run() {
result = "1234"; Message msg = new Message(); msg.what=0x123; Log.v("test_result",result); handler.sendMessage(msg); try{ Thread.sleep(300); }catch (Exception e){ e.printStackTrace(); } } }).start(); } }