Android 异步加载
为什么要使用异步加载
1.android 单线程模型- 耗时操作阻塞UI线程
异步加载最常用的两种方式
1.多线程\线程池
2.AsycnTask
直接上项目
mian 文件
package com.example.administrator.as_asyntask;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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 mlist;
private NewsBaseAdapter adapter;
private static String URL=”http://www.imooc.com/api/teacher?type=4&num=30”;//交流的json
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mlist= (ListView) findViewById(R.id.mList);
new NewsAsycTask().execute(URL);
}
/**
*
* @param url
* @return 将url对应JSON转化为我们所封装的NewBean方法
*/
private List<NewsBean> getJsonData(String url){
List<NewsBean> newsBeenList=new ArrayList<NewsBean>();
try {
String jsonString=readStrem(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.img_url=jsonObject.getString("picSmall");
newsBean.title=jsonObject.getString("name");
newsBean.content=jsonObject.getString("description");
newsBeenList.add(newsBean);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("TAG",jsonString);
} catch (IOException e) {
e.printStackTrace();
}
return newsBeenList;
}
/**
*
* @param is
* @return 字节流转化成字符流
*/
private String readStrem (InputStream is) {
InputStreamReader isr;
String result="";
try {
String line="";
isr=new InputStreamReader(is,"UTF-8");//字节流转化为字符流
BufferedReader br=new BufferedReader(isr);//又将buffer形式 读取出来 最终读取到result
while ((line=br.readLine())!=null){
result+=line;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 实现网络的异步访问
*/
class NewsAsycTask 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);
NewsBaseAdapter adapter=new NewsBaseAdapter(MainActivity.this,newsBeen);
mlist.setAdapter(adapter);
}
}
}
数据源
package com.example.administrator.as_asyntask;
import android.content.Context;
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 org.w3c.dom.Text;
import java.util.List;
/**
* Created by Administrator on 2016-07-21.
*/
public class NewsBaseAdapter extends BaseAdapter {
private List mList;
private LayoutInflater mInflater;
public NewsBaseAdapter(Context context, List<NewsBean> data) {
mList = data;
mInflater = LayoutInflater.from(context);
}
@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 (viewHolder==null){
viewHolder=new ViewHolder();
convertView=mInflater.inflate(R.layout.item_layout,null);
viewHolder.iv_img= (ImageView) convertView.findViewById(R.id.iv_img);
viewHolder.iv_title= (TextView) convertView.findViewById(R.id.tv_title);
viewHolder.iv_content= (TextView) convertView.findViewById(R.id.tv_content);
convertView.setTag(viewHolder);
}else {
viewHolder=(ViewHolder)convertView.getTag();
}
viewHolder.iv_img.setTag(mList.get(position).img_url);
new ImageViewLoader().showImageByThread(viewHolder.iv_img,mList.get(position).img_url);
// viewHolder.iv_img.setImageResource(R.mipmap.ic_launcher);
viewHolder.iv_title.setText(mList.get(position).title);
viewHolder.iv_content.setText(mList.get(position).content);
return convertView;
}
/*
*大家都叫文艺
*/
class ViewHolder {
private ImageView iv_img;
private TextView iv_title;
private TextView iv_content;
}
}
Bean
package com.example.administrator.as_asyntask;
/**
* Created by Administrator on 2015-07-21.
*/
public class NewsBean {
public String img_url;
public String title;
public String content;
}
加载图片 用的自定义的HANDDLE
package com.example.administrator.as_asyntask;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Message;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.widget.ImageView;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
/**
* Created by Administrator on 2016-07-21.
*/
public class ImageViewLoader {
private ImageView mImageView;
private String mUrl;
private android.os.Handler handler=new android.os.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(){
@Override
public void run() {
super.run();
Bitmap bitmap=getBitmapFromUrl(url);
Message message=Message.obtain();
message.obj=bitmap;
handler.sendMessage(message);
}
}.start();
}
/**
* 非主线程不能够在线程中更新UI Android 单线程模型 只能通过handle
*/
/**
* 用一个url获取一个bitmap
*/
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();
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
布局文件