Exoplayer не останавливается после закрытия приложения в PagerAdapter - PullRequest
0 голосов
/ 20 сентября 2019

У меня проблема с Exoplayer для остановки после закрытия приложения или изменения фрагмента из BottomNavigationView, я получаю данные из моего API, который приводится к Recyclerview / Adapter, который обрабатывает данные, затем данные сизображения и видео показываются с помощью PagerAdapter.

Я также попытался во фрагменте установить onDestroy, но не работает.

FeedAdapter.java

public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> {
    private final List<FeedData> feedList;
    private Activity context;
    private View.OnClickListener onClickListener;
    private SimpleExoPlayer videoPlayer;

    REST apiService =
            RestClient.getClient().create(REST.class);

    public FeedAdapter(Activity context, List<FeedData> feedList) {
        this.context = context;
        this.feedList = feedList;
        this.onClickListener = onClickListener;
    }

    public List<FeedData> getFeedData(){
        return feedList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_feed_photo, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.mBinding.setFeed(feedList.get(position));

        Boolean isLiked = holder.mBinding.getFeed().getIsLiked();
        Boolean isSaved = holder.mBinding.getFeed().getIsSaved();
        String username = holder.mBinding.getFeed().getUsername();

        if (holder.mBinding.getFeed().getAvatar().length() > 0) {
            Glide.with(context).load(holder.mBinding.getFeed().getAvatar())
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(holder.mBinding.userAvatar);
        }

        holder.mBinding.username.setText(username);
        holder.mBinding.description.setHashtagModeColor(ContextCompat.getColor(context, R.color.fitnessm8_green));
        holder.mBinding.description.addAutoLinkMode(AutoLinkMode.MODE_HASHTAG, AutoLinkMode.MODE_MENTION);
        holder.mBinding.description.setAutoLinkText(holder.mBinding.getFeed().getDescription());
        holder.mBinding.likecount.setText(holder.mBinding.getFeed().getLikes().toString());
        holder.mBinding.likecounttext.setText(context.getResources().getString(R.string.likes));
        holder.mBinding.commentcount.setText(holder.mBinding.getFeed().getComments().size() + " " + context.getResources().getString(R.string.comments));
        holder.mBinding.viewMoreComment.setText(context.getResources().getString(R.string.view) + " " + holder.mBinding.getFeed().getComments().size() + " " + context.getResources().getString(R.string.comments));

        holder.mBinding.viewMoreComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        if (isLiked) {
            holder.mBinding.like.setLiked(true);
        } else {
            holder.mBinding.like.setLiked(false);
        }

        if (isSaved) {
            holder.mBinding.fav.setLiked(true);
        } else {
            holder.mBinding.fav.setLiked(false);
        }

        if (holder.mBinding.getFeed().getType().equals("image")) {
            if (holder.mBinding.getFeed().getMediaSet().size() > 1) {

                holder.mBinding.image.setVisibility(View.GONE);
                MultiMediaAdapter pagerAdapter = new MultiMediaAdapter(context, holder.mBinding.getFeed().getMediaSet());
                holder.mBinding.viewpagerId.setAdapter(pagerAdapter);

                ScrollingPagerIndicator pagerIndicator = holder.mBinding.indicator;
                pagerIndicator.attachToPager(holder.mBinding.viewpagerId);
            } else {
                holder.mBinding.viewpagerId.setVisibility(View.GONE);
                Glide.with(context).load(holder.mBinding.getFeed().getMediaSet().get(0).getFile())
                        .placeholder(R.drawable.image_placeholder)
                        .error(R.drawable.image_placeholder)
                        .into(holder.mBinding.image);
            }
        }
        if (holder.mBinding.getFeed().getType().equals("video")) {
                holder.mBinding.image.setVisibility(View.GONE);
                MultiMediaAdapter pagerAdapter = new MultiMediaAdapter(context, holder.mBinding.getFeed().getMediaSet());
                holder.mBinding.viewpagerId.setAdapter(pagerAdapter);

                ScrollingPagerIndicator pagerIndicator = holder.mBinding.indicator;
                pagerIndicator.attachToPager(holder.mBinding.viewpagerId);
        }

        holder.mBinding.clickUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(context, UserProfileActivity.class);
                i.putExtra("profileUserID", holder.mBinding.getFeed().getUserId());
                view.getContext().startActivity(i);
            }
        });
    }

    @Override
    public int getItemCount() {
        return feedList.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        ListItemFeedPhotoBinding mBinding;

        public ViewHolder(View itemView) {
            super(itemView);
            mBinding = DataBindingUtil.bind(itemView);
        }
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    public interface ClickListener {
        void onClick(View view, int position);

        void onLongClick(View view, int position);
    }
}

MultiMediaAdapter.java

public class MultiMediaAdapter extends PagerAdapter {
    private PlayerView simpleExoPlayerView;
    private SimpleExoPlayer player;
    private ImageView image;
    Context context;
    List<FeedMediaSet> Media_list;

    public MultiMediaAdapter(Context context, List<FeedMediaSet> Media_list) {
        this.context = context;
        this.Media_list = Media_list;
    }

    @Override
    public int getCount() {
        return Media_list.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        FeedMediaSet mediaObj =  Media_list.get(position);

        if (mediaObj.getType().equals("image")) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.list_item_media_photo,container,false);

            image = view.findViewById(R.id.image);

            Glide.with(context).load(mediaObj.getFile())
                    .placeholder(R.drawable.image_placeholder)
                    .error(R.drawable.image_placeholder)
                    .into(image);

            container.addView(view);
            return view;
        } else if (mediaObj.getType().equals("video")) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.list_item_media_video,container,false);

            simpleExoPlayerView = view.findViewById(R.id.playerView);
            image = view.findViewById(R.id.image);
            image.setVisibility(View.GONE);

            initializePlayer(mediaObj.getFile(), mediaObj.getExtra());

            container.addView(view);
            return view;
        }
        return null;
    }

    private void initializePlayer(String uri, String extra) {

        player = ExoPlayerFactory.newSimpleInstance(context);

        try {
            Uri mp4VideoExtraUri = Uri.parse(uri);

            InputStream inputStream = context.getContentResolver().openInputStream(mp4VideoExtraUri);
            Drawable yourDrawable = Drawable.createFromStream(inputStream, extra);
            simpleExoPlayerView.setDefaultArtwork(yourDrawable);
        } catch (FileNotFoundException e) {
            Drawable yourDrawable = context.getResources().getDrawable(R.drawable.image_attach);
            simpleExoPlayerView.setDefaultArtwork(yourDrawable);
        }

        DataSource.Factory mediaDataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, context.getResources().getString(R.string.app_name)));

        MediaSource videoSource = new ProgressiveMediaSource.Factory(mediaDataSourceFactory)
                .createMediaSource(Uri.parse(uri));
        player.setPlayWhenReady(false);
        player.prepare(videoSource);

        if (simpleExoPlayerView != null) simpleExoPlayerView.setPlayer(player);
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
        releasePlayer();
    }

    private void releasePlayer() {
        if (player != null) {
            player.release();
            player = null;
            simpleExoPlayerView.setPlayer(null);
        }
    }
}
...