news_client/app/src/main/java/com/example/myapplication/ImageLoader.java
2019-12-29 22:59:55 +08:00

66 lines
1.9 KiB
Java

package com.example.myapplication;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class ImageLoader {
private ImageView mImageView;
private String murl;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(mImageView.getTag().equals(murl)) {
mImageView.setImageBitmap((Bitmap) msg.obj);
}
}
};
public void showImagerByThread(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();
}
public Bitmap getBitmapFromURL(String urlString){
Bitmap bitmap;
InputStream is = null;
try {
URL url = new URL(urlString);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
is = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
connection.disconnect();
return bitmap;
} catch (java.io.IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}