当前位置:主页 > 移动开发 > Android代码 >

RXjava网络获取图片数据的方法

时间:2020-12-11 20:52:15 | 栏目:Android代码 | 点击:

本文实例为大家分享了RXjava网络获取图片数据的具体代码,供大家参考,具体内容如下

RXjava

// An highlighted block
image = findViewById(R.id.tu);

  Observable.create(new ObservableOnSubscribe<Bitmap>() {
   @Override
   public void subscribe(ObservableEmitter<Bitmap> e) throws Exception {
    e.onNext(getBitmap());
   }
  })
    //设置数据在子线程中遍历
    .subscribeOn(Schedulers.io())
    //设置图片在主线程中加载
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Observer<Bitmap>() {
     @Override
     public void onSubscribe(Disposable d) {

     }

     @Override
     public void onNext(Bitmap bitmap) {
      image.setImageBitmap(bitmap);
     }

     @Override
     public void onError(Throwable e) {

     }

     @Override
     public void onComplete() {

     }
    });
  image.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    Toast.makeText(MainActivity.this, "ee", Toast.LENGTH_SHORT).show();
   }
  });
  image.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {

   }
  });

网络获取数据

// An highlighted block
//获取网络数据
 private Bitmap getBitmap() {
  String str = "https://b-ssl.duitang.com/uploads/blog/201406/16/20140616171020_TiEXR.thumb.700_0.jpeg";
  try {
   URL url = new URL(str);
   HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
   urlConnection.setRequestMethod("GET");
   urlConnection.setConnectTimeout(2000);
   urlConnection.connect();
   if(urlConnection.getResponseCode() == 200){
    return BitmapFactory.decodeStream(urlConnection.getInputStream());
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  return null;
 }

您可能感兴趣的文章:

相关文章