Android ViewPager中显示图片与播放视频的填坑记录

6
回复
1368
查看
[复制链接]

758

主题

1465

帖子

1858

安币

手工艺人

发表于 2018-5-21 11:09:05 | 显示全部楼层 |阅读模式

            

        viewpager介绍

        viewpager的功能就是可以使视图滑动,就像lanucher左右滑动那样。

        viewpager用于实现多页面的切换效果,该类存在于google的兼容包android-support-v4.jar里面.

        viewpager:

         1)viewpager类直接继承了viewgroup类,所有它是一个容器类,可以在其中添加其他的view类。

         2)viewpager类需要一个pageradapter适配器类给它提供数据。

         3)viewpager经常和fragment一起使用,并且提供了专门的fragmentpageradapter和fragmentstatepageradapter类供fragment中 的viewpager使用。

         4)在编写viewpager的应用的使用,还需要使用两个组件类分别是pagertitlestrip类和pagertabstrip类,pagertitlestrip类直接继承 自viewgroup类,而pagertabstrip类继承pagertitlestrip类,所以这两个类也是容器类。但是有一点需要注意,在定义xml的layout 的时候,这两个类必须是viewpager标签的子标签,不然会出错。

        本文将详细介绍关于android viewpager中显示图片与播放视频填坑的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。

        一.需求来源与实现思路

        1.最近项目需求中有用到需要在viewpager中播放视频和显示图片的功能,视频是本地视频,最开始的实现思路是viewpager中根据当前item位置对应的是图片还是视频去初始化photoview和surfaceview,同时销毁时根据item的位置去判断移除photoview和surfaceview。

        2.上面那种方式确实是可以实现的,但是存在2个问题,第一,mediaplayer的生命周期不容易控制并且存在内存泄漏问题。第二,连续三个item都是视频时,来回滑动的过程中发现会出现上个视频的最后一帧画面的bug。

        3.未提升用户体验,视频播放器初始化完成前上面会覆盖有该视频的第一帧图片,但是发现存在第一帧图片与视频第一帧信息不符的情况,后面会通过代码给出解决方案。

        4.图片和视频尺寸如何适配以保证不变形。

        二.需要填的坑

        1.对于mediaplayer的生命周期不容易控制的本质原因是这种实现思路上我的播放器只有1个,频繁的初始化和销毁造成了问题,所以后面我更改了实现方式,一个item的视频对应一个播放器。

        2.对于滑动过程中发现会出现上个视频的最后一帧画面的bug,发现是surfaceview这个控件造成的,后面通过将播放的载体更换为textureview完美解决该问题。

        3.surfaceview与textureview的本质异同

        第一:两者都能在独立的线程中绘制和渲染,在专用的gpu线程中大大提高渲染的性能。

        第二:surfaceview专门提供了嵌入视图层级的绘制界面,开发者可以控制该界面像size等的形式,能保证界面在屏幕上的正确位置。但也有局限:
1.由于是独立的一层view,更像是独立的一个window,不能加上动画、平移、缩放;
2.两个surfaceview不能相互覆盖。

        第三:texture更像是一般的view,像textview那样能被缩放、平移,也能加上动画。textureview只能在开启了硬件加速的window中使用,并且消费的内存要比surfaceview多,并伴随着1-3帧的延迟。

        第四:屏幕锁屏时surfaceview会销毁重建,textureview不会!

        三.具体实现核心代码

        1.viewpager的初始化

[Java] 查看源文件 复制代码
madapter = imagebrowsefragmentpageradapter(supportfragmentmanager, this, imgs)
 imgs_viewpager.offscreenpagelimit = 1
 imgs_viewpager.adapter = madapter
 imgs_viewpager.currentitem = mposition


 //为了处理首次点击时视频播放的问题
 val message = message.obtain()
 message.what = start_play_video
 mhandler.sendmessagedelayed(message, 200)

        2.handler处理消息

[Java] 查看源文件 复制代码
private val start_play_video = 0
private var delete_video = 1
private var delete_video_start_play = 2
private var mhandler = handler(handler.callback { msg ->
  when (msg.what) {
   //开始播放视频
   start_play_video -> notifydispatch.dispatch(previewplayvideoevent(mposition))
   //删除视频时刷新ui
   delete_video -> {
    madapter

        3.删除视频或图片的处理逻辑

[Java] 查看源文件 复制代码
 private fun deletephotos(position: int) {
  if (imgs!!.isempty()) {
   return
  }
  threaddispatch.right_now.execute({
   var file: file

        4.viewpager对应的adapter

[Java] 查看源文件 复制代码
package com.immomo.camerax.gui.view.adapter;
import android.content.context;
import android.os.bundle;
import android.support.v4.app.fragment;
import android.support.v4.app.fragmentmanager;
import android.support.v4.app.fragmentstatepageradapter;
import android.support.v4.app.fragmenttransaction;
import android.view.view;
import android.view.viewgroup;
import com.immomo.camerax.gui.fragment.previewimgfragment;
import com.immomo.camerax.gui.fragment.previewvideofragment;
import java.util.arraylist;
import java.util.list;

/**
 * created by liuxu on 2018/3/26.
 */

public class imagebrowsefragmentpageradapter extends fragmentstatepageradapter {
 private context mcontext;
 private list<string> datas;
 private int mcurrentselectedposition = -1;
 private fragmentmanager mfragmentmanager;
 private fragmenttransaction mfragmenttransaction;
 private arraylist<fragment> mfragments = new arraylist<>();

 public imagebrowsefragmentpageradapter(fragmentmanager fm, context context, list<string> datas) {
  super(fm);
  mfragmentmanager = fm;
  mcontext = context;
  this.datas = datas;
 }

 public void removecontext(){
  mcontext = null;
 }

 @override
 public void setprimaryitem(viewgroup container, int position, object object) {
  mcurrentselectedposition = position;
 }

 @override
 public void startupdate(viewgroup container) {
  super.startupdate(container);
 }

 public void setimgs(list<string> imgs) {
  this.datas = imgs;
  notifydatasetchanged();
 }

 //处理更新无效----删除条目
 @override
 public int getitemposition(object object) {
  return position_none;
 }

 public int getprimaryitemposition() {
  return mcurrentselectedposition;
 }

 public imagebrowsefragmentpageradapter(fragmentmanager fm) {
  super(fm);
 }

 @override
 public boolean isviewfromobject(view view, object object) {
  return view == ((fragment) object).getview();
 }

 @override
 public fragment getitem(int position) {
  bundle bundle = new bundle();
  bundle.putstring("url", datas.get(position));
  bundle.putint("position", position);
  if (datas.get(position).endswith(".jpg")) {
   previewimgfragment previewimgfragment = new previewimgfragment();
   previewimgfragment.setarguments(bundle);
   return previewimgfragment;
  } else {
   previewvideofragment previewvideofragment = new previewvideofragment();
   previewvideofragment.setarguments(bundle);
   return previewvideofragment;
  }
 }

 @override
 public int getcount() {
  return datas == null 

        5显示图片对应的fragment

[Java] 查看源文件 复制代码
package com.immomo.camerax.gui.fragment;
import android.os.bundle;
import android.support.annotation.nullable;
import android.support.v4.app.fragment;
import android.view.layoutinflater;
import android.view.view;
import android.view.viewgroup;
import com.bumptech.glide.glide;
import com.immomo.camerax.r;
import com.immomo.camerax.foundation.util.statusbarutils;
import com.immomo.camerax.gui.view.resizablephotoview;
/**
 * created by liuxu on 2018/3/27.
 */
public class previewimgfragment extends fragment {
 @nullable
 @override
 public view oncreateview(layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) {
  view view = inflater.inflate(r.layout.fragment_preview_photo, null);
  resizablephotoview resizablephotoview = view.findviewbyid(r.id.customphotoview);
  string url = getarguments().getstring("url");
  glide.with(getcontext()).load(url).into(resizablephotoview);
  resizablephotoview.setonclicklistener(new view.onclicklistener() {
   @override
   public void onclick(view view) {
    getactivity().finish();
   }
  });
  return view;
 }

 @override
 public void onpause() {
  super.onpause();
 }

 @override
 public void onresume() {
  super.onresume();
 }

 @override
 public void ondetach() {
  super.ondetach();
 }

 @override
 public void ondestroyview() {
  super.ondestroyview();
 }

 @override
 public void onstart() {
  super.onstart();
 }

 @override
 public void ondestroy() {
  super.ondestroy();
 }

 @override
 public void setuservisiblehint(boolean isvisibletouser) {
  super.setuservisiblehint(isvisibletouser);
 }
}

        6.图片根据宽度适配高度的自定义view

[Java] 查看源文件 复制代码
package com.immomo.camerax.gui.view;
import android.content.context;
import android.graphics.drawable.drawable;
import android.util.attributeset;
import com.github.chrisbanes.photoview.photoview;

/**
 * created by liuxu on 2018/4/7.
 */

public class resizablephotoview extends photoview {
 public resizablephotoview(context context) {
  super(context);
 }

 public resizablephotoview(context context, attributeset attr) {
  super(context, attr);
 }

 public resizablephotoview(context context, attributeset attr, int defstyle) {
  super(context, attr, defstyle);
 }

 @override
 protected void onmeasure(int widthmeasurespec, int heightmeasurespec) {
  drawable d = getdrawable();
  if (d != null){
   int width = measurespec.getsize(widthmeasurespec);
   //高度根据使得图片的宽度充满屏幕计算而得
   int height = (int) math.ceil((float) width * (float) d.getintrinsicheight() / (float) d.getintrinsicwidth());
   setmeasureddimension(width, height);
  }else {
   super.onmeasure(widthmeasurespec, heightmeasurespec);
  }
 }
}

        7.播放视频对应的fragment

[Java] 查看源文件 复制代码
/**
 * created by liuxu on 2018/3/27.
 */

public class previewvideofragment extends fragment {
 private imageview mphotoview;
 private textureview mtextureview;
 private string murl;
 private int mposition;
 private androidmediaplayer mijkvodmediaplayer;
 private boolean misselected;
 private boolean misfirstprepared;
 private previewplayvideosubscriber mpreviewplayvideosubscriber = new previewplayvideosubscriber() {
  @override
  public void oneventmainthread(previewplayvideoevent event) {
   super.oneventmainthread(event);
   mdlog.e("liuxu",event.getposition()+"");
   if (event != null && event.getposition() == mposition) {
    //说明是当前条目
    if (mijkvodmediaplayer != null && !mijkvodmediaplayer.isplaying()) {
     if (mtextureview != null) {
      mijkvodmediaplayer.setsurface(msurface);
      mijkvodmediaplayer.prepareasync();
      mphotoview.setvisibility(view.visible);
     }
    }
    misselected = true;
   } else {
    if (mijkvodmediaplayer != null && mijkvodmediaplayer.isplaying()) {
     mijkvodmediaplayer.pause();
     mijkvodmediaplayer.stop();
    }

    if (mphotoview != null) {
     mphotoview.setvisibility(view.visible);
    }
    misselected = false;
   }

  }
 };
 private string mwidth;
 private string mheight;

 @nullable
 @override
 public view oncreateview(layoutinflater inflater, @nullable viewgroup container, @nullable bundle savedinstancestate) {
  mpreviewplayvideosubscriber.register();
  view view = inflater.inflate(r.layout.fragment_preview_video, null);
  mphotoview = view.findviewbyid(r.id.photoview);
  mtextureview = view.findviewbyid(r.id.surfaceview);
  murl = getarguments().getstring("url");
  mposition = getarguments().getint("position");
  layoutplayer();
  loadvideoscreenshot(getcontext(), murl, mphotoview, 1);
  view.setonclicklistener(new view.onclicklistener() {
   @override
   public void onclick(view view) {

    release();
    getactivity().finish();
   }
  });
  inittexturemedia();
  return view;
 }

 private void inittexturemedia() {
  mtextureview.setsurfacetexturelistener(msurfacetexturelistener);
 }

 private void play(string url) {
  try {
   mijkvodmediaplayer = new androidmediaplayer();
   mijkvodmediaplayer.reset();
   mijkvodmediaplayer.setdatasource(url);
   //让mediaplayer和textureview进行视频画面的结合
   mijkvodmediaplayer.setsurface(msurface);
   //设置监听
   mijkvodmediaplayer.setonbufferingupdatelistener((mp, percent) -> {

   });
   mijkvodmediaplayer.setoncompletionlistener(mp -> {
    mp.seekto(0);
    mp.start();
   });
   mijkvodmediaplayer.setoninfolistener((mp1, what, extra) -> {
      if (what == imediaplayer.media_info_video_rendering_start) {
       mphotoview.setvisibility(view.gone);
       misfirstprepared = true;
      }
      return false;
     });
   mijkvodmediaplayer.setonerrorlistener((mp, what, extra) -> false);
   mijkvodmediaplayer.setonpreparedlistener(mp -> {
    mp.start();
    if (!misfirstprepared){
    }else {
     mphotoview.setvisibility(view.gone);
    }
   });
   mijkvodmediaplayer.setscreenonwhileplaying(true);//在视频播放的时候保持屏幕的高亮
   if (misselected){
    //异步准备
    mijkvodmediaplayer.prepareasync();
   }
  } catch (exception e) {
   e.printstacktrace();
  }
 }

 private surface msurface;
 private textureview.surfacetexturelistener msurfacetexturelistener = new textureview.surfacetexturelistener() {
  @override
  public void onsurfacetextureavailable(surfacetexture surface, int width, int height) {
   msurface = new surface(surface);
   play(murl);
  }

  @override
  public void onsurfacetexturesizechanged(surfacetexture surface, int width, int height) {

  }

  @override
  public boolean onsurfacetexturedestroyed(surfacetexture surface) {
   if (msurface != null){
    msurface.release();
    msurface = null;
   }
   if (mtextureview != null){
    if (build.version.sdk_int >= build.version_codes.o) {
     mtextureview.releasepointercapture();
    }
   }
   release();
   return false;
  }
  @override
  public void onsurfacetextureupdated(surfacetexture surface) {

  }
 };


 @override
 public void onstart() {
  super.onstart();
 }
 @override
 public void onattach(context context) {
  super.onattach(context);
 }

 @override
 public void ondetach() {
  super.ondetach();
 }

 @override
 public void onpause() {
  mdlog.e("liuxu", "onpause" + mposition);
  //处理锁屏时播放器停止播放
  if (mijkvodmediaplayer != null && mijkvodmediaplayer.isplaying()){
   mijkvodmediaplayer.pause();
   mijkvodmediaplayer.stop();
  }
  super.onpause();
 }

 //屏幕打开时重新播放
 @override
 public void onresume() {
  mdlog.e("liuxu", "onresume" + mposition);
  super.onresume();
  if (misselected && mijkvodmediaplayer != null && !mijkvodmediaplayer.isplaying()) {
   mijkvodmediaplayer.prepareasync();
  }
 }

 @override
 public void ondestroy() {
  mdlog.e("liuxu", "ondestroy");
  release();
  if (mpreviewplayvideosubscriber.isregister()) {
   mpreviewplayvideosubscriber.unregister();
  }
  super.ondestroy();
 }

 private void release() {
  if (mijkvodmediaplayer == null) {
   return;
  }
  if (mijkvodmediaplayer.isplaying()) {
   mijkvodmediaplayer.stop();
  }
  mijkvodmediaplayer.release();
  mijkvodmediaplayer = null;
 }

 @override
 public boolean getuservisiblehint() {
  return super.getuservisiblehint();
 }

 /**
  * 动态设置视频宽高信息
  */
 private void layoutplayer() {
  //获取视频宽高比
  getplayinfo(murl);
  float ratio = float.parsefloat(mheight) / float.parsefloat(mwidth);
  mdlog.e("type", mposition + "ratio" + ratio);
  int type = 0;
  //添加容错值
  if (ratio < mediaconstants.instance.getaspect_ratio_1_1().tofloat() + mediaconstants.instance.getscreen_default_value()
    && ratio > mediaconstants.instance.getaspect_ratio_1_1().tofloat() - mediaconstants.instance.getscreen_default_value()) {
   type = screenadapterutils.instance.getscale_type_11();
  } else if (ratio < mediaconstants.instance.getaspect_ratio_4_3().tofloat() + mediaconstants.instance.getscreen_default_value()
    && ratio > mediaconstants.instance.getaspect_ratio_4_3().tofloat() - mediaconstants.instance.getscreen_default_value()) {
   type = screenadapterutils.instance.getscale_type_43();
   mdlog.e("type", "43");
  } else if (ratio < mediaconstants.instance.getaspect_ratio_16_9().tofloat() + mediaconstants.instance.getscreen_default_value()
    && ratio > mediaconstants.instance.getaspect_ratio_16_9().tofloat() - mediaconstants.instance.getscreen_default_value()) {
   type = screenadapterutils.instance.getscale_type_169();
   mdlog.e("type", "169");
  }

  framelayout.layoutparams layoutparams = (framelayout.layoutparams) mtextureview.getlayoutparams();
  layoutparams.height = screenadapterutils.instance.getsurfaceheight(type);
  mtextureview.setlayoutparams(layoutparams);
  framelayout.layoutparams params = (framelayout.layoutparams) mphotoview.getlayoutparams();
  params.height = screenadapterutils.instance.getsurfaceheight(type);
  mphotoview.setlayoutparams(params);
  mdlog.e("params.height", params.height + "");
 }


 private void getplayinfo(string muri) {
  android.media.mediametadataretriever mmr = new android.media.mediametadataretriever();
  try {
   if (muri != null) {
    mmr.setdatasource(muri);
   } else {
    //mmr.setdatasource(mfd, moffset, mlength);
   }

   //宽
   mwidth = mmr.extractmetadata(android.media.mediametadataretriever.metadata_key_video_width);
   //高
   mheight = mmr.extractmetadata(android.media.mediametadataretriever.metadata_key_video_height);
//   mbitmap = mmr.getframeattime(1 );

  } catch (exception ex) {
  } finally {
   mmr.release();
  }

 }

 public static void loadvideoscreenshot(final context context, string uri, imageview imageview, long frametimemicros) {
  // 这里的时间是以微秒为单位
  requestoptions requestoptions = requestoptions.frameof(frametimemicros);
  requestoptions.set(frame_option, mediametadataretriever.option_closest);
  requestoptions.transform(new bitmaptransformation() {
   @override
   protected bitmap transform(@nonnull bitmappool pool, @nonnull bitmap totransform, int outwidth, int outheight) {
    return totransform;
   }

   @override
   public void updatediskcachekey(messagedigest messagedigest) {
    try {
     messagedigest.update((context.getpackagename() + "rotatetransform").getbytes("utf-8"));
    } catch (exception e) {
     e.printstacktrace();
    }
   }
  });
  glide.with(context).load(uri).apply(requestoptions).into(imageview);
 }
}

        4.结语

        笔者使用这种方式实现了项目需求,但是由于本人接触音视频的相关内容比较少,全是在不断探索和学习中前进,如有不足之处请评论指正,谢谢。大家共同学习共同进步。






        

17

主题

9334

帖子

2322

安币

Android大神

Rank: 6Rank: 6

发表于 2018-5-21 14:34:47 | 显示全部楼层
安卓巴士是个不错的网站,我来顶个贴~

20

主题

9304

帖子

2333

安币

Android大神

Rank: 6Rank: 6

发表于 2018-5-21 21:13:48 | 显示全部楼层
感谢大神~

443

主题

1203

帖子

1948

安币

手工艺人

发表于 2018-5-22 04:09:01 | 显示全部楼层
不错不错,楼主辛苦了。。。

0

主题

9379

帖子

2395

安币

Android大神

Rank: 6Rank: 6

发表于 2018-5-22 09:54:20 | 显示全部楼层
支持楼主,支持安卓巴士!

400

主题

1132

帖子

322

安币

手工艺人

发表于 2018-5-22 16:02:47 | 显示全部楼层
感谢分享,安卓巴士有你更精彩:lol

434

主题

1117

帖子

467

安币

手工艺人

发表于 2018-5-22 21:24:44 | 显示全部楼层
不错不错,楼主辛苦了。。。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

领先的中文移动开发者社区
18620764416
7*24全天服务
意见反馈:1294855032@qq.com

扫一扫关注我们

Powered by Discuz! X3.2© 2001-2019 Comsenz Inc.( 粤ICP备15117877号 )