Rxjava +Retrofit+ok+GreenDao视频播放

来源:互联网 发布:怎么弄成网络回路 编辑:程序博客网 时间:2024/05/29 15:10

==================依赖==============

compile 'com.facebook.fresco:fresco:1.5.0'compile 'com.squareup.retrofit2:retrofit:2.0.1'compile 'com.squareup.okio:okio:1.5.0'compile 'com.squareup.okhttp3:okhttp:3.2.0'compile 'com.squareup.retrofit2:converter-gson:2.0.1'compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'compile 'io.reactivex:rxandroid:1.1.0'compile 'com.jakewharton:butterknife:8.5.1'annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'compile 'com.youth.banner:banner:1.4.10'compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'compile 'cn.jzvd:jiaozivideoplayer:6.1.2'   //把支持最低版本改为16compile 'zlc.season:rxdownload:1.1.1'compile 'org.greenrobot:greendao:3.0.1'compile 'org.greenrobot:greendao-generator:3.0.0'compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
GreenDao相关配置查看本博客其他文章

==================Net==============

public class Api {    public static  final String url="http://result.eolinker.com/";}
public interface ApiService {    //http://result.eolinker.com/iYXEPGn4e9c6dafce6e5cdd23287d2bb136ee7e9194d3e9?uri=vedio    @GET("iYXEPGn4e9c6dafce6e5cdd23287d2bb136ee7e9194d3e9")    Observable<NewsBean> getList(@Query("uri") String uri);}

==================utils==============

public class RetrofitUtils {    private static RetrofitUtils retrofitUtils;    private RetrofitUtils() {    }    public static RetrofitUtils getInstance() {        if (retrofitUtils == null) {            synchronized (RetrofitUtils.class) {                if (retrofitUtils == null) {                    retrofitUtils = new RetrofitUtils();                }            }        }        return retrofitUtils;    }    private static Retrofit retrofit;    public static synchronized Retrofit getRetrofit(String url) {        HttpLoggingInterceptor tag = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {            @Override            public void log(String message) {                Log.i("TAG", message);            }        });        tag.setLevel(HttpLoggingInterceptor.Level.BODY);        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(tag).connectTimeout(5000, TimeUnit.SECONDS).build();        if (retrofit == null) {            retrofit = new Retrofit.Builder().client(okHttpClient).baseUrl(url).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();        }        return retrofit;    }    public <T> T getApiService(String url, Class<T> clazz) {        Retrofit retrofit = getRetrofit(url);        return retrofit.create(clazz);    }}
public class GlideImageLoader extends ImageLoader {    @Override    public void displayImage(Context context, Object path, ImageView imageView) {        /**         注意:         1.图片加载器由自己选择,这里不限制,只是提供几种使用方法         2.返回的图片路径为Object类型,由于不能确定你到底使用的那种图片加载器,         传输的到的是什么格式,那么这种就使用Object接收和返回,你只需要强转成你传输的类型就行,         切记不要胡乱强转!         */        //fresco加载图片简单用法,记得要写下面的createImageView方法        Uri uri = Uri.parse((String) path);        imageView.setImageURI(uri);    }    //提供createImageView 方法,如果不用可以不重写这个方法,主要是方便自定义ImageView的创建    @Override    public ImageView createImageView(Context context) {        //使用fresco,需要创建它提供的ImageView,当然你也可以用自己自定义的具有图片加载功能的ImageView        SimpleDraweeView simpleDraweeView=new SimpleDraweeView(context);        return simpleDraweeView;    }}
public class MyApp extends Application{    private static  MyApp mInstance;    private DaoSession daoSession;    @Override    public void onCreate() {        super.onCreate();        Fresco.initialize(this);        mInstance = this;        setDb();    }    public static MyApp getmInstance(){        return  mInstance;    }    private void setDb() {        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "bw.db", null);        SQLiteDatabase database = helper.getWritableDatabase();        DaoMaster daoMaster = new DaoMaster(database);        daoSession = daoMaster.newSession();    }    public DaoSession getDaoSessio(){        return daoSession;    }}

==================view==============

public interface IRecyView {    public void getData(NewsBean newsBean);}
public interface OnListListener {    public void OnSuccess(NewsBean newsBean);}

==================Model==============

public class RevyModel {    public void findData(String uri, final OnListListener listListener){        Log.i("xxc","传参"+uri);        ApiService apiService= RetrofitUtils.getInstance().getApiService(Api.url,ApiService.class);        Observable<NewsBean> list = apiService.getList(uri);        list.subscribeOn(Schedulers.io())                .observeOn(AndroidSchedulers.mainThread())                .subscribe(new Subscriber<NewsBean>() {                    @Override                    public void onCompleted() {                        Log.i("xxc","完成");                    }                    @Override                    public void onError(Throwable e) {                        Log.i("xxc","失败"+e.getMessage());                    }                    @Override                    public void onNext(NewsBean newsBean) {                        Log.i("xxc","成功");                        listListener.OnSuccess(newsBean);                    }                });    }}

================presenter============

public class RecyPresenter implements OnListListener{    IRecyView view;    RevyModel model;    public RecyPresenter(IRecyView view) {        this.view = view;        model=new RevyModel();    }    public void relevence(String uri){      model.findData(uri,this);    }    @Override    public void OnSuccess(NewsBean newsBean) {        view.getData(newsBean);    }}

==================Bean==============

public class NewsBean {    /**     * code : 200     * data : [{"content":"习近平举行仪式欢迎加蓬总统访华","id":10000,"image_url":"http://pic32.nipic.com/20130817/9745430_101836881000_2.jpg","title":"今日头条","type":1,"vedio_url":"http://2449.vod.myqcloud.com/2449_bfbbfa3cea8f11e5aac3db03cda99974.f20.mp4"},{"content":"习近平举行仪式欢迎加蓬总统访华","id":10001,"image_url":"http://pic15.nipic.com/20110630/6322714_105943746342_2.jpg","title":"往期故事","type":2,"vedio_url":"https://wdl.wallstreetcn.com/41aae4d2-390a-48ff-9230-ee865552e72d"},{"content":"这个市的书记市长双双被约谈 引发震动","id":10002,"image_url":"http://pic48.nipic.com/file/20140916/2531170_195153248000_2.jpg","title":"讨论天下","type":3,"vedio_url":"http://video.jiecao.fm/5/1/%E8%87%AA%E5%8F%96%E5%85%B6%E8%BE%B1.mp4"},{"content":"\u201c乔丹\u201d商标是否侵权 4年官司迎最高法判决 调查","id":10003,"image_url":"http://img.taopic.com/uploads/allimg/140626/240469-1406261S24553.jpg","title":"我的珍爱","type":4,"vedio_url":"http://2449.vod.myqcloud.com/2449_bfbbfa3cea8f11e5aac3db03cda99974.f20.mp4"},{"content":"黑龙江稻农收入暴涨组团进城买房 有人买十多套","id":10004,"image_url":"http://pic77.nipic.com/file/20150911/21721561_155058651000_2.jpg","title":"我的未来","type":5,"vedio_url":"http://video.jiecao.fm/5/1/%E8%87%AA%E5%8F%96%E5%85%B6%E8%BE%B1.mp4"},{"content":"印尼6.4级地震致97死 专家称当地防震意识差","id":10005,"image_url":"http://img4.duitang.com/uploads/item/201603/18/20160318103156_cziuY.jpeg","title":"东芝","type":6,"vedio_url":"http://ips.ifeng.com/video19.ifeng.com/video09/2014/06/16/1989823-102-086-0009.mp4"}]     * msg : 成功     */    private int code;    private String msg;    private List<DataBean> data;    public int getCode() {        return code;    }    public void setCode(int code) {        this.code = code;    }    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }    public List<DataBean> getData() {        return data;    }    public void setData(List<DataBean> data) {        this.data = data;    }    public static class DataBean {        /**         * content : 习近平举行仪式欢迎加蓬总统访华         * id : 10000         * image_url : http://pic32.nipic.com/20130817/9745430_101836881000_2.jpg         * title : 今日头条         * type : 1         * vedio_url : http://2449.vod.myqcloud.com/2449_bfbbfa3cea8f11e5aac3db03cda99974.f20.mp4         */        private String content;        private int id;        private String image_url;        private String title;        private int type;        private String vedio_url;        public String getContent() {            return content;        }        public void setContent(String content) {            this.content = content;        }        public int getId() {            return id;        }        public void setId(int id) {            this.id = id;        }        public String getImage_url() {            return image_url;        }        public void setImage_url(String image_url) {            this.image_url = image_url;        }        public String getTitle() {            return title;        }        public void setTitle(String title) {            this.title = title;        }        public int getType() {            return type;        }        public void setType(int type) {            this.type = type;        }        public String getVedio_url() {            return vedio_url;        }        public void setVedio_url(String vedio_url) {            this.vedio_url = vedio_url;        }    }}
@Entitypublic class User {    @Id    private Long id;   @Property(nameInDb = "status")    private int status;public int getStatus() {    return this.status;}public void setStatus(int status) {    this.status = status;}public Long getId() {    return this.id;}public void setId(Long id) {    this.id = id;}@Generated(hash = 469379441)public User(Long id, int status) {    this.id = id;    this.status = status;}@Generated(hash = 586692638)public User() {}

==================gen==============

自动生成

==================Adapter==============

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{    Subscription subscription;    Context context;    NewsBean bean;    int progress;    int max;    int download;    List<NewsBean.DataBean> list;    public MyAdapter(Context context, NewsBean bean) {        this.context = context;        this.bean = bean;        list=bean.getData();    }    @Override    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {        View view= LayoutInflater.from(context).inflate(R.layout.item,parent,false);        MyViewHolder mholder=new MyViewHolder(view);        return mholder;    }    @Override    public void onBindViewHolder(final MyViewHolder holder, final int position) {        holder.title.setText(list.get(position).getTitle());        Log.i("xxc","标题"+list.get(position).getTitle());        //设置播放视频链接和视频标题        holder.jz.setUp(list.get(position).getVedio_url(), JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, list.get(position).getTitle());        //为播放视频设置封面图        holder.jz.thumbImageView.setImageResource(R.mipmap.ic_launcher);        holder.down.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                if(subscription != null && !subscription.isUnsubscribed()){                    subscription.unsubscribe();                    User u=new User(null,progress);                    Log.i("xxc","我的下载进度"+progress);                    DaoSession daoSessio = MyApp.getmInstance().getDaoSessio();                    UserDao userDao = daoSessio.getUserDao();                    userDao.insert(u);                    List<User> userList = userDao.loadAll();//查询集合                    for (User userinfo : userList ) {                        int userinfoName = userinfo.getStatus();                        String s=String.valueOf(userinfoName);                        Log.i("xxc","存储"+s);                    }                }else {                            subscription = RxDownload.getInstance()                            .maxThread(3)     //设置最大线程                            .maxRetryCount(10) //设置下载失败重试次数                            .download(list.get(position).getVedio_url(),"myplayer.mp4",null) //开始下载                            .subscribeOn(Schedulers.io())                            .observeOn(AndroidSchedulers.mainThread())                            .subscribe(new Subscriber<DownloadStatus>() {                                @Override                                public void onCompleted() {                                    Log.i("xxc","下载成功");                                }                                @Override                                public void onError(Throwable e) {                                    Log.i("xxc","下载失败");                                }                                @Override                                public void onNext(DownloadStatus status) {                                    //Status表示的是当前的下载进度                                    Log.i("xxc","正在下载"+status);                                    long totalSize=status.getTotalSize();                                    max= (int) totalSize;                                    long downloaad=status.getDownloadSize();                                    download= (int) downloaad;                                    progress=max/download*100;                                    holder.sk.setProgress(progress);                                }                            });                }            }        });    }    @Override    public int getItemCount() {        return list.size();    }    public class MyViewHolder extends  RecyclerView.ViewHolder{        TextView down;        TextView title;        JZVideoPlayerStandard jz;        ProgressBar sk;        public MyViewHolder(View itemView) {            super(itemView);            title= itemView.findViewById(R.id.tv_item);            jz=itemView.findViewById(R.id.videoplayer);            down=itemView.findViewById(R.id.tv_download);            sk=itemView.findViewById(R.id.sk);        }    }}

===============MainActivity===================

public class MainActivity extends AppCompatActivity implements IRecyView {    List<String> img;    List<String> title;    @BindView(R.id.banner)    Banner ban;    @BindView(R.id.recy)    RecyclerView mrv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ButterKnife.bind(this);        mrv.setLayoutManager(new LinearLayoutManager(this));        RecyPresenter presenter = new RecyPresenter(this);        presenter.relevence("vedio");    }    @Override    public void getData(NewsBean newsBean) {        img=new ArrayList<>();        title=new ArrayList<>();        for (int i = 0; i <newsBean.getData().size() ; i++) {            img.add(newsBean.getData().get(i).getImage_url());            title.add(newsBean.getData().get(i).getTitle());            Log.i("xxc","BAn"+img.toString());        }        ban.setImageLoader(new GlideImageLoader());        ban.setImages(img);        ban.setBannerTitles(title);        ban.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE);        ban.start();        MyAdapter adapter=new MyAdapter(this,newsBean);        mrv.setAdapter(adapter);    }}

==============布局======================

<LinearLayout 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"    android:orientation="vertical">    <com.youth.banner.Banner        android:id="@+id/banner"        android:layout_width="match_parent"        android:layout_height="200dp" />    <android.support.v7.widget.RecyclerView        android:id="@+id/recy"        android:layout_width="match_parent"        android:layout_height="match_parent"/></LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:orientation="vertical">    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="wrap_content">        <TextView            android:id="@+id/tv_item"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="视频标题"            android:textSize="20sp"/>        <TextView            android:id="@+id/tv_download"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="下载"            android:layout_alignParentRight="true"            android:textSize="20sp"/>    </RelativeLayout><ProgressBar    android:id="@+id/sk"    style="?android:attr/progressBarStyleHorizontal"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:max="100"    android:progress="0"    />    <cn.jzvd.JZVideoPlayerStandard        android:id="@+id/videoplayer"        android:layout_width="match_parent"        android:layout_height="200dp"/></LinearLayout>

阅读全文
0 0
原创粉丝点击