滑动viewpager2时如何暂停exoplayer?

fgw7neuy  于 2021-06-30  发布在  Java
关注(0)|答案(0)|浏览(240)

我正在使用viewpager2和exoplayer,视频(来自firebase)。当我在浏览视频时,视频一直在播放,我必须通过再次浏览播放的视频并单击exoplayer暂停按钮来停止播放。我想视频自动停止时,我刷viewpager2。
我怎样才能停止录像?顺便说一下,我是一个非常新的编码一般,甚至在这个网站上,所以我希望得到帮助,而不是打扰任何人。
这是我正在实现的viewpager2类:

public class Dashboard extends AppCompatActivity {
    private static final String TAG = "Dashboard";
    private static final int ACTIVITY_NUM = 0;
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 88888;
    private Context xContext = Dashboard.this;

    int likescount;
    DatabaseReference likesref;

    //uis

    ViewPager2 viewPager2;

    FirebaseUser firebaseUser;

    boolean flag = false;

    DatabaseReference likesrefernce = FirebaseDatabase.getInstance().getReference("likes");

    Boolean likechecker = false;

    String profileid;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dashboard);
        Log.d(TAG, "onCreate: started.");

                    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (firebaseUser != null) {
            firebaseUser.getUid();
        }

        setupBottomNavigationView();
        // getSupportActionBar().setTitle("Videos");

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        viewPager2 = (ViewPager2) findViewById(R.id.vpager);

    }

            FirebaseRecyclerOptions<video> options =
                    new FirebaseRecyclerOptions.Builder<video>()
                            .setQuery(FirebaseDatabase.getInstance().getReference("video"), video.class)
                            .build();
            FirebaseRecyclerAdapter<video, ViewHolder> firebaseRecyclerAdapter =
                    new FirebaseRecyclerAdapter<video, ViewHolder>(options) {
                        @Override
                        protected void onBindViewHolder(@NonNull ViewHolder holder, int position, @NonNull video member) {

                            SharedPreferences prefs = xContext.getSharedPreferences("PREFS", MODE_PRIVATE);
                            profileid = prefs.getString("profileid", "none");

                            holder.setExoplayer(getApplication(), member.getName(), member.getVideourl());
                            FirebaseUser user1 = FirebaseAuth.getInstance().getCurrentUser();
                            assert user1 != null;
                            String currentUserId = user1.getUid();
                            String userId = user1.getUid();
                            final String i = getRef(position).getKey();
                            final String publisher = getRef(position).getKey();

                            DatabaseReference reference3 = FirebaseDatabase.getInstance().getReference("Users").child(member.getPublisher());
                            reference3.addValueEventListener(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                    if (getApplicationContext() == null) {
                                        return;
                                    }
                                    User user3 = dataSnapshot.getValue(User.class);

                                    Glide.with(getApplicationContext()).load(user3 != null ? user3.getImageurl() : null).into(holder.image_profile);
                                    holder.username.setText(user3 != null ? user3.getUsername() : null);

                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError databaseError) {

                                }
                            });

                            likesref = FirebaseDatabase.getInstance().getReference("likes");

                            String likes = "likes";

                            likesref.addValueEventListener(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                                    if (dataSnapshot.child(i).hasChild(userId)) {
                                        likescount = (int) dataSnapshot.child(i).getChildrenCount();
                                        holder.lovers.setImageResource(R.drawable.ic_love2);
                                        holder.lovers_text.setText(Integer.toString(likescount));
                                    } else {
                                        likescount = (int) dataSnapshot.child(i).getChildrenCount();
                                        holder.lovers.setImageResource(R.drawable.ic_love);
                                        holder.lovers_text.setText(Integer.toString(likescount));
                                    }

                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError databaseError) {

                                }
                            });

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

                                    likechecker = true;

                                    likesrefernce.addValueEventListener(new ValueEventListener() {
                                        @Override
                                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                                            if (likechecker.equals(true)) {
                                                if (dataSnapshot.child(i).hasChild(currentUserId)) {
                                                    likesrefernce.child(i).child(currentUserId).removeValue();
                                                    likechecker = false;
                                                } else {
                                                    likesrefernce.child(i).child(currentUserId).setValue(true);
                                                    likechecker = false;
                                                }
                                            }

                                        }

                                        @Override
                                        public void onCancelled(@NonNull DatabaseError databaseError) {

                                        }
                                    });
                                }
                            });

                            holder.comments.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent(xContext, CommentsVideos.class);
                                    intent.putExtra("i", i);
                                    xContext.startActivity(intent);
                                }
                            });

                            holder.comments_text.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent(xContext, CommentsVideos.class);
                                    intent.putExtra("i", i);
                                    xContext.startActivity(intent);
                                }
                            });

                            holder.image_profile.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    SharedPreferences.Editor editor = xContext.getSharedPreferences("PREFS", MODE_PRIVATE).edit();
                                    editor.putString("profileid", member.getPublisher());
                                    editor.apply();
                                    Intent intent = new Intent(xContext, Profile.class);
                                    xContext.startActivity(intent);
                                }
                            });

                            holder.Notification.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent(Dashboard.this, Notifications.class);
                                    startActivity(intent);
                                }
                            });

                            holder.btFullScreen.setOnClickListener(new View.OnClickListener() {
                                @SuppressLint("UseCompatLoadingForDrawables")
                                @Override
                                public void onClick(View view) {
                                    //check condition
                                    if (flag) {
                                        //when flag is true
                                        //set enter full screen image
                                        //set portrait orientation
                                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
                                        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavViewBar);
                                        bottomNavigationView.setVisibility(View.GONE);

                                        flag = false;
                                    } else {
                                        //when flag is false, set exit full screen image
                                        holder.btFullScreen.setImageDrawable(getResources().getDrawable(R.drawable.ic_cross));
                                        //set landscape orientation
                                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);

                                        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavViewBar);
                                        bottomNavigationView.setVisibility(View.GONE);

                                        //set flag value is true
                                        flag = true;
                                    }
                                }
                            });

                        }

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

                            return new ViewHolder(view);
                        }
                    };

    @Override
    protected void onStart() {
        super.onStart();
            firebaseRecyclerAdapter.startListening();
            viewPager2.setAdapter(firebaseRecyclerAdapter);

    }

    @Override
    protected void onStop() {
        super.onStop();
            firebaseRecyclerAdapter.stopListening();

    }

    /**
         * BottomNavigationView setup
         */
        private void setupBottomNavigationView () {
            Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
            BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavViewBar);
            BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationView);
            BottomNavigationViewHelper.enableNavigation(xContext, bottomNavigationView);
            Menu menu = bottomNavigationView.getMenu();
            MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
            menuItem.setChecked(true);
        }

        @Override
        protected void onResume () {
            super.onResume();
            checkPermission();

        }

        //  initializeplayer();

        private void checkPermission () {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                return;
            }
            // request camera permission if it has not been grunted.
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
                    checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED ||
                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            ) {
                requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_PERMISSION_REQUEST_CODE);
            }
        }

        @Override
        public void onRequestPermissionsResult ( int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults){
            switch (requestCode) {
                case CAMERA_PERMISSION_REQUEST_CODE:
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(Dashboard.this, "permission has been grunted.", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(Dashboard.this, "[WARN] permission is not grunted.", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
}

这是viewholder:

public class ViewHolder extends RecyclerView.ViewHolder {

    private final Context context = null;
    SimpleExoPlayer exoPlayer;
    //Initialize variable
    PlayerView playerView;
    ProgressBar progressBar;

    //uis
    ImageView comments, lovers, btFullScreen;
    private SimpleExoPlayer player;
    TextView lovers_text;
    TextView comments_text;
    TextView username1;
    TextView rTitleTv2, Notification, Challenges, username;
    CircleImageView image_profile;
    private User user2 = new User();
    Boolean finished;
    DatabaseReference reference1;

    int likescount;
    int commentscount;
    DatabaseReference likesref, postref;
    private ViewPager2 ViewPager2;
    private OnScrollListener OnScrollListener;
    MediaSource renderers;
    FirebaseUser firebaseUser;
    private Comment comment = new Comment();
    private video video = new video();

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        //uis
        image_profile = itemView.findViewById(R.id.image_profile);
        username = itemView.findViewById(R.id.username);

        comments = itemView.findViewById(R.id.comments);
        comments_text = itemView.findViewById(R.id.comments_text);
        rTitleTv2 = itemView.findViewById(R.id.rTitleTv2);
        Notification = itemView.findViewById(R.id.Notification);
        Challenges = itemView.findViewById(R.id.Challenges);
        btFullScreen = itemView.findViewById(R.id.bt_fullscreen);
        lovers = itemView.findViewById(R.id.lovers);
        lovers_text = itemView.findViewById(R.id.lovers_text);

    }

    public void setExoplayer(Application application, String name, String Videourl){

        TextView textView = itemView.findViewById(R.id.rTitleTv2);
        playerView = itemView.findViewById(R.id.player_view);
        progressBar = itemView.findViewById(R.id.progressBar);
        ImageView exo_pause = itemView.findViewById(R.id.exo_pause);
        ImageView exo_play = itemView.findViewById(R.id.exo_play);
        textView.setText(name);

        try {

            //Initialize load control
            LoadControl loadControl = new DefaultLoadControl();

            BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter.Builder(application).build();
            TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
            exoPlayer = (SimpleExoPlayer) ExoPlayerFactory.newSimpleInstance(application);
            Uri video = Uri.parse(Videourl);
            DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("video");
            ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
            MediaSource mediaSource = new ExtractorMediaSource(video,dataSourceFactory,extractorsFactory,null,null);
            playerView.setPlayer(exoPlayer);
            //keep screen on
            playerView.setKeepScreenOn(true);
            exoPlayer.prepare(mediaSource);
            exoPlayer.setPlayWhenReady(true);

            // ...enable autoplay...

        }catch (Exception e){
            Log.e("ViewHolder","exoplayer error"+e.toString());
        }

        if (exoPlayer == null){
            exo_pause.setImageDrawable(application.getResources().getDrawable(R.drawable.ic_play));

        }

        exoPlayer.addListener(new Player.EventListener() {
            @Override
            public void onTimelineChanged(Timeline timeline, Object manifest, int reason){

            }
            @Override
            public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
            }

            @Override
            public void onLoadingChanged(boolean isLoading) {
                progressBar.setVisibility(isLoading ? View.VISIBLE : View.GONE);
            }

            @Override
            public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {

                if (playbackState == STATE_BUFFERING){
                    //when buffering show progress bar
                    progressBar.setVisibility(View.VISIBLE);

                } else if (playbackState == STATE_READY){
                    //when ready hide
                    progressBar.setVisibility(View.GONE);
                    exoPlayer.isPlaying();

                }

                if (playbackState == STATE_ENDED){
                    //when ready hide
                    exoPlayer.isPlaying();
                    exoPlayer.getRepeatMode();

                }

            }

            @Override
            public void onRepeatModeChanged(int repeatMode ) {
                exo_play.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (exoPlayer != null){
                            exoPlayer.getRepeatMode();
                        }
                    }
                });
            }

            @Override
            public void onPlayerError(ExoPlaybackException error) {

            }

            @Override
            public void onPositionDiscontinuity(int reason) {

            }

            @Override
            public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {

            }
            @Override
            public void onSeekProcessed(){

            }
        });
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题