代码运行实例效果
MainActivity.java
package io.github.deligencc.asynctask;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView mListView;
//请求的网址
private static String URL = "http://www.imooc.com/api/teacher?type=4&num=30";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (android.widget.ListView) findViewById(R.id.lv_main);
new NewsAsyncTask().execute(URL);
}
/**
* 实现网络的异步访问
*/
public class NewsAsyncTask extends AsyncTask<String, Void, List<NewsBean>> {
@Override
protected List<NewsBean> doInBackground(String... params) {
return getJsonData(params[0]);
}
@Override
protected void onPostExecute(List<NewsBean> newsBeen) {
super.onPostExecute(newsBeen);
NewsAdapter adapter = new NewsAdapter(MainActivity.this, newsBeen,mListView);
mListView.setAdapter(adapter);
}
}
/**
* 将url对应的jsdon个数数据转化为我们所封装的NewsBean
* 解析Json数据 封装到List中
*
* @param url
* @return
*/
private List<NewsBean> getJsonData(String url) {
List<NewsBean> newsBeanList = new ArrayList<>();
try {
String jsonString = readStream(new URL(url).openStream());
JSONObject jsonObject;
NewsBean newsBean;
try {
jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
newsBean = new NewsBean();
newsBean.newsIconUrl = jsonObject.getString("picSmall");
newsBean.newsTitle = jsonObject.getString("name");
newsBean.newsContent = jsonObject.getString("description");
newsBeanList.add(newsBean);
Log.d("Tag","newsBeanList.size() is the "+newsBeanList.size());
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("xys", "jsonString");
} catch (Exception e) {
e.printStackTrace();
}
return newsBeanList;
}
/**
* 通过InputStream is 解析网页返回数据
*
* @param is
* @return
*/
private String readStream(InputStream is) {
InputStreamReader isr;
String result = "";
try {
String line = "";
isr = new InputStreamReader(is, "utf-8"); //字节流转化为字符流
BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
result += line;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
图片异步加载类
ImageLoader.java
package io.github.deligencc.asynctask;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.ListView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
/**
* Created by bummer on 2017/8/23.
*/
public class ImageLoader {
private ImageView mImageView;
private String mUrl;
//创建Cache
private LruCache<String, Bitmap> mCaches;//需要保存缓存对象的名字,保存对象 本质是map
private ListView mListView;
private Set<NewsAsyncTask> mTasks;
public ImageLoader(ListView listView) {
mListView = listView;
mTasks = new HashSet<>();
//获取最大可用内存
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemory / 4;
mCaches = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
//返回图片大小,每次存入缓存时调用
return value.getByteCount(); //将bitmap的实际大小传入
}
}; //初始化缓存大小
}
/**
* 将内容保存的Cache
*/
public void addBitmapToCache(String url, Bitmap bitmap) {
if (getBitmapFromCache(url) == null) { //判断当前缓存是否存在
mCaches.put(url, bitmap);
}
}
/**
* 从Cache中读取内容
*/
public Bitmap getBitmapFromCache(String url) {
//从缓存中获取数据
return mCaches.get(url);
}
private Handler mhandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (mImageView.getTag().equals(mUrl)) {
mImageView.setImageBitmap((Bitmap) msg.obj);
}
}
};
public void showImageByThread(ImageView imageView, final String url) {
mImageView = imageView;
mUrl = url;
new Thread(new Runnable() {
@Override
public void run() {
Bitmap bitmap = getBitmapFromUrl(url);
Message message = Message.obtain(); //通过这种方式创建的message,可以使用现有的,已经回收到的message,提高message的使用效率
message.obj = bitmap;
mhandler.sendMessage(message);
}
}).start();
}
public Bitmap getBitmapFromUrl(String urlstring) {
Bitmap bitmap;
InputStream is = null;
try {
URL url = new URL(urlstring);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
connection.disconnect();
// Thread.sleep(1000);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public void showImageByAsyncTask(ImageView imageView, String url) {
//先判断缓存中是否存在数据,减少下载时间 从缓存中取出对应的图片
Bitmap bitmap = getBitmapFromCache(url);
if (bitmap == null) { //如果缓存中没有,必须从网络下载
//new NewsAsyncTask(url).execute(url);
imageView.setImageResource(R.mipmap.ic_launcher);
} else { //直接从内存中获取 并设置
imageView.setImageBitmap(bitmap);
}
}
/**
* 用来加载从start到end所有图片
* @param start
* @param end
*/
public void loadImages(int start, int end) {
for (int i = start; i < end; i++) {
//从缓存中取出从start到end位置对应的图片
String url = NewsAdapter.URLS[i];
Bitmap bitmap = getBitmapFromCache(url);
//如果缓存中没有,那么必须去下载
if (bitmap == null) {
NewsAsyncTask task = new NewsAsyncTask(url);
task.execute(url);
mTasks.add(task);
} else {
ImageView imageView = (ImageView) mListView.findViewWithTag(url);
imageView.setImageBitmap(bitmap);
}
}
}
/**
* 取消当前正在取消的任务
*/
public void cancelAllTasks() {
if (mTasks != null) {
for (NewsAsyncTask task : mTasks) {
task.cancel(true);
}
}
}
private class NewsAsyncTask extends AsyncTask<String, Void, Bitmap> {
private ImageView mImageView;
private String mUrl;
public NewsAsyncTask(String url) {
// mImageView = imageView;
mUrl = url;
}
@Override
protected Bitmap doInBackground(String... params) {
String url = params[0];
//将下载的图片保存缓存中 从网络获取图片
Bitmap bitmap = getBitmapFromUrl(url);
if (bitmap != null) {
//将不再缓存的图片加入缓存
addBitmapToCache(url, bitmap);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
// if (mImageView.getTag().equals(mUrl)) {
// mImageView.setImageBitmap(bitmap);
// }
ImageView imageView = (ImageView) mListView.findViewWithTag(mUrl);
if (imageView != null && bitmap != null) {
imageView.setImageBitmap(bitmap);
}
mTasks.remove(this);
}
}
}
新闻适配器
NewsAdapter.java
package io.github.deligencc.asynctask;
import android.content.Context;
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;
import java.util.List;
/**
* Created by bummer on 2017/8/22.
*/
public class NewsAdapter extends BaseAdapter implements AbsListView.OnScrollListener{
private List<NewsBean> mList;
private LayoutInflater mInflater;
private ImageLoader mImageLoader;
private int mStart,mEnd;
public static String[] URLS;
private boolean mFirstIn;
public NewsAdapter(Context context, List<NewsBean> data, ListView listView) {
this.mList = data;
mInflater = LayoutInflater.from(context);
mImageLoader = new ImageLoader(listView);
URLS = new String[data.size()];
for (int i = 0; i < data.size(); i++) {
URLS[i] = data.get(i).newsIconUrl;
//获得data所有URL 转到静态数组中
}
mFirstIn = true;
//注册事件接口
listView.setOnScrollListener(this);
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if(convertView == null){
viewHolder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_layout,null);
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.iv_icon);
// new ImageLoader().showImageByThread(viewHolder.ivIcon,mList.get(position).newsIconUrl);
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tv_content);
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.ivIcon.setImageResource(R.mipmap.ic_launcher);
String url = mList.get(position).newsIconUrl;
viewHolder.ivIcon.setTag(url);//作为身份标识
// new ImageLoader().showImageByThread(viewHolder.ivIcon,mList.get(position).newsIconUrl);
mImageLoader.loadImages(mStart,mEnd);
viewHolder.tvTitle.setText(mList.get(position).newsTitle);
viewHolder.tvContent.setText(mList.get(position).newsContent);
return convertView;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
//状态改变时会调用
if(scrollState == SCROLL_STATE_IDLE){
//加载可见项
mImageLoader.loadImages(mStart,mEnd);
}else {
//停止所有的加载任务
mImageLoader.cancelAllTasks();
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//整个滑动中都会被调用
mStart = firstVisibleItem;
mEnd = firstVisibleItem+visibleItemCount;
if(mFirstIn && visibleItemCount > 0){
//当前列表第一次显示, item已经显示出来
mImageLoader.loadImages(mStart,mEnd);
mFirstIn = false;
}
}
class ViewHolder{
public TextView tvTitle,tvContent;
public ImageView ivIcon;
}
}
新闻实体类
NewsBean.java
package io.github.deligencc.asynctask;
/**
* Created by bummer on 2017/8/22.
*/
public class NewsBean {
//图片网址
public String newsIconUrl;
public String newsTitle;
public String newsContent;
}
//布局界面
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="io.github.deligencc.asynctask.MainActivity">
<ListView
android:id="@+id/lv_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
activity_main.xml布局截图
item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="4dp">
<ImageView
android:id="@+id/iv_icon"
android:layout_width="64dp"
android:layout_height="64dp"
android:gravity="center"
android:src="@mipmap/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="4dp">
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Title"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="3"
android:text="Content"
android:textSize="10sp" />
</LinearLayout>
</LinearLayout>
item_layout.xml布局截图