/*retrofit的引入*/
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
/*retrofit对rx支持的引入*/
compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'
/*rx的引入*/
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.9'
对于rx的引入,只需要最后两个即可,其他的是为了retrofit的使用
例子中的第二个参数,由于是项目使用。所以参数不具备通用性,但是方法就这样
private void showImage(final String imageUrl, final JCVideoPlayerStandard jcVideoPlayerStandard) {
Observable.create(new ObservableOnSubscribe<Bitmap>() {
@Override
public void subscribe(@io.reactivex.annotations.NonNull ObservableEmitter<Bitmap> e) throws Exception {
//e.onNext(BitmapFactory.decodeResource(getResources(), R.drawable.shoucang));
e.onNext(GetImageInputStream(imageUrl));
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Bitmap>() {
@Override
public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
}
@Override
public void onNext(@io.reactivex.annotations.NonNull Bitmap s) {
jcVideoPlayerStandard.thumbImageView.setImageBitmap(s);
}
@Override
public void onError(@io.reactivex.annotations.NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
}
/**
* 获取网络图片
*
* @param imageurl 图片网络地址
* @return Bitmap 返回位图
*/
public Bitmap GetImageInputStream(String imageurl) {
URL url;
HttpURLConnection connection = null;
Bitmap bitmap = null;
try {
url = new URL(imageurl);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(6000); //超时设置
connection.setDoInput(true);
connection.setUseCaches(false); //设置不使用缓存
InputStream inputStream = connection.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeStream(inputStream, null, options);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}