继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Rx_Android实现网络图片的异步加载

万千封印
关注TA
已关注
手记 90
粉丝 13
获赞 64

1.进行工具类的封装

  1.1图片下载类的封装  主要是通过Rx_Android实现 (观察者模式)

  package zm.ztd.com.rx_android.utils;



import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;


/**
 * Created by Administrator on 2016-12-31.
 */
public class DownLoadUtils {
    private OkHttpClient client;
    public DownLoadUtils(){
        client=new OkHttpClient();
    }

    /**
     * 声明一个被观察者对象  作为结果返回
     * @param path
     * @return
     */
    public Observable<byte[]>downLoadImage(String path){
        return Observable.create(new Observable.OnSubscribe<byte[]>() {
            @Override
            public void call(Subscriber<? super byte[]> subscriber) {
                if(!subscriber.isUnsubscribed()){
                    //访问网络操作
                    Request request=new Request.Builder().url(path).build();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(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);
                                  }
                              }
                        }
                    });
                }
            }
        });
    }


}

1.2 对图片进行压缩处理的工具类
package zm.ztd.com.rx_android.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * 对图片压缩的工具类
 * Created by Administrator on 2016-12-31.
 */
public class ImageUtils {
   public static Bitmap compreessIamge(Bitmap image){
       ByteArrayOutputStream baos=new ByteArrayOutputStream();
       image.compress(Bitmap.CompressFormat.JPEG,100,baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
       int options=100;
       while (baos.toByteArray().length/1024>100){  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
           baos.reset();
           options-=100;
           //这里压缩options%,把压缩后的数据存放到baos中
           image.compress(Bitmap.CompressFormat.JPEG,options,baos);
       }

       ByteArrayInputStream inputStream=new ByteArrayInputStream(baos.toByteArray());
       Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
       return bitmap;
   }
}

1.3 MainActivity中进行逻辑代码的实现
package zm.ztd.com.rx_android;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import zm.ztd.com.rx_android.utils.DownLoadUtils;
import zm.ztd.com.rx_android.utils.ImageUtils;

public class MainActivity extends AppCompatActivity {
   private ImageView imageView;
    private Button btnDownLoad;
    private String path="http://p1.so.qhmsg.com/t0196896c77ff138dd6.jpg";
    private DownLoadUtils downloadUtils;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initEvent();
    }

    private void initEvent() {
       btnDownLoad.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               downloadUtils.downLoadImage(path).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<byte[]>() {
                   @Override
                   public void onCompleted() {

                   }

                   @Override
                   public void onError(Throwable e) {

                   }

                   @Override
                   public void onNext(byte[] bytes) {
                       Bitmap source= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
                       Bitmap bitmap= ImageUtils.compreessIamge(source);
                       imageView.setImageBitmap(bitmap);

                       if(source!=null){
                           source.recycle();
                       }
                   }
               });
           }
       });
    }

    private void initView() {
        imageView= (ImageView) findViewById(R.id.iv_img);
        btnDownLoad= (Button) findViewById(R.id.btn_download);
        downloadUtils=new DownLoadUtils();
    }


}

1.4网络权限一定要添加:<uses-permission android:name="android.permission.INTERNET"></uses-permission>

原文链接:http://www.apkbus.com/blog-813041-62873.html

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP