package com.testasyntextview;
/**
* 把獲取的線程寫到方法中(比較好)
*/
import android.app.Activity;
import android.app.ProgressDialog;
import android.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 MethodTestAsynTextViewActivity 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, "獲取數據中", "等待");
getHtmlDate();
}
};
private void getHtmlDate() {// 獲取數據,把線程寫入了其中
new Thread() {
public void run() {
Message msg = myHandler.obtainMessage();
try {
html = HttpUtil.fromHtml(HttpUtil
.getHtml("http://wap.sina.com"));
msg.what = 0;
} catch (Exception e) {
e.printStackTrace();
msg.what = 1;
}
myHandler.sendMessage(msg);
}
}.start();
}
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);
}
};
}
package com.testasyntextview;
/**
* 使用AsyncTask類
*/
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class TestAsynTextViewActivity 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;
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("進度條");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
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) {
new InitTask().execute("http://wap.sina.com",
"http://wap.baidu.com");
}
};
private void getHtmlDate(String url) {// 獲取數據,把線程寫入了其中
try {
html = HttpUtil.fromHtml(HttpUtil.getHtml(url));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* When an asynchronous task is executed, the task goes through 4 steps:
*
* onPreExecute(),
* invoked on the UI thread immediately after the task is
* executed. This step is normally used to setup the task, for instance by
* showing a progress bar in the user interface.
*
* doInBackground(Params...),
* invoked on the background thread immediately after onPreExecute()
* finishes executing. This step is used to perform background computation
* that can take a long time. The parameters of the asynchronous task are
* passed to this step. The result of the computation must be returned by
* this step and will be passed back to the last step. This step can also
* use
*
* publishProgress(Progress...) to publish one or more units of
* progress. These values are published on the UI thread, in the
*
* onProgressUpdate(Progress...) step. onProgressUpdate(Progress...),
* invoked on the UI thread after a call to publishProgress(Progress...).
* The timing of the execution is undefined. This method is used to display
* any form of progress in the user interface while the background
* computation is still executing. For instance, it can be used to animate a
* progress bar or show logs in a text field. onPostExecute(Result), invoked
* on the UI thread after the background computation finishes. The result of
* the background computation is passed to this step as a parameter.
*/
class InitTask extends AsyncTask<String, Integer, Long> {
protected void onPreExecute() {
progressDialog.show();
super.onPreExecute();
}
protected Long doInBackground(String... params) {// Long是結果 String 是入口參數
getHtmlDate(params[0]);// 可以運行兩個任務
publishProgress(50);// 發送進度50%
getHtmlDate(params[1]);
publishProgress(100);// 發送進度100%
return (long) 1;
}
@Override
protected void onProgressUpdate(Integer... progress) {
progressDialog.setProgress(progress[0]);// 設置進度
super.onProgressUpdate(progress);
Log.e("測試", progress[0] + "");
}
@Override
protected void onPostExecute(Long result) {
setTitle(result + "測試");
textView1.setText(html);
progressDialog.dismiss();
super.onPostExecute(result);
}
}
}
package com.testasyntextview;
/**
* 使用Runable
*/
import android.app.Activity;
import android.app.ProgressDialog;
import android.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);
}
};
}
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() {
@Override
public Drawable getDrawable(String source) {
InputStream is = null;
try {
is = (InputStream) new URL(source).getContent();
Drawable d = Drawable.createFromStream(is, "src");
d.setBounds(0, 0, d.getIntrinsicWidth(),
d.getIntrinsicHeight());
is.close();
return d;
} catch (Exception e) {
return null;
}
}
}, null);
return sp;
}
}