非同期ロードデータの3つの実装


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;

	}
}