public class Main2Activity extends AppCompatActivity {
private ImageView img;
private DownLoadUtils mDownloadUtils;
String path="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1515082106078&di=5503a486aaba0a93462182b910a777d1&imgtype=0&src=http%3A%2F%2Fimg.taopic.com%2Fuploads%2Fallimg%2F131117%2F234805-13111FT63784.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//初始化数据
initView();
mDownloadUtils = new DownLoadUtils();
//访问网络的一张图片将图片显示在imageview上
//用到线程调度器
RxJavaThread();
}
/*
* 访问网络数据
*
* */
private void RxJavaThread() {
//将网络图片读取出来
//使用http协议获取数据
mDownloadUtils.downloadIamge(path)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<byte[]>() {
@Override
public void onCompleted() {
Log.e("TAG", "=====onCompleted=====");
//这里一般处理对话框消失
}
@Override
public void onError(Throwable e) {
Log.e("TAG", "onError: ", e);
}
@Override
public void onNext(byte[] bytes) {
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes
.length);
img.setImageBitmap(bitmap);
}
});
}
private void initView() {
img = (ImageView) findViewById(R.id.img);
}
}
访问网络的工具类
public class DownLoadUtils {
private OkHttpClient mOkHttpClient;
public DownLoadUtils() {
mOkHttpClient = new OkHttpClient();
}
/**
* 声明一个被观察者对象作为结果返回
*
* @param path
* @return
*/
public Observable<byte[]> downloadIamge(final String path) {
return Observable.create(new Observable.OnSubscribe<byte[]>() {
@Override
public void call(final Subscriber<? super byte[]> subscriber) {
if (!subscriber.isUnsubscribed()) {
//访问网络操作
Request request = new Request.Builder().url(path).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
subscriber.onError(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
byte[] data = response.body().bytes();
if (data != null) {
subscriber.onNext(data);
}
}
subscriber.onCompleted();
}
});
}
}
});
}
}