rxjava2系列:Android线程切换简单实例

写简单例子,不需要用Okhttp。借用这篇:java HttpURLConnection实现简单的网络请求。

效果图如下:
rxjava2系列:Android线程切换简单实例_第1张图片

rxjava2导入:

 implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
 implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
  • 要达到上图的效果,必须用Console字体,我的坚果云网盘上有,也可以下载:下载链接
  • 完整代码:
package com.exp.cpdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    private TextView tvMsg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvMsg = findViewById(R.id.tv);
        tvMsg.setTextSize(8f); //字体设小点,看着整齐些
        setFont(tvMsg);
        Observable<String> normalObservable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> observableEmitter) throws Exception {
                Log.i("xxx", "开始网络请求,线程名称:" + Thread.currentThread().getName());
                observableEmitter.onNext(getTextFromHttp());
            }
        });


        Observer<String> mObserver = new Observer<String>() {
            @Override
            public void onSubscribe(Disposable disposable) {
            }

            @Override
            public void onNext(String s) {
                Log.i("xxx", "网络请求完成,线程名称:" + Thread.currentThread().getName());
                tvMsg.setText(s);
            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onComplete() {
                Log.d("xxx", "complete");
            }
        };
        normalObservable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mObserver);

    }
    public void setFont(TextView textView) {
        Typeface typeFace2 = Typeface.createFromAsset(getAssets(), "fonts/conso.ttf");
        textView.setTypeface(typeFace2);
    }



    private String getTextFromHttp() {
        try {
            // 根据地址创建URL对象(网络访问的url)
            URL url = new URL("https://publicobject.com/helloworld.txt");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(5000);
            urlConnection.setConnectTimeout(5000);
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                InputStream is = urlConnection.getInputStream();
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                int len = 0;
                byte buffer[] = new byte[1024];
                // 按照缓冲区的大小,循环读取
                while ((len = is.read(buffer)) != -1) {
                    // 根据读取的长度写入到os对象中
                    os.write(buffer, 0, len);
                }
                is.close();
//                os.close(); //无需关闭
                urlConnection.disconnect();
                String result = new String(os.toByteArray());
                System.out.println(result);
                return result;
            } else {
                System.out.println("------------------连接失败-----------------");
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

}

你可能感兴趣的:(RxJava2,android,rxjava)