在Android中播放Exo播放器时关闭活动

时间:2018-08-23 14:55:15

标签: android onbackpressed exoplayer activity-finish

我正在播放用于播放视频的视频网址列表(列表大小为200),并且我使用exo播放器而不是播放第15个以上的视频,而不是我调用finish()方法,但是活动未关闭,视频只是暂停了exo播放器,并且活动仍然存在

活动未完成的原因是什么?

请提前帮助我。

public class EventVideosPlayingActivity extends BaseActivity {

@BindView(R.id.tv_name)
TextView mUserName;
@BindView(R.id.tv_time)
TextView mTime;
@BindView(R.id.follow_count_txt)
Button follow_unfollow_txt;
@BindView(R.id.tv_caption)
TextView mCaption;
@BindView(R.id.video_view)
SimpleExoPlayerView mVideoView;
@BindView(R.id.progress_bar)
ProgressBar mProgressBar;
@BindView(R.id.likeBtn)
Button mLikeBtn;
@BindView(R.id.right_btn)
Button mRightBtn;
@BindView(R.id.left_btn)
Button mLeftBtn;
@BindView(R.id.follow_unfollow_btn)
Button mFollowBtn;
@BindView(R.id.like_count_txt)
Button mLikeCountTxt;

int remainder;
private EventsResModel mEventResModel;
private SimpleExoPlayer mExoPlayer;
private ProfileResModel mMyProfileResModel, mOtherProfileResModel;
private int pos = 0, checkPosition = 0;
private CacheDataSourceFactory mCacheDataSrcFactory;
private ArrayList<PromoterVideoModel.Resource> mPostsList = new ArrayList<>();
private int ProfileID;
private int mDeleteLikeID;
private String mFilter;
private boolean mIsAlreadyBlocked, isBlockedme, mIsAlreadyFollowing, isNextVideo, isLoadedData;
private String usertype, replaceString;
private int mOtherProfileID, mMyProfileID;
private int mQuotient, mTotalCount;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE); //Remove title bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //Remove notification bar
    this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.activity_on_deman_audo_video_view);
    ButterKnife.bind(this);
    initView();
}

private void initView() {

    setSwipeListenerForVideoView();
    checkPosition = getIntent().getIntExtra(AppConstants.POSITION, 0);
    mPostsList = (ArrayList<PromoterVideoModel.Resource>) getIntent().getSerializableExtra(AppConstants.ONDEMAND_DATA);
    mOtherProfileID = Integer.parseInt(mPostsList.get(pos).getProfileID());
    mMyProfileResModel = (ProfileResModel) getIntent().getSerializableExtra(AppConstants.MY_PROFILE_OBJ);
    mMyProfileID = mMyProfileResModel.getID();
    mFilter = getIntent().getStringExtra("Filter");
    pos = checkPosition;

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        onBackPressed();
    }
    return super.onKeyDown(keyCode, event);
}

public void onBackPressed() {
    releasePlayer();
    finish();
    return;
}

@Override
protected void onResume() {
    super.onResume();
    initializePlayer();
    mPostsList.removeAll(Collections.singleton(null));
    isNextVideo = true;
    mQuotient = mPostsList.size() / 10;
    if (mPostsList != null && mPostsList.size() > 0)
        playVideo();
    updateVideoList();
}

@SuppressLint("ClickableViewAccessibility")
private void setSwipeListenerForVideoView() {
    mVideoView.setOnTouchListener(new OnSwipeTouchListener(EventVideosPlayingActivity.this) {

        public void onSwipeRight() {
            isNextVideo = false;
            if (mPostsList.size() - 1 > pos) {
                managePrevVideoAndPlayer();
            } else {
                mVideoView.setFocusable(false);
            }
        }

        public void onSwipeLeft() {
            isNextVideo = true;
            manageNextVideoAndPlayer();
        }
    });
}

private void initializePlayer() {
    mVideoView.setUseController(false);
    BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
    TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
    TrackSelector mTrackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
    LoadControl mLoadControl = new DefaultLoadControl(new DefaultAllocator(true, 16 * 1024),
            25000, 30000, 2500, 5000);

    mExoPlayer = ExoPlayerFactory.newSimpleInstance(
            new DefaultRenderersFactory(this),
            mTrackSelector, mLoadControl);

    mExoPlayer.addListener(new ExoPlayer.EventListener() {
        @Override
        public void onTimelineChanged(Timeline timeline, Object manifest) {
            sysOut("Listener-onTimelineChanged...");
        }

        @Override
        public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
            sysOut("Listener-onTracksChanged...");
        }

        @Override
        public void onLoadingChanged(boolean isLoading) {
            sysOut("Listener-onLoadingChanged...isLoading:" + isLoading);
        }

        @Override
        public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
            sysOut("Listener-onPlayerStateChanged..." + playbackState);
            if (playbackState == ExoPlayer.STATE_BUFFERING) {
                mProgressBar.setVisibility(View.VISIBLE);
            } else if (playbackState == ExoPlayer.STATE_READY) {
                mProgressBar.setVisibility(View.GONE);
            } else if (playbackState == ExoPlayer.STATE_ENDED) {
                if (mExoPlayer != null)
                    if (isNextVideo)
                        manageNextVideoAndPlayer();
                    else
                        managePrevVideoAndPlayer();
            }
        }

        @Override
        public void onPlayerError(ExoPlaybackException error) {
            sysOut("Listener-onPlayerError...");
            showToast(EventVideosPlayingActivity.this, "Can't play this video");
            if (isNextVideo)
                manageNextVideoAndPlayer();
            else
                managePrevVideoAndPlayer();
        }

        @Override
        public void onPositionDiscontinuity() {
            sysOut("Listener-onPositionDiscontinuity...");
        }

        @Override
        public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
            sysOut("Listener-onPlaybackParametersChanged...");
        }

    });
    mVideoView.requestFocus();
    mVideoView.setPlayer(mExoPlayer);
    mVideoView.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIT);
    mExoPlayer.setPlayWhenReady(mExoPlayer.getPlayWhenReady());
    mExoPlayer.seekTo(0, 0);

    Cache mCache = new SimpleCache(getCacheDir(),
            new LeastRecentlyUsedCacheEvictor(getCacheDir().getUsableSpace()));
    mCacheDataSrcFactory = new CacheDataSourceFactory(mCache,
            new DefaultHttpDataSourceFactory("ua"),
            CacheDataSource.FLAG_BLOCK_ON_CACHE | CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR);
}



private void manageNextVideoAndPlayer() {
    runOnUiThread(new Runnable() {

        @Override
        public void run() {

            // Stuff that updates the UI
            if (pos <= mPostsList.size()) {

                if (mQuotient != 0 && mPostsList.size() / 10 == mQuotient) {
                    if (pos < mPostsList.size()) {
                        updateVideoList();
                    }
                }

                pos = pos + 1;                  
                if (pos < mPostsList.size()) {
                    if (isAlreadyLikedPost()) {
                        mLikeBtn.setBackground(ContextCompat.getDrawable(EventVideosPlayingActivity.this, R.drawable.like_click_to_like_bg));
                        mLikeBtn.setTag("unlike");
                    } else {
                        mLikeBtn.setBackground(ContextCompat.getDrawable(EventVideosPlayingActivity.this, R.drawable.like_to_like_click_bg));
                        mLikeBtn.setTag("like");
                    }
                    isAlreadyFollowed();
                    playVideo();
                } else {
                    if (mExoPlayer != null) {
                        mExoPlayer.seekToDefaultPosition();
                        mExoPlayer.setPlayWhenReady(false);
                        finish();
                    }
                }
            } else {
                if (mExoPlayer != null) {
                    mExoPlayer.seekToDefaultPosition();
                    mExoPlayer.setPlayWhenReady(false);
                    finish();
                }
            }
        }
    });


}

private void updateVideoList() {
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            //TODO your background code
            if (mTotalCount != mPostsList.size() && isLoadedData == false) {
                isLoadedData = true;
                callGetPromoterVideosWhilePlaying(EventVideosPlayingActivity.this, mFilter, mPostsList.size(), true);
            }
        }
    });
}

private void managePrevVideoAndPlayer() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            //TODO your background code
            if (pos >= 0) {
                if (pos < mPostsList.size() && pos >= 0) {
                    pos = pos - 1;

                    if (isAlreadyLikedPost()) {
                        mLikeBtn.setBackground(ContextCompat.getDrawable(EventVideosPlayingActivity.this, R.drawable.like_click_to_like_bg));
                        mLikeBtn.setTag("unlike");
                    } else {
                        mLikeBtn.setBackground(ContextCompat.getDrawable(EventVideosPlayingActivity.this, R.drawable.like_to_like_click_bg));
                        mLikeBtn.setTag("like");
                    }
                    isAlreadyFollowed();
                    playVideo();
                } else {
                    if (mExoPlayer != null) {
                        mExoPlayer.seekToDefaultPosition();
                        mExoPlayer.setPlayWhenReady(false);
                        finish();
                    }
                }
            } else {
                if (mExoPlayer != null) {
                    mExoPlayer.seekToDefaultPosition();
                    mExoPlayer.setPlayWhenReady(false);
                    finish();
                }
            }
        }
    });

}

@Override
protected void onDestroy() {
    DialogManager.hideProgress();
    super.onDestroy();
}

private void playVideo() {
    try {
        if (mPostsList.get(pos).getCaption() != null || !mPostsList.get(pos).getCaption().equals("")) {
            if (mPostsList.get(pos).getCaption().contains(" ")) {
                mCaption.setText(mPostsList.get(pos).getCaption());
            } else {
                mCaption.setText(URLDecoder.decode(mPostsList.get(pos).getCaption(), "UTF-8"));
            }
        }
        mPostsList.get(pos).setViewCount(mPostsList.get(pos).getViewCount() + 1);
        replaceString = mPostsList.get(pos).getVideoUrl().replaceAll(" ", "%20");
        Uri uri = Uri.parse(UrlUtils.AWS_S3_BASE_URL + replaceString);

        MediaSource mediaSource = new ExtractorMediaSource(uri, mCacheDataSrcFactory,
                new DefaultExtractorsFactory(), null, null);
        mExoPlayer.setPlayWhenReady(true); //run file/link when ready to play.
        mExoPlayer.prepare(mediaSource, true, false);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void releasePlayer() {
    if (mExoPlayer != null) {
        if (mExoPlayer.getPlayWhenReady()) {
            mExoPlayer.stop();
        }
        mExoPlayer.release();
        mExoPlayer = null;
    }
}

@Override
public void onStop() {
    super.onStop();
    releasePlayer();
}

public void callGetPromoterVideosWhilePlaying(final BaseActivity activity, String filter, int mOffset, boolean mIsLoadMore) {
    int mLimit = 40;
    String fields = "*";
    activity.sysOut("API-TYPE: " + "GET");
    activity.sysOut("API-OPERATION: " + UrlUtils.BASE_URL + UrlUtils.GALLERY_VIDEO + "?fields=" + fields + "&filter=" + filter +
            "&limit=" + mLimit + "&offset=" + mOffset + "&include_count=true");
    if (!mIsLoadMore)
        DialogManager.showProgress(activity);

    String mOrderBy = "CreatedAt ASC";

    RetrofitClient.getRetrofitInstance().getRetrofitApiInterface().callGetPromotersVideos(fields, filter, APIConstants.mPromoterGalleryRelated,
            mOrderBy, mLimit, mOffset, true)
            .enqueue(new Callback<PromoterVideoModel>() {
                @Override
                public void onResponse(Call<PromoterVideoModel> call, Response<PromoterVideoModel> response) {
                    DialogManager.hideProgress();
                    if (response.isSuccessful()) {
                        PromoterVideoModel mModel = response.body();
                        assert mModel != null;
                        if (mModel.getResource().size() > 0) {
                            isLoadedData = false;
                            mTotalCount = mModel.getMeta().getCount();
                            if (mQuotient != 0 && mPostsList.size() / 10 == mQuotient) {
                                mPostsList.addAll(mModel.getResource());
                                mVideoView.setFocusable(true);
                                mQuotient = mPostsList.size() / 10;
                            }
                        }
                    } else {
                        //showToast(EventVideosPlayingActivity.this, "" + response.message());
                        if (mExoPlayer != null) {
                            mExoPlayer.seekToDefaultPosition();
                            mExoPlayer.setPlayWhenReady(false);
                            finish();
                        }
                    }
                }

                @Override
                public void onFailure(Call<PromoterVideoModel> call, Throwable t) {
                    DialogManager.hideProgress();
                    mVideoView.setFocusable(true);
                    if (mExoPlayer != null) {
                        mExoPlayer.seekToDefaultPosition();
                        mExoPlayer.setPlayWhenReady(false);
                        finish();
                    }
                    showToast(EventVideosPlayingActivity.this, getResources().getString(R.string.internet_err));
                }
            });
}



@Override
public void retrofitOnFailure() {
    super.retrofitOnFailure();
    releasePlayer();
}

@Override
public void retrofitOnFailure(int code, String message) {
    super.retrofitOnFailure(code, message);
    releasePlayer();
}

@Override
public void retrofitOnSessionError(int code, String message) {
    super.retrofitOnSessionError(code, message);
    releasePlayer();
}

@Override
public void retrofitOnError(int code, String message, int responseType) {
    super.retrofitOnError(code, message, responseType);
    releasePlayer();
}

}

0 个答案:

没有答案