简单入门使用Retrofit+ rxjava 下载图片

现在比较流行所以就尝试写了一个demo。发现确实比较好用,

首先,导入相关的库
//rxJava
compile ‘io.reactivex:rxjava:latest.release’
compile ‘io.reactivex:rxandroid:latest.release’
//network - squareup
compile ‘com.squareup.retrofit2:retrofit:latest.release’
compile ‘com.squareup.retrofit2:adapter-rxjava:latest.release’
compile ‘com.squareup.okhttp3:okhttp:latest.release’
compile ‘com.squareup.okhttp3:logging-interceptor:latest.release’
首先获取Retrofit实例对象
Retrofit retrofit = new Retrofit.Builder() .baseUrl(“http://pic41.nipic.com“) .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
----------------
在使用Retrofit的时候它的网路访问时通过注解来实现,要有一个定义访问参数和访问类型的接口
interface ServiceApi{
@GET(“/20140509/4746986_145156378323_2.jpg”)
Observable<ResponseBody>downloadPcFromNet();

其中可以定义post请求,也可以设置请求参数,相关使用百度一下
---------------
下来获取ServiceApi
ServiceApi service = retrofit.create(ServiceApi.class);

rxjava最方便的就是没有handler 没有去显示的new 子线程,没有去用异步加载。代码看起来比较整洁,下面放demo了 ,没有分包久一个类解决所有问题
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView mImageView ;
private ProgressDialog progressBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   mImageView =(ImageView)findViewById(R.id.image);
    progressBar = new ProgressDialog(this);

    com.example.hefei.myapplication.ViewUtils.setOnClick(this,this,R.id.text);
}

@Override
public void onClick(View v) {
   Load();
}

private void Load() {
    progressBar.show();
    getService().downloadPicFromNet()
            .subscribeOn(Schedulers.newThread())
            .map(new Func1() {
                @Override
                public Bitmap call(ResponseBody responseBody) {
                    return BitmapFactory.decodeStream(responseBody.byteStream());
                }
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber() {
                @Override
                public void onCompleted() {
                    progressBar.hide();
                }

                @Override
                public void onError(Throwable e) {
                    progressBar.hide();
                }

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

interface ServiceApi{
    @GET("/20140509/4746986_145156378323_2.jpg")
    Observable downloadPicFromNet();
}

public ServiceApi getService(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://pic41.nipic.com")
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //添加Rxjava
            .build();
    return retrofit.create(ServiceApi.class);
}

}
大家可以根据需求自己改动,良心制作,测试无残留,你值得拥有

你可能感兴趣的:(android)