RXJava Thinking Download Image

Table of contents

Why learn RxJava?

What is Reactive Programming?

RXJava Thinking Download Image


Why learn RxJava?

  • Change thinking (responsive programming thinking), improve programming efficiency

        Official website: ReactiveX

What is Reactive Programming?

[Based on the response of the previous layer to affect the changes of the next layer]

  Reactive programming is a programming paradigm oriented towards data flow and change propagation. This means that static or dynamic data flows can be easily expressed in a programming language, and the associated computational model will automatically propagate changing values ​​through the data flow

RXJava Thinking Download Image

Step 1: Add dependency packages

//RxAndroid的依赖包
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
//RxJava的依赖包
implementation 'io.reactivex.rxjava2:rxjava:2.0.7'

Step 2: Enable network permissions

<!--开启网络权限-->
<uses-permission android:name="android.permission.INTERNET"/>

Step Three: Page Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    
    <!--下载图片-->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载图片"
        android:onClick="loadDownImage" />

    <!--Rxjava来显示图片-->
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

Step 4: RXJava downloads/displays pictures (MainActivity code)

package com.example.rxjavastudy;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {

    //网络图片的链接地址
    private final String PATH = "https://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr" +
            "=detail&url=https%3A%2F%2Fgimg2.baidu.com%2Fimage_search%2Fsrc%3Dhttp%253A%252F%252Fpic1.win4000." +
            "com%252Fwallpaper%252F7%252F57ec72987b140.jpg%26refer%3Dhttp%253A%252F%252Fpic1.win4000.com%26ap" +
            "p%3D2002%26size%3Df9999%2C10000%26q%3Da80%26n%3D0%26g%3D0n%26fmt%3Dauto%3Fsec%3D1663469947%26t%3Df1" +
            "cb7822473a7224f3ae863f7d7082ee&thumburl=https%3A%2F%2Fimg2.baidu.com%2Fit%2Fu%3D791640261%2C44080610%" +
            "26fm%3D253%26fmt%3Dauto%26app%3D120%26f%3DJPEG%3Fw%3D1280%26h%3D800";

    //弹出加载框(正在加载中.....)
    private ProgressDialog progressDialog;

    //ImageView控件,用来显示图片
    private ImageView image;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化ImageView
        image=findViewById(R.id.image);

    }

    public void loadDownImage(View view) {
        //起点-创建被观察者 通过just完成起点流向终点的操作
        //TODO 第二步
        Observable.just(PATH)
                //需求 1:图片下载
                //TODO 第三步
                .map(new Function<String, Bitmap>() {
                    @Override
                    public Bitmap apply(String s) throws Exception {
                        try {
                            Thread.sleep(2000);//睡眠2s

                            URL url=new URL(PATH);//url
                            //请求服务器
                            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                            httpURLConnection.setConnectTimeout(5000);//设置请求时间为5s

                            //拿到服务器的响应码
                            int responseCode =  httpURLConnection.getResponseCode();
                            if(responseCode==HttpURLConnection.HTTP_OK){//如果拿到200
                                InputStream inputStream=httpURLConnection.getInputStream();//获取输入流
                                Bitmap bitmap= BitmapFactory.decodeStream(inputStream);//解析输入流
                                return bitmap;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                })
                //需求2:给图片加水印
                //TODO 第四步
                .map(new Function<Bitmap, Bitmap>() {
                    @SuppressLint("ResourceAsColor")
                    @Override
                    public Bitmap apply(Bitmap bitmap) throws Exception {
                        Paint paint=new Paint();
                        paint.setColor(R.color.black);//颜色
                        paint.setTextSize(150);//文字大小
                        Bitmap bitmap1=drawTextToBitmap(bitmap,"这是一个水印",paint,100,150);
                        return bitmap1;
                    }
                })
                //需求3:打印日志
                //TODO 第五步
                .map(new Function<Bitmap, Bitmap>() {
                    @Override
                    public Bitmap apply(Bitmap bitmap) throws Exception {
                        System.out.println("日志:"+bitmap);
                        return bitmap;
                    }
                })

                //给上面的分配异步线程
                .subscribeOn(Schedulers.io())

                //图片显示终点分配andorid主线程
                .observeOn(AndroidSchedulers.mainThread())

                //TODO 导火索 点燃了 开始执行
                //关联起点和终点 创建观察者,并进行订阅
                .subscribe(new Observer<Bitmap>() {

                    @Override
                    //终点-订阅成功
                    //TODO 第一步
                    public void onSubscribe(Disposable d) {
                        //显示加载框
                        progressDialog = new ProgressDialog(MainActivity.this);
                        progressDialog.setTitle("图片正在加载中...");
                        progressDialog.show();
                    }

                    @Override
                    //上一层给的响应
                    //TODO 第六步
                    public void onNext(Bitmap bitmap) {
                        //显示到控件上
                        image.setImageBitmap(bitmap);
                    }

                    @Override
                    //发生异常
                    public void onError(Throwable e) {

                    }

                    @Override
                    //链条结束
                    //TODO 第七步
                    public void onComplete() {
                        //隐藏加载框
                        if(progressDialog != null){
                            progressDialog.dismiss();
                        }
                    }
                });
    }

    
    //水印
    private final Bitmap drawTextToBitmap(Bitmap bitmap, String text, Paint paint, int paddingLeft, int paddingTop){
        Bitmap.Config bitmapConfig = bitmap.getConfig();
        paint.setDither(true);//获得更清晰的图片采样
        paint.setFilterBitmap(true);//过滤
        if(bitmapConfig == null){
            bitmapConfig = Bitmap.Config.ARGB_8888;
        }

        Bitmap bitmap1 = bitmap.copy(bitmapConfig, true);
        Canvas canvas = new Canvas(bitmap1);
        canvas.drawText(text,paddingLeft,paddingTop,paint);
        return bitmap1;
    }



}

Step 5: Effect

rxjava thinking download picture

Guess you like

Origin blog.csdn.net/weixin_53443677/article/details/126420939