多執行緒和非同步下載圖片
阿新 • • 發佈:2019-01-06
一開始從慕課網學習到的非同步載入顯示圖片,今天終於有時間按照記憶寫了份非同步載入圖片程式碼;有很多小細節需要注意的。
步驟:
1、先解析完JSon資料,並存放在List中間
2、非同步下載圖片,放在Item.xml中
3、listView.setAdapter(teacherAapter);
1、從類開始介紹:
- Teacher:圖片bean
- TeacherAdapter:介面卡
- ImageLoad:根據URL獲取圖片,顯示到Item.xml中
- MainActivity:從Json中獲取資料,呼叫介面卡,並顯示;
2、解析Json
- 通過Thread來適配
public void getTeacher()
{
new Thread()
{
@Override
public void run() {
try
{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.imooc.com/api/teacher?type=4&num=30" )
.build();
Response response = client.newCall(request).execute();
String data = response.body().string();
parseJson(data);
//初始化介面卡和列表
final TeacherAapter teacherAapter = new TeacherAapter(MainActivity.this,teacherList);
runOnUiThread(new Runnable() {
@Override
public void run() {
//在子執行緒中設定介面
listView.setAdapter(teacherAapter);
}
});
}catch (Exception e)
{
e.printStackTrace();
}
}
}.start();
}
//解析Json
public void parseJson(String data)
{
try
{
JSONObject jsonObject1 = new JSONObject(data);
JSONArray jsonArray = jsonObject1.getJSONArray("data");
System.out.println("length:"+jsonArray.length());
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
Teacher teacher = new Teacher();
teacher.setName(jsonObject.getString("name"));
Log.d("name:",jsonObject.getString("name"));
teacher.setPicSmall(jsonObject.getString("picSmall"));
teacher.setDescription(jsonObject.getString("description"));
teacherList.add(teacher);
System.out.println("tea_list:"+teacherList.size());
}
}catch (Exception e)
{
e.printStackTrace();
}
}
- AsyncTask 非同步載入來適配
class MyAsyncTask extends AsyncTask<String,Void,List<Teacher>>
{
@Override
protected List<Teacher> doInBackground(String... params) {
teacherList = getTeacher(params[0]);
return teacherList;
}
@Override
protected void onPostExecute(List<Teacher> teacherList) {
super.onPostExecute(teacherList);
TeacherAapter teacherAapter = new TeacherAapter(MainActivity.this,teacherList);
listView.setAdapter(teacherAapter);
}
}
//呼叫非同步任務
new MyAsyncTask().execute(url);
- 3、載入圖片
- 通過Thread載入
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 通過判斷載入的路徑是否正確來載入圖片,
if (imageView.getTag().equals(url))
imageView.setImageBitmap((Bitmap) msg.obj);
}
};
public void showImageByThread(ImageView imageView, final String url) {
this.url = url;
this.imageView = imageView;
new Thread(new Runnable() {
@Override
public void run() {
try {
Bitmap bitmap = getFromCache(url);
if (bitmap == null) {
URL url1 = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
InputStream is = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
//加入快取
addToCache(url, bitmap);
}
// OkHttpClient client = new OkHttpClient();
// Request request = new Request.Builder()
// .url(url)
// .build();
// Response response = client.newCall(request).execute();
// byte[] b =response.body().string().getBytes();
// System.out.println("b.length"+b.length);
// bitmap = BitmapFactory.decodeByteArray(b,0,b.length);
Message message = handler.obtainMessage();
message.obj = bitmap;
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
- 通過非同步載入圖片
//通過非同步的方法載入
public void showImageByAsy(ImageView imageView, final String url) {
this.url = url;
this.imageView = imageView;
new MyAsyLoad().execute(url);
}
class MyAsyLoad extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = getFromCache(params[0]);
if (bitmap != null)
return bitmap;
try {
URL url1 = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
InputStream is = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
addToCache(params[0], bitmap);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null && imageView != null)
imageView.setImageBitmap(bitmap);
}
}
- 4、Lrucache快取
private LruCache<String, Bitmap> mCache;
public ImageLoad() {
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemory / 8;
// 設定圖片快取大小為程式最大可用記憶體的1/8
mCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount();
}
};
}