异步加载数据的三种实现(四)

2014-11-24 09:44:18 · 作者: · 浏览: 8
roid.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class RunableTestAsynTextViewActivity extends Activity {
private TextView textView1;
private Button button1;
private Context context;
private ProgressDialog progressDialog;
private Spanned html;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
textView1 = (TextView) findViewById(R.id.textView1);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(l);

}

private OnClickListener l = new OnClickListener() {

@Override
public void onClick(View v) {

progressDialog = ProgressDialog.show(context, "获取数据中", "等待");
new Thread(new ThreadDemo()).start();

}
};

private void getHtmlDate() {
try {
html = HttpUtil.fromHtml(HttpUtil.getHtml("http://wap.sina.com"));
} catch (Exception e) {
e.printStackTrace();
}

}

class ThreadDemo implements Runnable {//一个runable
public void run() {
getHtmlDate();
myHandler.sendEmptyMessage(0);
}
}

Handler myHandler = new Handler() {

public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
textView1.setText(html);
progressDialog.dismiss();
break;
case 1:
textView1.setText("当前无数据");
progressDialog.dismiss();
break;
}
super.handleMessage(msg);
}
};

}
[java]
package com.testasyntextview;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Spanned;

public class HttpUtil {
public static String getHtml(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
InputStream inStream = conn.getInputStream();// 通过输入流获取html数据
byte[] data = readInputStream(inStream);// 得到html的二进制数据
String html = new String(data, "utf-8");
return html;
}

public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}

public static Spanned fromHtml(String html) {
Spanned sp = Html.fromHtml(html, new Html.ImageGetter