試用一下RxJava加Retrofit

前言

這段時間我已經在一個公司實習了,雖然工資不高,我並無太多的介意。可是有一點是我不舒服的,負責咱們部門的經理助理彷佛看不起實習生,對我有些輕蔑。主要是他技術也不是很牛逼那種。整個公司用的技術仍是比較落後那種。當我推薦Vue時居然說這種別人封裝好的js不太好。當時心裏有一千條草泥馬奔跑,那你爲何還要用jQuery?so,我打算跳槽,跳去更有發展的公司,畢竟我如今是實習,主要仍是但願獲得成長~因而接到了一個安卓面試,因此特意前來寫下這篇文章進行復習。(本人面試如今的公司就是來作安卓的,可是人手不夠讓我作作前端)前端

正文

安卓如今比較熱火的四大框架應該是Rxjava,retrofit,Okhttp,Dagger。因而我去翻各類博文本身嘗試着去寫一個小demo。首先來看看咱們這個小demo的一個效果圖:java

效果圖.gif
能夠看到咱們這個demo就是調用了一個接口,有一個滑動列表,有圖片,有的是視頻,點進去能夠觀看視頻。一個很簡單的App DEMO。好了廢話很少說,讓咱們開始吧! 第一,先來看看咱們整個項目引入的依賴:

implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support:recyclerview-v7:27.1.0'
    implementation 'com.android.support:cardview-v7:27.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    //最主要的是下面這幾條
    implementation "io.reactivex.rxjava2:rxjava:2.1.10"
    implementation 'io.reactivex.rxjava2:rxandroid:2.0.2'
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    implementation 'com.github.bumptech.glide:glide:4.6.1'
複製代碼

其次來看看咱們整個項目的一個結構圖(MVP架構,直接用MVPHelper生成的):react

項目結構圖
如今來介紹一下整個項目結構:

  • contract包裏面放的是接口,用來約束後面的開發;
  • model裏面就是實體類對象和提供後臺數據的請求接口;
  • presenter,很明顯就是MVP中的P,主持者類;
  • view裏面原本我是要把activity也放進去的,可是沒放,裏面就放了一個RecyclerView的適配器。
  • utils裏面是一個建立Retrofit的工廠類
至此,整個包的項目結構就算是介紹完成了。

第二,在主界面佈局文件中加入一個RcyclerView和一個ProgressBar,根佈局咱們直接使用的是ConstraintLayout:android

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="top.cyixlq.rxtestapp.MainActivity">

    <ProgressBar
        android:id="@+id/pro"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rec"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
複製代碼

接着就是建立一個RecyclerView的單個條目佈局文件joker_rec_item.xml,根佈局咱們用的是CardView:git

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardCornerRadius="5dp"
    app:cardElevation="3dp"
    app:contentPadding="5dp"
    android:layout_marginBottom="5dp">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="標題"
        android:textSize="15sp"/>

    <TextView
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10sp"
        android:layout_marginTop="20dp"
        android:text="內容"/>

    <ImageView
        android:id="@+id/img"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"/>

</android.support.v7.widget.CardView>
複製代碼

能夠看出這個佈局很簡單,就是標題內容都是TextView,還有一個ImageView來展現圖片。 而後把約束類創建起來,JokerContract:github

public interface JokerContract {
    interface Model {
        void getJokerList(String type,String page,Observer<Joker> observer);
    }

    interface View {
        void showJokerList(List<Joker.DataBean> list);
        void getJokerListFinish();
        void getJokerListErro(String msg);
    }

    interface Presenter {
        void getJokerList(String type,String page);
    }
}
複製代碼

第三,完成咱們的Retrofit的工廠類RetrofitFactory:面試

public class RetrofitFactory {
    private final static String BASE_URL="https://www.apiopen.top/";
    private static final long TIMEOUT = 30;
    private static JokerApiService jokerApiService=new Retrofit.Builder()
            .baseUrl(BASE_URL)
            //添加Gson轉換器
            .addConverterFactory(GsonConverterFactory.create())
            //// 添加Retrofit到RxJava的轉換器
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
            .create(JokerApiService.class);

    public static JokerApiService getJokerApiService(){
        return jokerApiService;
    }

}
複製代碼

第四,完成M層,先完成接口api的請求,在model包中的apiservices包中新建一個接口,JokerApiService:api

public interface JokerApiService {
    @GET("satinApi")
    Observable<Joker> getJokerList(@Query("type")String type,@Query("page")String page);
}
複製代碼

而後利用GsonFormat建立實體類Joker(內容有點長,可是其實咱們會用到的屬性很少):bash

public class Joker {
    private int code;
    private String msg;
    private List<DataBean> data;
    //get和set省略
    public static class DataBean {
        private String type;
        private String text;
        private String user_id;
        private String name;
        private String screen_name;
        private String profile_image;
        private String created_at;
        private Object create_time;
        private String passtime;
        private String love;
        private String hate;
        private String comment;
        private String repost;
        private String bookmark;
        private String bimageuri;
        private Object voiceuri;
        private Object voicetime;
        private Object voicelength;
        private String status;
        private String theme_id;
        private String theme_name;
        private String theme_type;
        private String videouri;
        private int videotime;
        private String original_pid;
        private int cache_version;
        private String playcount;
        private String playfcount;
        private String cai;
        private Object weixin_url;
        private String image1;
        private String image2;
        private boolean is_gif;
        private String image0;
        private String image_small;
        private String cdn_img;
        private String width;
        private String height;
        private String tag;
        private int t;
        private String ding;
        private String favourite;
        private Object top_cmt;
        private Object themes;
        //get和set省略
    }
}
複製代碼

接着就是把Model類建起來,JokerModel:網絡

public class JokerModel implements JokerContract.Model {
    @Override
    public void getJokerList(String type, String page, Observer<Joker> observer) {
        JokerApiService apiService=RetrofitFactory.getJokerApiService();  //獲取接口
        Observable<Joker> observable= apiService.getJokerList(type,page);  //利用接口獲取數據
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer); //在IO線程執行,發送結果到主線程
    }
}
複製代碼
這樣,M層算是完成了。

第五,完成P層,新建JokerPresenter:

public class JokerPresenter implements JokerContract.Presenter {

    JokerContract.Model mModel;
    JokerContract.View mView;

    public JokerPresenter(JokerContract.View view){
        mModel=new JokerModel();
        this.mView=view;
    }

    @Override
    public void getJokerList(String type, String page) {
        mModel.getJokerList(type,page,new Observer<Joker>(){

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Joker joker) {
                List<Joker.DataBean> list=joker.getData();
                mView.showJokerList(list);  //視圖層將列表結果展現出來
            }

            @Override
            public void onError(Throwable e) {
                mView.getJokerListErro(e.getMessage());    //視圖層將錯誤信息顯示出來
            }

            @Override
            public void onComplete() {
                mView.getJokerListFinish();    //視圖層完成數據獲取狀態
            }
        });
    }
}
複製代碼
至此,P層算是完成了。

第六,完成V層,也就是視圖層,在第一步中咱們已經把各類佈局寫完了,這裏咱們主要寫activity和RecyclerView的適配器。先來寫適配器,JokerAdapter:

public class JokerAdapter extends RecyclerView.Adapter<JokerAdapter.MyViewHolder> {
    private List<Joker.DataBean> list;
    private Context mContext;
    private OnItemClickListener mOnItemClickListener;

    public JokerAdapter(List<Joker.DataBean> list,Context context){
        this.list=list;
        this.mContext=context;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.joker_rec_item,parent,false);
        MyViewHolder viewHolder=new MyViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        holder.txt_title.setText(list.get(position).getName());
        holder.txt_content.setText(list.get(position).getText());
        Glide.with(mContext).load(list.get(position).getBimageuri()).into(holder.img);
        if(mOnItemClickListener!=null){
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnItemClickListener.onClick(position);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    //原本這個內部類是沒有設置成靜態的,可是據說不是靜態的會形成內存泄漏?還望大神給我這個小白解答一下,感激涕零!
    static class MyViewHolder extends RecyclerView.ViewHolder{

        TextView txt_title;
        TextView txt_content;
        ImageView img;

        public MyViewHolder(View itemView) {
            super(itemView);
            txt_title=itemView.findViewById(R.id.title);
            txt_content=itemView.findViewById(R.id.content);
            img=itemView.findViewById(R.id.img);
        }
    }

    //點擊事件接口
    public interface OnItemClickListener{
        void onClick( int position);
    }

    //設置點擊事件
    public void setOnItemClickListener(OnItemClickListener onItemClickListener ){
        this.mOnItemClickListener=onItemClickListener;
    }
}
複製代碼

以上就是個人適配器的全部代碼,其中有個問題想請教諸位大神,還請大神不吝賜教:ViewHolder那個內部類是沒有設置成靜態的,可是據說不是靜態的會形成內存泄漏?還望大神給我這個小白解答一下,感激涕零! 接着就是MainActivity:

public class MainActivity extends AppCompatActivity implements JokerContract.View{

    public static final String TAG="MainActivity";

    JokerPresenter mPresenter;
    JokerAdapter mAdapter;
    List<Joker.DataBean> mList;

    private RecyclerView mRecyclerView;
    private ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPresenter=new JokerPresenter(this);
        mRecyclerView=findViewById(R.id.rec);
        mProgressBar=findViewById(R.id.pro);
        initData();
        mPresenter.getJokerList("29","1"); //咱們只獲取了第一頁的數據
    }

    private void initData(){
        mList=new ArrayList<>();
        mAdapter=new JokerAdapter(mList,this);
        mAdapter.setOnItemClickListener(new JokerAdapter.OnItemClickListener() { //設置點擊事件
            @Override
            public void onClick(int position) {
                String url=mList.get(position).getVideouri();  //獲取對應的視頻連接,而且經過intent攜帶連接進行跳轉
                Intent intent=new Intent(MainActivity.this,VideoPlayActivity.class);
                intent.putExtra("url",url);
                startActivity(intent);
            }
        });
        LinearLayoutManager manager=new LinearLayoutManager(MainActivity.this);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void showJokerList(List<Joker.DataBean> list) {
        mProgressBar.setVisibility(View.VISIBLE);
        mList.addAll(list);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void getJokerListFinish() {
        mProgressBar.setVisibility(View.GONE);
    }

    @Override
    public void getJokerListErro(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        Log.e(TAG,msg);
    }
}
複製代碼
至此,V層算是完成了。

第七,就是完成VideoActivity啦,我直接用的VideoView來播放網絡視頻,先把VideoActivity佈局文件寫好,activity_video_play.xml:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="top.cyixlq.rxtestapp.VideoPlayActivity">

    <VideoView
        android:id="@+id/video"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>
複製代碼

我就是直接放的一個VideoView。而後編寫activity代碼,讓VideoView播放網絡視頻:

public class VideoPlayActivity extends AppCompatActivity {

    private VideoView mVideoVIew;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_play);
        mVideoVIew=findViewById(R.id.video);
        mVideoVIew.setMediaController(new MediaController(this));
        mVideoVIew.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Toast.makeText(VideoPlayActivity.this, "播放完成了", Toast.LENGTH_SHORT).show();
            }
        });
        startPlay();
    }

    private void startPlay(){
        Intent intent=getIntent();
        String url=intent.getStringExtra("url");
        if(null!=url) {
            mVideoVIew.setVideoURI(Uri.parse(url));
            mVideoVIew.start();
        }
    }
}
複製代碼

這樣就能輕鬆實現VideoView播放網絡視頻啦。而後咱們整個Demo也就這樣寫完了哦!

後記


這只是一個簡單的Demo,我的也是剛開始接觸不久,若是還有什麼地方寫的不對,還望各位大神指教,本人不勝感激,求大神帶飛!本Demo的GitHub地址:github.com/cyixlq/RxTe…

本人只是一個在IT技術上不斷探索的小白,但願能跟着你們一塊兒進步,好的,今天就寫到這裏,白了個白!
相關文章
相關標籤/搜索