`
maoxiao1229
  • 浏览: 3671 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

异步加载图片的实例代码2

阅读更多
package cindy.android.test.synclistview;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.widget.Toast;

public abstract class AbstructCommonActivity extends Activity  {

private MyHandler handler = new MyHandler();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
}

protected void handleOtherMessage(int flag){

}

public void sendMessage(int flag) {
handler.sendEmptyMessage(flag);
}

public void sendMessageDely(int flag,long delayMillis){
handler.sendEmptyMessageDelayed(flag, delayMillis);
}

public void showToast(String toast_message){
handler.toast_message = toast_message;
sendMessage(MyHandler.SHOW_STR_TOAST);
}

public void showToast(int res){
handler.toast_res = res;
sendMessage(MyHandler.SHOW_RES_TOAST);
}

private class MyHandler extends Handler {
public static final int SHOW_STR_TOAST = 0;
public static final int SHOW_RES_TOAST = 1;

private String toast_message=null;
private int toast_res;

@Override
public void handleMessage(Message msg) {
if (!Thread.currentThread().isInterrupted()) {
switch (msg.what) {
case SHOW_STR_TOAST:
Toast.makeText(getBaseContext(), toast_message, 1).show();
break;
case SHOW_RES_TOAST:
Toast.makeText(getBaseContext(), toast_res, 1).show();
break;
default:
handleOtherMessage(msg.what);
}
}
}


}
}


package cindy.android.test.synclistview;

import java.util.Vector;


import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class BookItemAdapter extends BaseAdapter{

private LayoutInflater mInflater;
private Context mContext;
private Vector<BookModel> mModels = new Vector<BookModel>();
private ListView mListView;
SyncImageLoader syncImageLoader;

public BookItemAdapter(Context context,ListView listView){
mInflater = LayoutInflater.from(context);
syncImageLoader = new SyncImageLoader();
mContext = context;
mListView = listView;

mListView.setOnScrollListener(onScrollListener);
}


public void addBook(String book_name,String out_book_url,String out_book_pic){
BookModel model = new BookModel();
model.book_name =book_name;
model.out_book_url = out_book_url;
model.out_book_pic = out_book_pic;
mModels.add(model);
}

public void clean(){
mModels.clear();
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return mModels.size();
}

@Override
public Object getItem(int position) {
if(position >= getCount()){
return null;
}
return mModels.get(position);
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = mInflater.inflate(R.layout.book_item_adapter, null);
}
BookModel model = mModels.get(position);
convertView.setTag(position);
ImageView iv = (ImageView) convertView.findViewById(R.id.sItemIcon);
TextView sItemTitle =  (TextView) convertView.findViewById(R.id.sItemTitle);
TextView sItemInfo =  (TextView) convertView.findViewById(R.id.sItemInfo);
sItemTitle.setText(model.book_name);
sItemInfo.setText(model.out_book_url);
iv.setBackgroundResource(R.drawable.rc_item_bg);
syncImageLoader.loadImage(position,model.out_book_pic,imageLoadListener);
return  convertView;
}

SyncImageLoader.OnImageLoadListener imageLoadListener = new SyncImageLoader.OnImageLoadListener(){

@Override
public void onImageLoad(Integer t, Drawable drawable) {
//BookModel model = (BookModel) getItem(t);
View view = mListView.findViewWithTag(t);
if(view != null){
ImageView iv = (ImageView) view.findViewById(R.id.sItemIcon);
iv.setBackgroundDrawable(drawable);
}
}
@Override
public void onError(Integer t) {
BookModel model = (BookModel) getItem(t);
View view = mListView.findViewWithTag(model);
if(view != null){
ImageView iv = (ImageView) view.findViewById(R.id.sItemIcon);
iv.setBackgroundResource(R.drawable.rc_item_bg);
}
}

};

public void loadImage(){
int start = mListView.getFirstVisiblePosition();
int end =mListView.getLastVisiblePosition();
if(end >= getCount()){
end = getCount() -1;
}
syncImageLoader.setLoadLimit(start, end);
syncImageLoader.unlock();
}

AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener() {

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
DebugUtil.debug("SCROLL_STATE_FLING");
syncImageLoader.lock();
break;
case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
DebugUtil.debug("SCROLL_STATE_IDLE");
loadImage();
//loadImage();
break;
case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
syncImageLoader.lock();
break;

default:
break;
}

}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub

}
};
}


package cindy.android.test.synclistview;

public class BookModel {
public String book_id;
public String out_book_url;
public String author;
public String book_state_s;
public String leading_role;
public String update_time;
public String book_name;
public String out_book_pic;
public String sort_id;
public String last_update_section_title;
public String last_update_section_url;
public String introduction;
}


package cindy.android.test.synclistview;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class DebugUtil {
    public static final String TAG = "DebugUtil";
    public static final boolean DEBUG = true;
    
    public static void toast(Context context,String content){
        Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
    }
    
    public static void debug(String tag,String msg){
        if (DEBUG) {
            Log.d(tag, msg);
        }
    }
    
    public static void debug(String msg){
        if (DEBUG) {
            Log.d(TAG, msg);
        }
    }
    
    public static void error(String tag,String error){
        Log.e(tag, error);
    }
    
    public static void error(String error){
        Log.e(TAG, error);
    }
}


package cindy.android.test.synclistview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class LoadStateView extends RelativeLayout{

ProgressBar progBar;

LinearLayout downLoadErrMsgBox;

TextView downLoadErrText;

Button btnListLoadErr;

public LoadStateView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

@Override
protected void onFinishInflate() {
// TODO Auto-generated method stub
super.onFinishInflate();
progBar = (ProgressBar) findViewById(R.id.progBar);
downLoadErrMsgBox = (LinearLayout) findViewById(R.id.downLoadErrMsgBox);
downLoadErrText = (TextView) findViewById(R.id.downLoadErrText);
btnListLoadErr = (Button) findViewById(R.id.btnListLoadErr);
}

public void startLoad(){
downLoadErrMsgBox.setVisibility(View.GONE);
progBar.setVisibility(View.VISIBLE);
}

public void stopLoad(){
progBar.setVisibility(View.GONE);
}

public void showError(){
downLoadErrMsgBox.setVisibility(View.VISIBLE);
progBar.setVisibility(View.GONE);
}

public void showEmpty(){
downLoadErrMsgBox.setVisibility(View.VISIBLE);
progBar.setVisibility(View.GONE);
}

public void setOnReloadClickListener(OnClickListener onReloadClickListener){
btnListLoadErr.setOnClickListener(onReloadClickListener);
}
}



package cindy.android.test.synclistview;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;

import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;

public class SyncImageLoader {

private Object lock = new Object();

private boolean mAllowLoad = true;

private boolean firstLoad = true;

private int mStartLoadLimit = 0;

private int mStopLoadLimit = 0;

final Handler handler = new Handler();

private HashMap<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();  

public interface OnImageLoadListener {
public void onImageLoad(Integer t, Drawable drawable);
public void onError(Integer t);
}

public void setLoadLimit(int startLoadLimit,int stopLoadLimit){
if(startLoadLimit > stopLoadLimit){
return;
}
mStartLoadLimit = startLoadLimit;
mStopLoadLimit = stopLoadLimit;
}

public void restore(){
mAllowLoad = true;
firstLoad = true;
}

public void lock(){
mAllowLoad = false;
firstLoad = false;
}

public void unlock(){
mAllowLoad = true;
synchronized (lock) {
lock.notifyAll();
}
}

public void loadImage(Integer t, String imageUrl,
OnImageLoadListener listener) {
final OnImageLoadListener mListener = listener;
final String mImageUrl = imageUrl;
final Integer mt = t;

new Thread(new Runnable() {

@Override
public void run() {
if(!mAllowLoad){
DebugUtil.debug("prepare to load");
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

if(mAllowLoad && firstLoad){
loadImage(mImageUrl, mt, mListener);
}

if(mAllowLoad && mt <= mStopLoadLimit && mt >= mStartLoadLimit){
loadImage(mImageUrl, mt, mListener);
}
}

}).start();
}

private void loadImage(final String mImageUrl,final Integer mt,final OnImageLoadListener mListener){

if (imageCache.containsKey(mImageUrl)) { 
            SoftReference<Drawable> softReference = imageCache.get(mImageUrl); 
            final Drawable d = softReference.get(); 
            if (d != null) { 
            handler.post(new Runnable() {
    @Override
    public void run() {
    if(mAllowLoad){
    mListener.onImageLoad(mt, d);
    }
    }
    });
                return; 
            } 
        } 
try {
final Drawable d = loadImageFromUrl(mImageUrl);
if(d != null){
                imageCache.put(mImageUrl, new SoftReference<Drawable>(d));
}
handler.post(new Runnable() {
@Override
public void run() {
if(mAllowLoad){
mListener.onImageLoad(mt, d);
}
}
});
} catch (IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
mListener.onError(mt);
}
});
e.printStackTrace();
}
}

public static Drawable loadImageFromUrl(String url) throws IOException {
DebugUtil.debug(url);
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File f = new File(Environment.getExternalStorageDirectory()+"/TestSyncListView/"+MD5.getMD5(url));
if(f.exists()){
FileInputStream fis = new FileInputStream(f);
Drawable d = Drawable.createFromStream(fis, "src");
return d;
}
URL m = new URL(url);
InputStream i = (InputStream) m.getContent();
DataInputStream in = new DataInputStream(i);
FileOutputStream out = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int   byteread=0;
while ((byteread = in.read(buffer)) != -1) {
out.write(buffer, 0, byteread);
}
in.close();
out.close();
Drawable d = Drawable.createFromStream(i, "src");
return loadImageFromUrl(url);
}else{
URL m = new URL(url);
InputStream i = (InputStream) m.getContent();
Drawable d = Drawable.createFromStream(i, "src");
return d;
}

}
}




package cindy.android.test.synclistview;


import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

public class TestListViewActivity extends AbstructCommonActivity
implements AdapterView.OnItemClickListener{

ListView viewBookList;

BookItemAdapter adapter;

//ViewGroup listFolder;

LoadStateView loadStateView;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewBookList = (ListView) findViewById(R.id.viewBookList);
adapter = new BookItemAdapter(this,viewBookList);
loadStateView = (LoadStateView) findViewById(R.id.downloadStatusBox);

loadStateView.setOnReloadClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
reload();
}
});
//listFolder = (ViewGroup) getLayoutInflater().inflate(R.layout.load_more, null);
//viewBookList.addFooterView(listFolder);
viewBookList.setAdapter(adapter);
viewBookList.setOnItemClickListener(this);
reload();
}

private void reload(){
adapter.clean();
loadStateView.startLoad();
new Thread(new Runnable(){
@Override
public void run() {
try {
Thread.sleep(2*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loadDate();
sendMessage(REFRESH_LIST);
//sendMessageDely(LOAD_IMAGE, 500);
}
}).start();
}

public void loadDate(){
for(int i=0;i<10;i++){
adapter.addBook("吞噬星空"+i,
"http://www.pfwx.com/bookinfo/11/11000.html",
"http://www.pfwx.com/files/article/image/11/11000/11000s.jpg");

adapter.addBook("仙逆"+i,
"http://www.pfwx.com/bookinfo/9/9760.html",
"http://www.pfwx.com/files/article/image/9/9760/9760s.jpg");

adapter.addBook("武动乾坤"+i,
"http://www.pfwx.com/bookinfo/13/13939.html",
"http://www.pfwx.com/files/article/image/13/13939/13939s.jpg");

adapter.addBook("凡人修仙传"+i,
"http://www.pfwx.com/bookinfo/3/3237.html",
"http://www.pfwx.com/files/article/image/3/3237/3237s.jpg");

adapter.addBook("遮天"+i,
"http://www.pfwx.com/bookinfo/11/11381.html",
"http://www.pfwx.com/files/article/image/11/11381/11381s.jpg");
}
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

}

private static final int REFRESH_LIST = 0x10001;
private static final int SHOW_LOAD_STATE_VIEW = 0x10003;
private static final int HIDE_LOAD_STATE_VIEW = 0x10004;

@Override
protected void handleOtherMessage(int flag) {
switch (flag) {
case REFRESH_LIST:
adapter.notifyDataSetChanged();
loadStateView.stopLoad();
if(adapter.getCount() == 0){
loadStateView.showEmpty();
}
break;
case SHOW_LOAD_STATE_VIEW:
loadStateView.startLoad();
break;
case HIDE_LOAD_STATE_VIEW:
loadStateView.stopLoad();
break;

default:
break;
}
}

}









分享到:
评论

相关推荐

    android异步加载图片的实例代码

    总之,这个实例代码提供了一个基础的异步加载图片的实现,结合了ExecutorService来管理线程池,提高了加载效率。在实际应用中,你可能需要根据具体需求对其进行扩展和优化,例如加入缓存策略和错误处理机制。

    android异步加载网络图片实例

    只需一行代码,就可以完成网络图片的异步加载,并且提供了丰富的图片变换和错误处理功能。 4. **Glide**: Glide 是一个现代的图片加载库,优化了滚动性能,特别适合在列表视图或网格视图中加载图片。它能够自动...

    以AJAX方式加载图片=异步加载图片,先显示个图片的占位图片 此技术常见于漫画网站.zip

    不过,它可能与上述的异步加载图片技术有关,提供了实际的实现代码供开发者参考和学习。 总的来说,异步加载图片是通过JavaScript和AJAX技术提高网页性能的关键手段,尤其是在处理大量图片的场景下。通过合理利用...

    vue-router异步加载实例代码

    在这个"vue-router异步加载实例代码"中,我们将探讨如何利用 Vue Router 进行异步组件加载,以提高应用的性能和用户体验。 在 Vue.js 应用中,异步加载组件是一种常见的优化策略。当用户导航到特定路由时,相关的...

    Android网络图片异步加载实例

     最近一段处理跟图片相关的问题,本来是自己写的图片加载,不过有些状态的控制还是比较烦人的,比如ListView滚动时ImageView的重用,所以本着偷懒与充分利用现有资源的态度去网上搜罗图片异步加载的代码,最终在...

    Android ListView优化 异步加载图片

    你可以通过分析这些代码,更好地理解ListView异步加载图片的实现过程。 通过以上介绍,你应该对Android ListView的优化有了更深入的理解,特别是异步加载图片和Json解析这两个关键环节。实践中,结合各种优化策略,...

    Android很好用的图片异步加载工具

    本篇文章将详细解析标题为“Android很好用的图片异步加载工具”的知识点,主要关注的是一个开源项目——"nostra13-Android-Universal-Image-Loader-dfbff1d"。 这个开源库是Android平台上的一个强大的图片异步加载...

    Android异步加载网络图片(线程)

    这个文件可能是项目中实现上述功能的一个示例代码或资源列表,包含了图片的URL列表以及如何利用LruCache和线程回调实现异步加载的具体实现。通过查看和分析这个文件,开发者可以更好地理解和学习如何在实际项目中...

    handler结合Thread异步加载网络图片

    本文将深入探讨如何利用这些组件来实现网络图片的异步加载。 首先,我们需要理解`Thread`。`Thread`是Java中的一个类,用于实现并发执行的任务。在Android中,主线程(UI线程)负责处理用户交互和更新界面,而其他...

    Android图片异步加载(双缓存)实例

    本文将深入探讨“Android图片异步加载(双缓存)实例”,介绍如何利用线程池管理和实现内存及SD卡双缓存机制,以提高图片加载效率和用户体验。 1. **异步加载图片** 在Android中,图片加载必须在后台线程执行,以...

    Android 异步加载图片的实例代码

    总之,这个实例代码演示了如何高效地在Android中异步加载和缓存图片,避免阻塞主线程,提高用户体验。开发者可以根据实际需求对代码进行扩展,比如添加网络错误处理、使用更高级的缓存策略(如LruCache)、考虑使用...

    异步加载图片2

    在Android应用开发中,异步加载图片是一项常见的需求,它涉及到多线程和UI更新的知识。Android遵循单线程模型,即UI线程是主线程,负责处理所有的UI交互和绘制。由于Android的UI操作不是线程安全的,因此不能在非UI...

    Android实现ListView异步加载图片

    至于提供的"20130830153639.jpg"和"AsyncListImage"这两个文件,它们可能是示例图片或用于演示异步加载图片的代码片段。在实际开发中,你需要根据自己的需求替换为实际的网络图片URL或本地图片路径。 总的来说,...

    Android网络图片异步加载实例.pdf

    至此,一个简单的Android网络图片异步加载实例就完成了。在实际应用中,可能还需要考虑更多因素,如图片缓存、错误处理、内存管理等。此外,现在更推荐使用像Glide或Picasso这样的第三方库来实现图片加载,它们提供...

    Android实现异步加载图片

    这个"Android实现异步加载图片"的示例代码旨在帮助初学者理解如何在不阻塞主线程的情况下加载网络或者本地存储的图片,提高应用性能。 首先,我们需要了解Android的线程模型。Android应用的主要UI更新都在主线程...

    安卓图片加载缓存相关-演化理解Android异步加载图片.rar

    "JavaApk源码说明.txt"可能是对源码的简要说明,包括如何运行项目、代码结构、关键类的功能等,这对于理解和学习"Android异步加载图片"的实现过程非常有帮助。 总的来说,通过研究这个压缩包中的内容,开发者可以...

    c# webform 异步加载用户控件

    2. **在主页面引用用户控件**:在需要异步加载的主页面中,为用户控件提供一个容器,例如一个空的Div,同时在后台代码中声明对用户控件的引用。 3. **编写JavaScript**:使用jQuery的$.ajax方法或者$.get方法,发起...

    Android ListView 异步加载图片

    为了解决这一问题,开发者通常会采用异步加载图片的技术,使得用户在滚动ListView时,只加载当前可视区域内的图片,提高用户体验。本文将详细介绍如何使用AsyncTask和WeakReference实现Android ListView中图片的异步...

    VS2008 加载图片实例[源码]

    8. **性能优化**:如果图片文件较大,加载可能会较慢,这时可以考虑使用流式加载或异步加载技术,以提高用户体验。 9. **图片格式转换**:根据需求,开发者可能需要将图片转换为不同的格式,如从PNG转换为JPEG。VS...

Global site tag (gtag.js) - Google Analytics