public class MainActivity extends Activity {
ListView listView;
File cache;
//访问其他线程在当前线程中存放的数据
Handler handler = new Handler(){
public void handleMessage(Message msg) {
listView.setAdapter(new ContactAdapter(MainActivity.this, (List<Contact>)msg.obj,
R.layout.listview_item, cache));
}
}; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) this.findViewById(R.id.listView);
//缓存文件
cache = new File(Environment.getExternalStorageDirectory(), "cache");
if(!cache.exists()) cache.mkdirs(); new Thread(new Runnable() {
public void run() {
try {
List<Contact> data = ContactService.getContacts();
handler.sendMessage(handler.obtainMessage(22, data));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} @Override
protected void onDestroy() {
for(File file : cache.listFiles()){
file.delete();
}
cache.delete();
super.onDestroy();
} }
public class ContactAdapter extends BaseAdapter {
private List<Contact> data;
private int listviewItem;
private File cache;
LayoutInflater layoutInflater; public ContactAdapter(Context context, List<Contact> data, int listviewItem, File cache) {
this.data = data;
this.listviewItem = listviewItem;
this.cache = cache;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/**
* 得到数据的总数
*/
public int getCount() {
return data.size();
}
/**
* 根据数据索引得到集合所对应的数据
*/
public Object getItem(int position) {
return data.get(position);
} public long getItemId(int position) {
return position;
} public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = null;
TextView textView = null; if(convertView == null){
convertView = layoutInflater.inflate(listviewItem, null);
imageView = (ImageView) convertView.findViewById(R.id.imageView);
textView = (TextView) convertView.findViewById(R.id.textView);
convertView.setTag(new DataWrapper(imageView, textView));
}else{
DataWrapper dataWrapper = (DataWrapper) convertView.getTag();
imageView = dataWrapper.imageView;
textView = dataWrapper.textView;
}
Contact contact = data.get(position);
textView.setText(contact.name);
asyncImageLoad(imageView, contact.image);
return convertView;
}
private void asyncImageLoad(ImageView imageView, String path) {
AsyncImageTask asyncImageTask = new AsyncImageTask(imageView);
asyncImageTask.execute(path); }
//实现资源的异步加载,可以防止打开很多条线程 影响程序的功能String输入参数类型,Uri子线程返回的数据类型
private final class AsyncImageTask extends AsyncTask<String, Integer, Uri>{
private ImageView imageView;
public AsyncImageTask(ImageView imageView) {
this.imageView = imageView;
}
protected Uri doInBackground(String... params) {//子线程中执行的
try {
return ContactService.getImage(params[0], cache);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Uri result) {//运行在主线程,参数为doInBackground返回的值
if(result!=null && imageView!= null)
imageView.setImageURI(result);
}
}
/*
private void asyncImageLoad(final ImageView imageView, final String path) {
final Handler handler = new Handler(){
public void handleMessage(Message msg) {//运行在主线程中
Uri uri = (Uri)msg.obj;
if(uri!=null && imageView!= null)
imageView.setImageURI(uri);
}
}; Runnable runnable = new Runnable() {
public void run() {
try {
Uri uri = ContactService.getImage(path, cache);
handler.sendMessage(handler.obtainMessage(10, uri));
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
*/
private final class DataWrapper{
public ImageView imageView;
public TextView textView;
public DataWrapper(ImageView imageView, TextView textView) {
this.imageView = imageView;
this.textView = textView;
}
}
}
public class ContactService {

    /**
* 获取联系人
* @return
*/
public static List<Contact> getContacts() throws Exception{
String path = "http://192.168.1.100:8080/web/list.xml";
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
return parseXML(conn.getInputStream());
}
return null;
} private static List<Contact> parseXML(InputStream xml) throws Exception{
List<Contact> contacts = new ArrayList<Contact>();
Contact contact = null;
XmlPullParser pullParser = Xml.newPullParser();
pullParser.setInput(xml, "UTF-8");
int event = pullParser.getEventType();
while(event != XmlPullParser.END_DOCUMENT){
switch (event) {
case XmlPullParser.START_TAG:
if("contact".equals(pullParser.getName())){
contact = new Contact();
contact.id = new Integer(pullParser.getAttributeValue(0));
}else if("name".equals(pullParser.getName())){
contact.name = pullParser.nextText();
}else if("image".equals(pullParser.getName())){
contact.image = pullParser.getAttributeValue(0);
}
break; case XmlPullParser.END_TAG:
if("contact".equals(pullParser.getName())){
contacts.add(contact);
contact = null;
}
break;
}
event = pullParser.next();
}
return contacts;
}
/**
* 获取网络图片,如果图片存在于缓存中,就返回该图片,否则从网络中加载该图片并缓存起来
* @param path 图片路径
* @return
*/
public static Uri getImage(String path, File cacheDir) throws Exception{// path -> MD5 ->32字符串.jpg
File localFile = new File(cacheDir, MD5.getMD5(path)+ path.substring(path.lastIndexOf(".")));
if(localFile.exists()){
return Uri.fromFile(localFile);
}else{
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if(conn.getResponseCode() == 200){
FileOutputStream outStream = new FileOutputStream(localFile);
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = inputStream.read(buffer)) != -1){
outStream.write(buffer, 0, len);
}
inputStream.close();
outStream.close();
return Uri.fromFile(localFile);
}
}
return null;
} }
public class MD5 {

    public static String getMD5(String content) {
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(content.getBytes());
return getHashString(digest); } catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
} private static String getHashString(MessageDigest digest) {
StringBuilder builder = new StringBuilder();
for (byte b : digest.digest()) {
builder.append(Integer.toHexString((b >> 4) & 0xf));
builder.append(Integer.toHexString(b & 0xf));
}
return builder.toString();
}
}

android 数据异步加载的更多相关文章

  1. android的progressDialog 的使用。android数据异步加载 对话框提示

    在调用的Activity中定义一个全局的 progressDialog 点击按钮的时候调用下面这句 progressDialog = ProgressDialog.show(SearchActivit ...

  2. android 网络异步加载数据进度条

    ProgressDialog progressDialog = null; public static final int MESSAGETYPE = 0; private void execute( ...

  3. Android 图片异步加载的体会,SoftReference已经不再适用

      在网络上搜索Android图片异步加载的相关文章,目前大部分提到的解决方案,都是采用Map<String, SoftReference<Drawable>>  这样软引用的 ...

  4. Android 之异步加载LoaderManager

    LoaderManager: Loader出现的背景: Activity是我们的前端页面展现,数据库是我们的数据持久化地址,那么正常的逻辑就是在展示页面的渲染页面的阶段进行数据库查询.拿到数据以后才展 ...

  5. [Android] Android 用于异步加载 ContentProvider 中的内容的机制 -- Loader 机制 (LoaderManager + CursorLoader + LoaderManager.LoaderCallbacks)

    Android 用于异步加载 ContentProvider 中的内容的机制 -- Loader 机制 (LoaderManager + CursorLoader + LoaderManager.Lo ...

  6. Android图片异步加载之Android-Universal-Image-Loader

    将近一个月没有更新博客了,由于这段时间以来准备毕业论文等各种事务缠身,一直没有时间和精力沉下来继续学习和整理一些东西.最近刚刚恢复到正轨,正好这两天看了下Android上关于图片异步加载的开源项目,就 ...

  7. Android图片异步加载之Android-Universal-Image-Loader(转)

    今天要介绍的是Github上一个使用非常广泛的图片异步加载库Android-Universal-Image-Loader,该项目的功能十分强大,可以说是我见过的目前功能最全.性能最优的图片异步加载解决 ...

  8. Java 爬虫遇上数据异步加载,试试这两种办法!

    这是 Java 爬虫系列博文的第三篇,在上一篇 Java 爬虫遇到需要登录的网站,该怎么办? 中,我们简单的讲解了爬虫时遇到登录问题的解决办法,在这篇文章中我们一起来聊一聊爬虫时遇到数据异步加载的问题 ...

  9. Android学习笔记_36_ListView数据异步加载与AsyncTask

    一.界面布局文件: 1.加入sdcard写入和网络权限: <!-- 访问internet权限 --> <uses-permission android:name="andr ...

随机推荐

  1. HDU 1398 Square Coins(DP)

    Square Coins Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tota ...

  2. ELK-7.3安装部署

    原文 ELK-7.3安装部署 前沿 1.什么是ELK? ELK是由Elasticsearch.Logstash.Kibana 三个开源软件的组成的一个组合体 不懂自行查阅 https://www.el ...

  3. Springboot1.5.9整合WebSocket

    一.WebSocket介绍 1.WebSocket是什么? WebSocket是协议,是HTML5开始提供的基于TCP(传输层)的一种新的网络协议, 它实现了浏览器与服务器全双工(full-duple ...

  4. Xcode开发时碰到的问题

    1.打包成功后,发布到蒲公英上,显示"未签名,只能越狱手机可以安装". 出现这个问题,是因为打包的时候签名没有获取到.下面是配置签名的大概步骤. 打包的时候需要点击左上角选择这个设 ...

  5. 深入学习Redis主从复制

    一.主从复制概述 主从复制,是指将一台Redis服务器的数据,复制到其他的Redis服务器.前者称为主节点(master),后者称为从节点(slave):数据的复制是单向的,只能由主节点到从节点. 默 ...

  6. 2019牛客暑期多校训练营(第三场)I Median

    题意:给出n-2的中位数序列b,b[i]代表原序列中(a[i],a[i+1],a[i+2])的中位数,求a. 解法:比赛的时候没做出来,赛后看题解的.解法跟网上各位大佬一样:首先要证明其实原序列a中的 ...

  7. css 多行省略号兼容移动端

    浏览器兼容css样式 -webkit-line-clamp: ; display: -webkit-box; overflow: hidden; text-overflow: ellipsis; te ...

  8. Repeater的使用

    1.页面代码 如果要分页,那么页面开头必须写(<%@ Register Src="~/Controls/Page.ascx" TagName="Page" ...

  9. c++11 委派构造函数

    委派构造函数可以减少构造函数的书写量: class Info { public: Info() : type(), name('a') { InitRest(); } Info(int i) : ty ...

  10. 【NOIP2019模拟2019.10.07】果实摘取 (约瑟夫环、Mobius反演、类欧、Stern-Brocot Tree)

    Description: 小 D 的家门口有一片果树林,果树上果实成熟了,小 D 想要摘下它们. 为了便于描述问题,我们假设小 D 的家在二维平面上的 (0, 0) 点,所有坐标范围的绝对值不超过 N ...