1. 程式人生 > >imageloader圖片載入+將圖片快取到sd卡

imageloader圖片載入+將圖片快取到sd卡

1.mainActivity頁面

package com.example.guoxinyu20181108;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    private ListView listView;
    private NewsAdaper mAdaper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //獲取資源id
        listView = findViewById(R.id.listview);
        //建立介面卡
        mAdaper = new NewsAdaper(MainActivity.this);
        //賦值給listview
        listView.setAdapter(mAdaper);
        infoData();
    }
    private String urlStr = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
    private void infoData() {
        NetUtil.getInstance().getResult(urlStr, NewsBean.class, new NetUtil.CallBack<NewsBean>() {
            @Override
            public void onSuccess(NewsBean o) {
                mAdaper.setmData(o.getData());
            }
        });
    }
}

2.Bean類

package com.example.guoxinyu20181108;

import java.util.List;

public class NewsBean {

    private List<DataBean> data;

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {

        private String news_id;
        private String news_title;
        private String news_summary;
        private String pic_url;

        public String getNews_id() {
            return news_id;
        }

        public void setNews_id(String news_id) {
            this.news_id = news_id;
        }

        public String getNews_title() {
            return news_title;
        }

        public void setNews_title(String news_title) {
            this.news_title = news_title;
        }

        public String getNews_summary() {
            return news_summary;
        }

        public void setNews_summary(String news_summary) {
            this.news_summary = news_summary;
        }

        public String getPic_url() {
            return pic_url;
        }

        public void setPic_url(String pic_url) {
            this.pic_url = pic_url;
        }
    }
}

3.介面卡類

package com.example.guoxinyu20181108;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;

import java.util.ArrayList;
import java.util.List;

public class NewsAdaper extends BaseAdapter {
    private List<NewsBean.DataBean> mData;
    private Context mContext;

    public NewsAdaper(Context mContext) {
        this.mContext = mContext;
        //初始化
        mData = new ArrayList<>();
    }
    public void setmData(List<NewsBean.DataBean> datas){
        this.mData = datas;
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public NewsBean.DataBean getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView == null){
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item,parent,false);
            //例項化
            holder = new ViewHolder(convertView);
        }else{
            //複用
            holder = (ViewHolder) convertView.getTag();
        }
        holder.bind(getItem(position));
        return convertView;
    }
    //建立暫存器
    class ViewHolder{
        ImageView image;
        TextView title;
        TextView summary;
        //獲取資源id
        public ViewHolder(View convertView) {
            image = convertView.findViewById(R.id.image);
            title = convertView.findViewById(R.id.title);
            summary = convertView.findViewById(R.id.summary);
            convertView.setTag(this);
        }
        //賦值
        public void bind(NewsBean.DataBean item) {
            title.setText(item.getNews_title());
            summary.setText(item.getNews_summary());
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    //配置色彩模式
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    //讓圖片進行sdcard快取
                    .cacheOnDisk(true)
                    //讓圖片進行記憶體快取
                    .cacheInMemory(true)
                    //顯示圓形
                    .displayer(new CircleBitmapDisplayer())
                    .build();
            ImageLoader.getInstance().displayImage(item.getPic_url(),image,options);
        }
    }
}

4.工具類

package com.example.guoxinyu20181108;

import android.annotation.SuppressLint;
import android.os.AsyncTask;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class NetUtil {

    private static NetUtil instance;
    //私有構造
    public NetUtil() {
    }
    //定義方法獲取物件
    public static NetUtil getInstance() {
        if(instance == null){
            instance = new NetUtil();
        }
        return instance;
    }
    //載入網路資料 返回string
    public String getResult(String urlStr){
        String result = null;
        try {
            //定義url地址
            URL url = new URL(urlStr);
            //開啟連線
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //設定請求方式
            urlConnection.setRequestMethod("GET");
            //設定超時
            urlConnection.setConnectTimeout(5000);
            urlConnection.setReadTimeout(5000);
            //獲取請求嗎
            int responseCode = urlConnection.getResponseCode();
            if(responseCode == 200){
                result = stream2String(urlConnection.getInputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    //將位元組流轉換為字元流
    private String stream2String(InputStream inputStream) throws IOException {
        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader br = new BufferedReader(isr);
        StringBuilder builder = new StringBuilder();
        for (String tmp = br.readLine();tmp!=null;tmp = br.readLine()){
            builder.append(tmp);
        }
        return builder.toString();
    }
    //執行一個網路請求返回bean
    public <E> E getResult(String urlStr,Class clazz){
        String result = getResult(urlStr);
           E e = (E) new Gson().fromJson(result,clazz);
        return e;
    }
    //定義一個介面
    public interface CallBack<E>{
        void onSuccess(E e);
    }
    //通過介面回撥
    @SuppressLint("StaticFieldLeak")
    public void getResult(String urlStr, final Class clazz, final CallBack callBack){
        new AsyncTask<String,Void,Object>(){
            @Override
            protected Object doInBackground(String... strings) {
                return getResult(strings[0],clazz);
            }
            @Override
            protected void onPostExecute(Object o) {
                callBack.onSuccess(o);
            }
        }.execute(urlStr);
    }
}

5.Application頁面初始化imageloader

package com.example.guoxinyu20181108;

import android.app.Application;
import android.os.Environment;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import java.io.File;

public class App extends Application {
    @Override
    public void onCreate() {
        String path = Environment.getExternalStorageDirectory()+ "/image";
        File file = new File(path);
        ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
                //配置記憶體快取
                .memoryCacheSizePercentage(10)
                //配置磁碟快取
                .diskCache(new UnlimitedDiskCache(file))//UnlimitedDiskCache 限制這個圖片的快取路徑
                .diskCacheFileCount(50)//配置sdcard快取檔案的數量
                .diskCacheFileNameGenerator(new Md5FileNameGenerator())//MD5這種方式生成快取檔案的名字
                .diskCacheSize(50 * 1024 * 1024)//在sdcard快取50MB
                .build();
        //初始化imageload
        ImageLoader.getInstance().init(configuration);
        super.onCreate();
    }
}

6.AndroidManifest.xml頁面

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.guoxinyu20181108">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:name=".App"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>