如题:谷歌自身的bug,VideoView持有ActivityContext引用,导致内存泄漏。

 

解决方法:

1.  xml中定义容器【如果在xml定义VideoView,那么VideoView持有的是ActivityContext】

        <RelativeLayout
            android:id="@+id/video_view_container"
            android:layout_width="match_parent"
            android:layout_height="202dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"/>

2. activity 或 fragment中,通过容器加载VideoView

    if (mVideoViewContainer != null) {
      mVideoViewContainer.removeAllViews();
    }
    mVideoViewContainer = view.findViewById(R.id.video_view_container);
    mVideoView = new VideoView(mContext.getApplicationContext());
    mVideoViewContainer.addView(mVideoView);

3. 界面转后台或退出时,资源释放:

   

  @Override
  public void onDestroyView() {
    super.onDestroyView();
    mVideoView.stopPlayback();
    mVideoView.setOnCompletionListener(null);
    mVideoView.setOnPreparedListener(null);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    mVideoViewContainer.removeAllViews();
    mVideoView = null;
  }

 

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐