Android httpGet 使用 以及使用Handler异步更新textview的text值

来源:互联网 发布:数据备份厂商 编辑:程序博客网 时间:2024/05/04 12:05


在 Activity中定义3个属性

private Handler handler; //实现异步更新textview值private String result;//保存get返回的字符串private TextView text;//textview控件


初始化属性值

//初始化的时候代码要在 onCreate方法中初始化 不能在子线程中
handler = new Handler(); 
text = (TextView) findViewById(R.id.text);

源代码:

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);handler = new Handler();text = (TextView) findViewById(R.id.text);new Thread() {public void run() {String str = "http://www.hbecoop.com/index.html";HttpResponse httpResponse = null;HttpGet get = new HttpGet(str);try {httpResponse = (new DefaultHttpClient()).execute(get);} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {try {result = EntityUtils.toString(httpResponse.getEntity());handler.post(new Runnable() {@Overridepublic void run() {text.setText(result);}});} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}}.start();}}


备注:

需要注意几点 

1:需要在xml中添加网络访问权限   <uses-permission android:name="android.permission.INTERNET" />

2:如果httpget直接在主线程里面使用有可能会抛出异常,导致程序崩溃  建议使用异步的形式来获取资源


原创粉丝点击