Handler.post(new Runnable(){})使用

在一个线程中使用Handler.post(new Runnable(){})来跟新一个控件

1、先看activity中的代码

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;

public class MainActivity extends Activity {
	private Handler handler;
	private String Uri = "http://www.baidu.com/";
	private WebView webview;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		webview = (WebView) findViewById(R.id.webView);
		handler=new Handler();
		new HttpURLPost(Uri, handler, webview).start();
	}

}
2、需要的布局文件


    


3、线程中的逻辑(网络权限)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Handler;
import android.util.Log;
import android.webkit.WebView;

public class HttpURLPost extends Thread {
	private String Uri;
	private Handler hander;
	WebView webview;

	public HttpURLPost(String Uri, Handler hander, WebView webview) {
		this.hander = hander;
		this.Uri = Uri;
		this.webview = webview;
	}

	@Override
	public void run() {
		try {
			URL url = new URL(Uri);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(5000);
			conn.setRequestMethod("GET");

			final StringBuffer sb = new StringBuffer();
			String str = new String();
			BufferedReader breader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

			while ((str = breader.readLine()) != null) {
				sb.append(str);
				// 加载成缓存

			}
			//ui线程
			hander.post(new Runnable() {

				@Override
				public void run() {
					Log.i("*******", "post线程已启动");

					webview.loadData(sb.toString(), "text/html;charset=utf-8", null);


				}
			});
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
4、最后注意IO流遇到关闭
 
  

你可能感兴趣的:(Handler.post(new Runnable(){})使用)