亲宝软件园·资讯

展开

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

人气:0

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;
 }
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论