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


在 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() {

							@Override
							public void run() {

								text.setText(result);
							}
						});

					} catch (ParseException e) {

						e.printStackTrace();
					} catch (IOException e) {

						e.printStackTrace();
					}

				}
			}

		}.start();

	}
}


备注:

需要注意几点 

1:需要在xml中添加网络访问权限  

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


你可能感兴趣的:(android)