rxjava2 series: simple examples of Android thread switching

Write simple examples without using Okhttp. Borrow this article: java HttpURLConnection implements simple network requests .

The renderings are as follows:

rxjava2 import:

 implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
 implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
  • To achieve the effect of the picture above, you must use the Console font, which is available on my nut cloud network disk, and can also be downloaded: download link
  • Full code:
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 "";
        }
    }

}

Guess you like

Origin blog.csdn.net/zhangjin1120/article/details/131194242