文档章节

异步加载数据的三种实现

SuShine
 SuShine
发布于 2015/06/25 15:28
字数 960
阅读 14
收藏 0
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;

	}
}



本文转载自:http://blog.csdn.net/sfshine/article/details/8050819

共有 人打赏支持
SuShine
粉丝 123
博文 541
码字总数 153477
作品 0
朝阳
后端工程师
私信 提问
Jquery工作常用实例——使用$.post,$.get,$.ajax使网页进行异步更新

AJAX = Asynchronous JavaScript and XML.,是一种创建快速动态网页的技术。 AJAX 通过在后台与服务器交换少量数据的方式,允许网页进行异步更新。这意味着有可能在不重载整个页面的情况下,...

Adam-Lee
2011/07/16
0
1
Android Loader 机制,让你的数据加载更加高效

前言 在 Android 中,任何耗时的操作都不能放在 UI 线程中,所以耗时的操作都需要使用异步加载来实现。其实,加载耗时数据的常用方式其实也挺多的,就让我们来看一下 1、Thread + Handler Th...

developerHaoz
2017/11/27
0
0
使用Webpack的代码分离实现Vue的懒加载(译文)

当一个Vue的项目体积变得十分庞大的时候,使用Webpack的代码分离功能将,或的代码进行分离并按需加载,会极大的提高App的首屏加载速度。 在Vue的项目中,我们可以在三种不同的情况下使用懒加...

Lee_tanghui
08/05
0
0
java做的电子商务网站,首页数据用什么方式加载效率更快。

struts+spring+ibatis+velocity做的电子商务网站,网站首页数据大都是动态读取数据库,用什么方式读取会快一点。 1通常页面取值是循环作用域里的List; 2ajax异步获取数据; 3页面上直接调用读...

zkool
2012/10/22
1K
8
开源中国Android客户端-使用Tab切换Fragment

一、简述 在开源中国客户端中,使用了大量的列表去加载新闻、咨询、博客等等内容,而根据合理的分类,又可以使得这些列表显示的样式保持一致。 说明: 1)、可以左右滑动切换,更方便。 2)、左...

Xushao
2013/07/04
0
2

没有更多内容

加载失败,请刷新页面

加载更多

Spring源码学习笔记-1-Resource

打算补下基础,学习下Spring源码,参考书籍是《Spring源码深度解析》,使用版本是Spring 3.2.x,本来想试图用脑图记录的,发现代码部分不好贴,还是作罢,这里只大略记录下想法,不写太细了 ...

zypy333
8分钟前
0
0
RestClientUtil和ConfigRestClientUtil区别说明

RestClientUtil directly executes the DSL defined in the code. ConfigRestClientUtil gets the DSL defined in the configuration file by the DSL name and executes it. RestClientUtil......

bboss
今天
14
0

中国龙-扬科
昨天
2
0
Linux系统设置全局的默认网络代理

更改全局配置文件/etc/profile all_proxy="all_proxy=socks://rahowviahva.ml:80/"ftp_proxy="ftp_proxy=http://rahowviahva.ml:80/"http_proxy="http_proxy=http://rahowviahva.ml:80/"......

临江仙卜算子
昨天
9
0
java框架学习日志-6(bean作用域和自动装配)

本章补充bean的作用域和自动装配 bean作用域 之前提到可以用scope来设置单例模式 <bean id="type" class="cn.dota2.tpye.Type" scope="singleton"></bean> 除此之外还有几种用法 singleton:......

白话
昨天
9
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部