图片和视频混合广告栏轮播实现

现在很多APP都有自己的广告轮播导航栏特效,这篇文章我将带大家实现非传统的图片轮播特效,要求实现图片和视频轮播特效,当轮播到视频时停止轮播,播放视频。视频播放完后如果遇到下一个是图片就正常轮播,反之则继续播放视频

必须熟悉图片轮播的前提,视频播放基础知识,文件下载,io流操作。好了,废话不多说,代码走起来(贴出核心代码,后面会提供下载demo链接地址)!!

  • 轮播周期性调度
 /**
     * 开始轮播图切换
     *
     * @param flag
     */
    private void startPlay(boolean flag) {
        //根据他的参数说明,第一个参数是执行的任务,第二个参数是第一次执行的间隔,第三个参数是执行任务的周期;
        if (flag) {
            scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);
        }

    }
  • 利用handler处理判断当前轮播位置是图片还是视频
 private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if (msg.what == 100) {

                View view = list.get(currentItem);
                if (view instanceof RelativeLayout) {//走视频播放
                    mviewPager.setCurrentItem(currentItem);
                    scheduledExecutorService.shutdown();//只要遇到视频停止轮询器
                    reaLayout = (RelativeLayout) list.get(currentItem);
                    currentView = (SurfaceView) reaLayout.findViewById(R.id.sv);//拿到当前对应的SurfaceView
                    currentView.getHolder().addCallback(callback);
                    exitVideos = FileUtils.isExitVideos(getApplication());
                    if (null != exitVideos && exitVideos != "") {
                        play(0, exitVideos, currentView);
                    } else {
                        dynamicAddProgressBar(reaLayout);
                        loadVideos();
                    }
                    setFinshListener(new LoadFinshListener() {//监听视频下载完成回调播放视频
                        @Override
                        public void loadFinsh() {
                            exitVideos = FileUtils.isExitVideos(getApplication());
                            play(0, exitVideos, currentView);
                        }
                    });

                    Log.e("from surfaceView:", currentItem + "");
                } else {//走普通图片
                    Log.e("from imageView:", currentItem + "");
                    mviewPager.setCurrentItem(currentItem);
                }
            }
        }

    };
  • 当前是视频界面时动态添加进度条
   /**
     * 动态添加ProgressBar
     * 保证对应到当前准确的RelativeLayout中
     *
     * @param reaLayout
     */
    public void dynamicAddProgressBar(RelativeLayout reaLayout) {
            RelativeLayout.LayoutParams param1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        progressBar = new ProgressBar(getApplication());
        progressBar.setIndeterminateDrawable(getResources().getDrawable(R.drawable.progressbar));
        param1.addRule(RelativeLayout.CENTER_IN_PARENT);
        reaLayout.addView(progressBar, param1);
    }



  • 这里利用Retrofit下载网络视频到本地
 /**
     * loadVideos
     */
    private void loadVideos() {
        progressBar.setVisibility(View.VISIBLE);
        String videoName = "D046015255134077DDB3ACA0D7E68D45.flv";
        FileApi.getInstance(baseUrl)
                .loadFileByName(videoName, new FileCallback(FileUtils.getDiskCacheDir(this).toString(), videoName) {
                    @Override
                    public void onSuccess(File file) {
                        super.onSuccess(file);
                        Log.e("file onSuccess:::::", "");
                        progressBar.setVisibility(View.GONE);
                        currentView.setBackground(null);
                        loadListener.loadFinsh();//通过回调通知界面播放,用handler此处无效
                    }

                    @Override
                    public void progress(long progress, long total) {
                    }

                    @Override
                    public void onFailure(Call call, Throwable t) {
                        Log.e("file onFailure:::::", "");
                        call.cancel();
                    }
                });

    }
  • 视频播放代码块
/**
     * 开始播放
     *
     * @param msec 播放初始位置
     * @param msec
     */
    protected void play(final int msec, final String files, final SurfaceView sv) {
        currentView.setBackground(null);
        File file = new File(files);
        if (!file.exists()) {
            Toast.makeText(this, "视频文件路径错误", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            mediaPlayer = new MediaPlayer(); //这个初始化不能放在这里,因为surfaceView可能会多次执行,导致mediaPlayer重新被初始化,由于监听器用的是同一个导致回调的时候会出现不适同一个mediaplayer的情况
            //此方法创建同步加载,直接start
//            mediaPlayer = MediaPlayer.create(this, Uri.parse(file.getAbsolutePath()), null);
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            // 设置播放的视频源
            mediaPlayer.setDataSource(file.getAbsolutePath());
            // 设置显示视频的SurfaceHolder
            mediaPlayer.setDisplay(sv.getHolder());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                @Override
                public void onPrepared(MediaPlayer mp) {

                    mediaPlayer.start();
                    // 按照初始位置播放
                    mediaPlayer.seekTo(msec);
                    isPlaying = true;
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    // 在播放完毕被回调
                    mp.release();
                    startPlay(true);
                }
            });

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    // 发生错误重新播放
                    play(0, files, sv);
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

这里还不知道怎么上传文件,第一次写博客,有需要完整demo源码请联系我[email protected]。希望大家多多理解,有错误欢迎提问多多交流

你可能感兴趣的:(APP实战demo)