HttpUrlConnection+圖片載入+工具類+介面回撥+單例+AsyncTask封裝工具類
阿新 • • 發佈:2018-11-22
1.MainActivity頁面
package com.example.httpurlconnection; 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(MainActivity.this).getResult(urlStr, NewsBean.class, new NetUtil.AsyCallBack<NewsBean>() { @Override public void onSuccess(NewsBean o) { mAdaper.setmData(o.getData()); } }); } }
2.Bean類
package com.example.httpurlconnection; 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.httpurlconnection; 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 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 text1; TextView text2; //獲取資源id public ViewHolder(View convertView) { image = convertView.findViewById(R.id.image); text1 = convertView.findViewById(R.id.text1); text2 = convertView.findViewById(R.id.text2); convertView.setTag(this); } //賦值 public void bind(final NewsBean.DataBean item) { text1.setText(item.getNews_title()); text2.setText(item.getNews_summary()); image.setTag(item.getPic_url()); NetUtil.getInstance(mContext).loadImage(item.getPic_url(), new NetUtil.imageCallBack() { @Override public void getImageSuccess(String imageUrl, Bitmap bitmap) { if(image.getTag().equals(item.getPic_url())){ image.setImageBitmap(bitmap); } } }); } } }
4.工具類+單例
package com.example.httpurlconnection;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.LruCache;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetUtil {
//單例
private static NetUtil instance;
//圖片記憶體快取
private static LruCache<String,Bitmap> cache;
private File saveDir;
//提供方法,獲取物件
public static NetUtil getInstance(Context context) {
if(instance == null){
instance = new NetUtil(context);
}
return instance;
}
//私有構造
private NetUtil(Context context){
int size = (int)(Runtime.getRuntime().freeMemory()*0.3);
cache = new LruCache<>(size);
//圖片檔案快取目錄
saveDir = new File(context.getCacheDir(),"imag_cache");
//不存在建立
if(!saveDir.exists()){
saveDir.mkdirs();
}
}
//httpurlconnection網路請求返回string
public String getResult(String urlStr){
String result = "";
try {
//定義url地址
URL url = new URL(urlStr);
//開啟連線
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//定義請求型別
urlConnection.setRequestMethod("GET");
//設定超時
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(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();
}
//解析gson返回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 AsyCallBack<E>{
void onSuccess(E e);
}
//執行執行緒的方法
@SuppressLint("StaticFieldLeak")
public void getResult(String urlStr, final Class clazz, final AsyCallBack asyCallBack){
new AsyncTask<String,Void,Object>(){
@Override
protected Object doInBackground(String... strings) {
return getResult(strings[0],clazz);
}
@Override
protected void onPostExecute(Object o) {
asyCallBack.onSuccess(o);
}
}.execute(urlStr);
}
//載入網路圖片 返回Bitmap
public Bitmap loadImage(String urlImage){
Bitmap bitmap = null;
try {
//定義url地址
URL url = new URL(urlImage);
//開啟連線
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//定義請求型別
urlConnection.setRequestMethod("GET");
//設定超時
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
//獲取狀態碼
int responseCode = urlConnection.getResponseCode();
if(responseCode == 200){
bitmap = BitmapFactory.decodeStream(urlConnection.getInputStream());
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
//定義介面
public interface imageCallBack{
void getImageSuccess(String imageUrl,Bitmap bitmap);
}
//獲取圖片回撥介面
@SuppressLint("StaticFieldLeak")
public void loadImage(final String imageUrl, final imageCallBack imageCallBack){
new AsyncTask<String,Void,Bitmap>(){
@Override
protected Bitmap doInBackground(String... strings) {
return loadImage(strings[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
imageCallBack.getImageSuccess(imageUrl,bitmap);
}
}.execute(imageUrl);
}
//獲取圖片三級快取
public Bitmap loadImageWork(String imageUrl){
Bitmap bitmap = null;
//從記憶體中取圖片
bitmap = cache.get(url2Key(imageUrl));
//記憶體命中
if(bitmap!=null){
return bitmap;
}
//從磁碟中取圖片
bitmap = getBitmapForFile(imageUrl);
//檔案命中
if(bitmap!=null){
cache.put(url2Key(imageUrl),bitmap);
return bitmap;
}
//從網路申請
bitmap = loadImage(imageUrl);
//寫檔案
saveBitmap2File(imageUrl,bitmap);
//存到記憶體快取
cache.put(url2Key(imageUrl),bitmap);
return bitmap;
}
//將圖片存到檔案
private void saveBitmap2File(String imageUrl, Bitmap bitmap) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(saveDir,url2Key(imageUrl)));
//圖片質量壓縮
bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//從檔案讀取圖片
private Bitmap getBitmapForFile(String imageUrl) {
//解碼檔案為bitmap圖片
return BitmapFactory.decodeFile(new File(saveDir,url2Key(imageUrl)).getAbsolutePath());
}
//將url裝換為key
private String url2Key(String imageUrl) {
return String.valueOf(imageUrl.hashCode());
}
}