使用Viewpager制作图片阅读器(5)- 增加获取网络图片(附上源码)

在读完这篇文章之后:http://blog.csdn.net/guolin_blog/article/details/34093441

源码下载地址:http://download.csdn.net/detail/hewence1/7885443

增加一个新功能--从网络上下载图片到本地,在读出来:

首先要增加一个网络文件夹:

 /**
     * Add a network dir
     */
   private void AddNetWorkDir() {
       MyPhotoDir dir = new MyPhotoDir(DataConfig.NetWorkPath);
       if (!DataConfig.mPhotoDirList.contains(dir)){
           dir.setmThumb(getResources().getDrawable(R.drawable.network));
           DataConfig.mPhotoDirList.add(dir);
       }
      
        
    }
主界面显示为:

点击network跳转到另一个Activity:

 mGridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
                LogUtils.i("onItemClick position = " + position);
                if (position == mAdapter.getCount() - 1){
                    Intent it = new Intent(MainActivity.this , MyNetworkActivity.class);
                    startActivity(it);
                }else{
                    Intent it = new Intent(MainActivity.this , MyListActivity.class);
                    it.putExtra("index", position);
                    startActivityForResult(it, REQUEST_MY_LIST);
                }
            }
        });
显示网络的Activity
public class MyNetworkActivity extends Activity{
    private static final String TAG = null;
    GridView mGridView = null;
    NetworkAdapter mAdapter = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Network");
        setContentView(R.layout.network_layout);
        
        findView();
        fillData();
    }

    private void findView() {
        mGridView = (GridView)findViewById(R.id.network_gridview);
    }
    

    private void fillData() {
        mAdapter = new NetworkAdapter(this, 0, DataConfig.ALL_IMAGE_URLS);
        mGridView.setAdapter(mAdapter);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        mAdapter.fluchCache();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAdapter.cancelAllTasks();
    }
}
跟最前的那个文章是一样的,

public class NetworkAdapter extends ArrayAdapter<String>{
    private static final String TAG = "NetworkAdapter";
    private HashSet<BitmapWorkerTask> taskCollection; 
    private Context mContxt = null;
    private LruCache<String , Bitmap>  memCache ;
    private DiskLruCache  mDiskLruCache;
    
    public NetworkAdapter(Context context, int textViewResourceId,
           String[] objects) {
        super(context,  textViewResourceId, objects);
        mContxt = context;
        
        taskCollection = new HashSet<BitmapWorkerTask>();
        int maxSize = (int)Runtime.getRuntime().maxMemory();
        memCache = new LruCache<String, Bitmap>(maxSize / 8){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight();
            }
        };
        
        try {
            File cache = getDiskCacheDir(context , "thumb");
            mDiskLruCache = DiskLruCache.open(cache, getCurVersion(), 1, 10 * 1024 * 1024);
            if (!cache.exists()){
                cache.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public View getView(int position, View view, ViewGroup parent) {
        final String urlString = getItem(position);
        if (null == view){
            view = LayoutInflater.from(mContxt).inflate(R.layout.network_detail, null);
        }         
        ImageView mImageView = (ImageView)view.findViewById(R.id.network_image);
        mImageView.setTag(urlString);
        mImageView.setImageResource(R.drawable.empty_photo);
        loadBitmap(mImageView , urlString);
        
        return view;
    }
    
    /**
     * 加载Url对应的图片到imageView
     * @param imageView
     * @param url
     */
    private void loadBitmap(ImageView imageView, String url) {
        try {
            Bitmap  bitmap = getBitmapForMemery(url);
            if (null == bitmap){
                BitmapWorkerTask task = new BitmapWorkerTask(imageView);
                taskCollection.add(task);
                task.execute(url);
            }else{
                imageView.setImageBitmap(bitmap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Bitmap getBitmapForMemery(String url) {
        return memCache.get(url);
    }

    /**
     * 
     * @return  get the current Version of Application
     */
    private int getCurVersion() {
        
        try {  
            PackageInfo info = mContxt.getPackageManager().getPackageInfo(mContxt.getPackageName(),  
                    0);  
            return info.versionCode;  
        } catch (NameNotFoundException e) {  
            e.printStackTrace();  
        }  
        return 1;  
    }



    /**
     * 
     * @param context
     * @param string
     * @return  得到cache的路径
     */
    private File getDiskCacheDir(Context context, String name) {
        String cachePath;  
        cachePath = context.getCacheDir().getPath();  
        
        return new File(cachePath + File.separator + name);  
    }




    public class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap>{
        private String imageUrl ;
        private ImageView mImageView = null;
        public BitmapWorkerTask(ImageView imageView) {
            mImageView = imageView;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            imageUrl = params[0];
            FileDescriptor fileDescriptor = null;
            FileInputStream fileInputStream = null;
            Snapshot snapshot = null;
            try {
                final String key = hashKeyForDisk(imageUrl);
                snapshot = mDiskLruCache.get(key);
                if (null == snapshot) {
                    DiskLruCache.Editor editor = mDiskLruCache.edit(key);
                    if (null != editor) {
                        OutputStream outputStream = editor.newOutputStream(0);
                        if (downloadUrlToStream(imageUrl, outputStream)) {
                            editor.commit();
                        } else {
                            editor.abort();
                        }
                    }
                    snapshot = mDiskLruCache.get(key);
                }

                if (null != snapshot) {
                    fileInputStream = (FileInputStream)snapshot.getInputStream(0);
                    fileDescriptor = fileInputStream.getFD();
                }
                Bitmap bitmap = null;
                if (null != fileDescriptor) {
                    BitmapFactory.Options options = new Options();
                    options.inSampleSize = 4;
                    bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor , null , options);
                }
                if (null != bitmap) {
                    addBitmapToMemoryCache(imageUrl, bitmap);
                }

                return bitmap;
            } catch (Exception e) {
               e.printStackTrace();
            }finally{
                Log.d(TAG , "fileDescriptor = " + fileDescriptor + "fileInputStream = " + fileInputStream);
                if (fileDescriptor == null && fileInputStream != null){
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            
            return null;
        }
        
        @Override
        protected void onPostExecute(Bitmap result) {
            Log.d(TAG , "onPostExecute  result = " + result + "mImageView = " + mImageView);
            if (null != result  &&  null != mImageView){
                mImageView.setImageBitmap(result);
            }
            taskCollection.remove(this);
        }
    }
    
    /** 
     * 使用MD5算法对传入的key进行加密并返回。 
     */  
    public String hashKeyForDisk(String key) {  
        String cacheKey;  
        try {  
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");  
            mDigest.update(key.getBytes());  
            cacheKey = bytesToHexString(mDigest.digest());  
        } catch (NoSuchAlgorithmException e) {  
            cacheKey = String.valueOf(key.hashCode());  
        }  
        return cacheKey;  
    }  
    
    public void addBitmapToMemoryCache(String imageUrl, Bitmap bitmap) {
        if (null == getBitmapForMemery(imageUrl)){
            memCache.put(imageUrl, bitmap);
        }
        
    }

    /** 
     * 建立HTTP请求,并获取Bitmap对象。 
     *  
     * @param imageUrl 
     *            图片的URL地址 
     * @return 解析后的Bitmap对象 
     */  
    private boolean downloadUrlToStream(String urlString, OutputStream outputStream) {  
        Log.i(TAG , "downloadUrlToStream  urlString = " + urlString);
        HttpURLConnection urlConnection = null;  
        BufferedOutputStream out = null;  
        BufferedInputStream in = null;  
        try {  
            final URL url = new URL(urlString);  
            urlConnection = (HttpURLConnection) url.openConnection();  
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.setReadTimeout(10 * 1000);
            in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);  
            out = new BufferedOutputStream(outputStream, 8 * 1024);  
            int b;  
            while ((b = in.read()) != -1) {  
                out.write(b);  
            }  
            Log.i(TAG , "downloadUrlToStream  return true");
            return true;  
        } catch (final IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (urlConnection != null) {  
                urlConnection.disconnect();  
            }  
            try {  
                if (out != null) {  
                    out.close();  
                }  
                if (in != null) {  
                    in.close();  
                }  
            } catch (final IOException e) {  
                e.printStackTrace();  
            }  
        }  
        Log.i(TAG , "downloadUrlToStream  return false");
        return false;  
    }  
 

    private String bytesToHexString(byte[] bytes) {  
        StringBuilder sb = new StringBuilder();  
        for (int i = 0; i < bytes.length; i++) {  
            String hex = Integer.toHexString(0xFF & bytes[i]);  
            if (hex.length() == 1) {  
                sb.append('0');  
            }  
            sb.append(hex);  
        }  
        return sb.toString();  
    }  
    
    /** 
     * 取消所有正在下载或等待下载的任务。 
     */  
    public void cancelAllTasks() {  
        if (taskCollection != null) {  
            for (BitmapWorkerTask task : taskCollection) {  
                task.cancel(false);  
            }  
        }  
    }  
    
    /** 
     * 将缓存记录同步到journal文件中。 
     */  
    public void fluchCache() {  
        if (mDiskLruCache != null) {  
            try {  
                mDiskLruCache.flush();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    } 
    
    
}
最主要的是adpter的实现了。

图片URL是自己架的小型服务器

 public static final String[] ALL_IMAGE_URLS= {
        "http://192.168.1.79/photo13.jpg",
        "http://192.168.1.79/photo14.jpg",
        "http://192.168.1.79/photo15.jpg",
        "http://192.168.1.79/photo16.jpg",
        "http://192.168.1.79/photo17.jpg",
        "http://192.168.1.79/photo18.jpg",
        "http://192.168.1.79/photo19.jpg",
        "http://192.168.1.79/photo20.jpg",
        "http://192.168.1.79/photo21.jpg",
        "http://192.168.1.79/photo22.jpg",
        "http://192.168.1.79/photo23.jpg",
        "http://192.168.1.79/photo24.jpg",
        "http://192.168.1.79/photo25.jpg",
        "http://192.168.1.79/photo26.jpg",
        "http://192.168.1.79/photo27.jpg",
        "http://192.168.1.79/photo28.jpg",
        "http://192.168.1.79/photo29.jpg",
        "http://192.168.1.79/photo30.jpg",
        "http://192.168.1.79/photo32.jpg",
        "http://192.168.1.79/photo33.jpg",
        "http://192.168.1.79/photo34.jpg",
        "http://192.168.1.79/photo35.jpg",
        "http://192.168.1.79/photo36.jpg",
        "http://192.168.1.79/photo37.jpg",
        "http://192.168.1.79/photo38.jpg",
        "http://192.168.1.79/photo39.jpg",
        "http://192.168.1.79/photo40.jpg",
        "http://192.168.1.79/photo41.jpg",
        "http://192.168.1.79/photo42.jpg",
        "http://192.168.1.79/photo43.jpg",
        "http://192.168.1.79/photo44.jpg",
        "http://192.168.1.79/photo45.jpg",
        "http://192.168.1.79/photo46.jpg",
        "http://192.168.1.79/photo31.jpg",
        "http://192.168.1.79/photo31.jpg",
        "http://192.168.1.79/photo31.jpg",
        "http://192.168.1.79/photo31.jpg",
    };


使用过后这个硬盘缓存还是很好用的!

这里都不啰嗦了,请参照链接上面所写的!http://blog.csdn.net/guolin_blog/article/details/34093441




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值