在一个线程中使用Handler.post(new Runnable(){})来跟新一个控件
1、先看activity中的代码
<span style="font-size:18px;">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();
}
}</span>
<span style="font-size:18px;">2、需要的布局文件</span>
<pre name="code" class="html"><span style="font-size:18px;"><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.imooc.httpurlpost.MainActivity" >
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout></span>
3、线程中的逻辑(网络权限)
<span style="font-size:18px;">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线程已启动");</span>
<span style="font-size:18px;">
webview.loadData(sb.toString(), "text/html;charset=utf-8", null);</span>
<span style="font-size:18px;">
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}</span>
4、最后注意IO流遇到关闭