google / ExoPlayer

This project is deprecated and stale. The latest ExoPlayer code is available in https://github.com/androidx/media
https://developer.android.com/media/media3/exoplayer
Apache License 2.0
21.74k stars 6.03k forks source link

I am using exoplayer in viewpager2 but multiple sound mixing and not pausing player #10583

Closed mayursancheti closed 2 months ago

mayursancheti commented 2 years ago

ExoPlayer Version

2.15.1

Devices that reproduce the issue

All android devices from 8 onwards, i test in moto, nokia, narzo but still same issue

Devices that do not reproduce the issue

-

Reproducible in the demo app?

No

Reproduction steps

i tried below code `package com.example.splashscreen;

import static androidx.viewpager2.widget.ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT;

import androidx.annotation.NonNull; import androidx.viewpager2.widget.ViewPager2;

import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.ViewGroup; import android.widget.Toast;

import com.google.android.material.snackbar.Snackbar; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.messaging.FirebaseMessaging; import com.google.firebase.storage.StorageReference;

import java.util.ArrayList; import java.util.List; import java.util.Objects;

//import static com.example.splashscreen.VideosAdapter.VideoViewHolder.nofication_imag;

public class MainActivity extends common_bottom_menu {

private ViewGroup container;

private MainActivity_VideosAdapter rvOneAdapter;
private StorageReference videoRef;
private DatabaseReference reference,notificaiondata;
private FirebaseDatabase firebaseDatabase;
List<MainActivity_VideoItem> videoItems;
String addit = "no";
ViewPager2 videosViewPager;

@Override
int getContentViewId() {
    return R.layout.activity_main;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //DO NOT ADD setContentView HERE WHEN USE extends common_bottom_menu
    //setContentView(R.layout.activity_main);
   /*swipe videos*/

    FirebaseMessaging.getInstance().subscribeToTopic("hello");
    FirebaseMessaging.getInstance().subscribeToTopic("comment");

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // Create channel to show notifications.
        String channelId  = "11";
        String channelName = "testing";
        NotificationManager notificationManager =
                getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(new NotificationChannel(channelId,
                channelName, NotificationManager.IMPORTANCE_LOW));
    }

    /*check below for start service
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(new Intent(this, notification_myservice.class));
    } else {
        startService(new Intent(this, notification_myservice.class));
    }
    */

    Bundle extras = getIntent().getExtras();
    // UNCOMMENT WHEN SEND NOTIFICAION
    /*if(!getIntent().hasExtra("alreadysent")) {
        Intent intent = new Intent(MainActivity.this, notification_myservice.class);
        this.startActivity(intent);
    }*/

    videosViewPager = findViewById(R.id.viewPagerVideos);
    videosViewPager.setOffscreenPageLimit(1);

    videoItems = new ArrayList<>();

    //Bundle extras = getIntent().getExtras();

    SharedPreferences sh = getSharedPreferences("mylogindetail",MODE_PRIVATE);
    String currentmyuserid = sh.getString("currentuserid", "");

    //reference = firebaseutil.getDatabase().getReference().child("Video");
    reference = firebaseutil.getDatabase().getReference().child("Video");

    notificaiondata = firebaseutil.getDatabase().getReference().child("notifications");
    //reference = FirebaseDatabase.getInstance().getReference().child("Video");

    if(getIntent().hasExtra("refrenckeyis"))
    {
        Snackbar.make(findViewById(android.R.id.content), "viewing  is " +extras.getString("refrenckeyis"), Snackbar.LENGTH_LONG).show();

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

                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    String keyis = ds.getKey();
                    if(Objects.equals(keyis, extras.getString("refrenckeyis"))) {
                        String videolink = ds.child("videolink").getValue(String.class);
                        MainActivity_VideoItem item = new MainActivity_VideoItem();
                        item.videoURL = videolink;//dataSnapshot.getValue(String.class);
                        item.videoTitle = ds.child("creatornam").getValue(String.class);
                        item.videoDesc = ds.child("videotitle").getValue(String.class);
                        item.videocreatoremail = ds.child("creatorid").getValue(String.class);
                        item.videodatakey = keyis;

                        videoItems.add(item);
                        videosViewPager.setAdapter(new MainActivity_VideosAdapter(videoItems));

                    }
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });

    }

    if(getIntent().hasExtra("currntvideokey")) //when video thumbnail click
    {
        //this  "currntvideokey" coming from search video thumbnail click
        String currntvideokey = extras.getString("currntvideokey");
        Toast.makeText(MainActivity.this,currntvideokey+" ",Toast.LENGTH_SHORT).show();
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
               for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    String key1 = ds.getKey();
                   Log.d("",key1+" abcdddd");
                    if(Objects.equals(key1, currntvideokey)) {
                        Log.d("",key1+" Matcheddd");

                        String videolink = ds.child("videolink").getValue(String.class);
                        MainActivity_VideoItem item = new MainActivity_VideoItem();
                        item.videoURL = videolink;//dataSnapshot.getValue(String.class);
                        item.videoTitle = ds.child("creatornam").getValue(String.class);
                        item.videoDesc = ds.child("videotitle").getValue(String.class);
                        item.videocreatoremail = ds.child("creatorid").getValue(String.class);
                        item.videodatakey = key1;
                        videoItems.add(item);
                        videosViewPager.setAdapter(new MainActivity_VideosAdapter(videoItems));

                    }
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });

    }
    else {
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    String keyis = ds.getKey();
                    String videolink = ds.child("videolink").getValue(String.class);
                    MainActivity_VideoItem item = new MainActivity_VideoItem();
                    item.videoURL = videolink;//dataSnapshot.getValue(String.class);
                    item.videoTitle = ds.child("creatornam").getValue(String.class);
                    item.videoDesc = ds.child("videotitle").getValue(String.class);
                    item.videocreatoremail = ds.child("creatorid").getValue(String.class);
                    item.videodatakey = keyis;

                    videoItems.add(item);
                    videosViewPager.setAdapter(new MainActivity_VideosAdapter(videoItems));

                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });
    }

       /* MainActivity_VideoItem item2 = new MainActivity_VideoItem();
        item2.videoURL = "https://firebasestorage.googleapis.com/v0/b/login-25afc.appspot.com/o/Files%2F1661790740641.null?alt=media&token=1796d579-4745-4e3b-befa-1c3f282ac942"; //here add video url
        item2.videoTitle = "Sanjiv Kumar";
        item2.videoDesc = "How you can Became a Software Developer at Twitter";
        videoItems.add(item2);

        /*VideoItem item3 = new VideoItem();
        item3.videoURL = "android.resource://" + getPackageName() + "/"
                + R.raw.video4; //here add video url
        item3.videoTitle = "Rakesh Sharma";
        item3.videoDesc = " any Search Algorithm";
        videoItems.add(item3);*/
        videosViewPager.setAdapter(new MainActivity_VideosAdapter(videoItems));

        videosViewPager.registerOnPageChangeCallback(pageChangeCallback);

    /*swipe videos end*/

}

ViewPager2.OnPageChangeCallback pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        //Stop media here.
    }

    @Override
    public void onPageSelected(int position) {
        //Save your previous position here.
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
};

@Override
public boolean onGenericMotionEvent(MotionEvent event) {
    return super.onGenericMotionEvent(event);
}

}`

and for adapter below code,

`package com.example.splashscreen;

import static android.content.Context.MODE_PRIVATE; import static android.media.MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT;

import static com.example.splashscreen.App.getProxy; import static com.facebook.FacebookSdk.getApplicationContext;

import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Looper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.MediaController; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.VideoView;

import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.FragmentActivity; //import androidx.multidex.BuildConfig; import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.danikula.videocache.BuildConfig; import com.danikula.videocache.HttpProxyCacheServer; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.source.MediaSource; import com.google.android.exoplayer2.source.ProgressiveMediaSource; import com.google.android.exoplayer2.ui.PlayerView; import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory; import com.google.android.exoplayer2.upstream.cache.SimpleCache; import com.google.android.exoplayer2.util.Log; import com.google.android.exoplayer2.util.Util; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.ValueEventListener;

import java.util.HashMap; import java.util.List; import java.util.Objects;

public class MainActivity_VideosAdapter extends RecyclerView.Adapter { private List mVideoItems; DatabaseReference likedata; boolean testclick = true; String TAG = "100";

public MainActivity_VideosAdapter(List<MainActivity_VideoItem> videoItems) {
    mVideoItems = videoItems;
}

@NonNull
@Override
public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    return new VideoViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main_inner_design_container,parent,false));

}

@Override
public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
    likedata = firebaseutil.getDatabase().getReference().child("likevideo");

    SharedPreferences sh = holder.context.getSharedPreferences("mylogindetail",MODE_PRIVATE);
    String currentuserid = sh.getString("currentuserid", "");

    SharedPreferences sh2 = holder.context.getSharedPreferences("currplayvideolink_forlike", MODE_PRIVATE);
    String currentvidokey = sh2.getString("linkisforlike", "");

    holder.setVideoData(mVideoItems.get(position));
    holder.setlikestatus();

    holder.like_on_video.setOnClickListener(view -> {
        if(Objects.equals(currentuserid, "") || currentuserid == null)
        {
            new AlertDialog.Builder(view.getContext())
                    .setTitle("Login Is Required")
                    .setMessage("Please Login To Liked Video")
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                        }
                    }).show();
        }
        else {

            likedata.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    if (snapshot.exists()) {
                        String exist = "false";
                        for (DataSnapshot ds : snapshot.getChildren()) {
                            String tempiskey = ds.getKey();

                            Log.d(TAG, tempiskey + " yesyes");

                            if (Objects.equals(snapshot.child(tempiskey).child("userid").getValue(), currentuserid) && Objects.equals(snapshot.child(tempiskey).child("videokey").getValue(), currentvidokey)) {
                                snapshot.child(tempiskey).getRef().removeValue();
                                exist = "true";
                                holder.like_on_video.setImageResource(R.drawable.ic_notlike);
                                Toast.makeText(holder.context,"Video Not Liked",Toast.LENGTH_SHORT).show();
                            }

                        }

                        if (exist.equals("false")) {
                            HashMap<String, Object> hashMap1 = new HashMap<>();
                            hashMap1.put("userid", currentuserid);
                            hashMap1.put("videokey", currentvidokey);
                            likedata.push().setValue(hashMap1);
                            holder.like_on_video.setImageResource(R.drawable.ic_like);
                            Toast.makeText(holder.context,"Video Liked",Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        HashMap<String, Object> hashMap1 = new HashMap<>();
                        hashMap1.put("userid", currentuserid);
                        hashMap1.put("videokey", currentvidokey);
                        likedata.push().setValue(hashMap1);
                        holder.like_on_video.setImageResource(R.drawable.ic_like);
                        Toast.makeText(holder.context,"Video Liked",Toast.LENGTH_SHORT).show();
                    }
                }

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

                }
            });
        }
    });

    holder.mVideoView.onPause();
    holder.setfollowstatus();

}

@Override
public void onViewAttachedToWindow(@NonNull VideoViewHolder holder) {
    super.onViewAttachedToWindow(holder);
    holder.simpleExoPlayer.setPlayWhenReady(true);
    holder.simpleExoPlayer.getPlaybackState();
}

@Override
public void onViewDetachedFromWindow(@NonNull VideoViewHolder holder) {
    super.onViewDetachedFromWindow(holder);
    holder.simpleExoPlayer.setPlayWhenReady(false);
    holder.simpleExoPlayer.getPlaybackState();
    holder.simpleExoPlayer.release();
    holder.simpleExoPlayer.stop(true);
}

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

 public static class VideoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    //private final ImageView like_on_video;

    SimpleExoPlayer simpleExoPlayer;
    PlayerView mVideoView;
    TextView txtTitle,txtDesc,txtemail,textVideo_datakey;
    ProgressBar mProgressBar;
    ImageView moreoptiontovideo;
    ImageView ic_comment;
    ImageView share_image_on_video;
    ImageView nofication_imag;
    ImageView search_imag;
    ImageView profile_image_on_video;
    ImageView like_on_video;
    ImageView mainpage_play_video,mainpage_pause_video;
    ImageView bucket_image_on_video;
    private Object Context;
    Boolean flaglike = false;
    MediaController mediaController;
    LinearLayout play_pause_controler_video;
    private boolean paused=false;
    //LinearLayout view_product_detail;

    int number_of_clicks = 0;
    boolean thread_started = false;
    final int DELAY_BETWEEN_CLICKS_IN_MILLISECONDS = 250;
    Context context;
    DatabaseReference likedata,followdata, userdata;
    String currentuserid;
    String key;
    TextView textVideo_following;
    String likimagis = "notlike";

    public VideoViewHolder(@NonNull View itemView) {
        super(itemView);
        context =itemView.getContext();

        likedata = firebaseutil.getDatabase().getReference().child("likevideo");

        SharedPreferences sh = ((Activity) context).getSharedPreferences("mylogindetail",MODE_PRIVATE);
        currentuserid = sh.getString("currentuserid", "");

        nofication_imag = itemView.findViewById(R.id.nofication_imag);

        Bundle extras =  ((Activity) context).getIntent().getExtras();
        if(((Activity) context).getIntent().hasExtra("hidenotificationicon")) { //in case from search then hide notification icon
            nofication_imag.setVisibility(View.INVISIBLE);
        }

        mVideoView = itemView.findViewById(R.id.playerview_videos);
       // mVideoView.pause(); //*****

        //Toast.makeText(itemView.getContext(),mVideoView.getCurrentPosition(),Toast.LENGTH_SHORT).show();
        txtTitle = itemView.findViewById(R.id.textVideo_profilename);
        txtDesc = itemView.findViewById(R.id.textVideotitle);
        txtemail = itemView.findViewById(R.id.textVideo_creator_emailid);
        textVideo_datakey = itemView.findViewById(R.id.textVideo_datakey);

        mProgressBar = itemView.findViewById(R.id.progressBar);
        //moreoptiontovideo = itemView.findViewById(R.id.moreoptiontovideo);
        //moreoptiontovideo.setOnClickListener(this);
        ic_comment = itemView.findViewById(R.id.comment_image_on_video);
        ic_comment.setOnClickListener(this);
        share_image_on_video = itemView.findViewById(R.id.share_image_on_video);
        share_image_on_video.setOnClickListener(this);

        nofication_imag.setOnClickListener(this);

        search_imag = itemView.findViewById(R.id.search_imag);
        search_imag.setOnClickListener(this);

        profile_image_on_video = itemView.findViewById(R.id.profile_image_on_video);
        profile_image_on_video.setOnClickListener(this);

        //profile_image_on_video.setContentDescription(txtemail.getText());

        like_on_video = itemView.findViewById(R.id.like_on_video);

        play_pause_controler_video = itemView.findViewById(R.id.play_pause_controler_video);
        /*mediaController = new MediaController(context);
        mediaController.setAnchorView(play_pause_controler_video);
        mVideoView.setMediaController(mediaController);*/
        //mediaController.setVisibility(View.INVISIBLE);

        mVideoView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {   // VIDEO LONG PRESS TO VIEW MORE OPTION

                BottomSheetDialog bottomSheetDialogFragment = new BottomSheetDialog();
                Bundle args = new Bundle();
                args.putString("videokeyis", textVideo_datakey.getText().toString());
                bottomSheetDialogFragment.setArguments(args);
                bottomSheetDialogFragment.show(((FragmentActivity)v.getContext()).getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
                //Toast.makeText(v.getContext() ,"testdfgdfgfgd",Toast.LENGTH_LONG).show();
                return true;
            }
        });

        ImageView when_pause = itemView.findViewById(R.id.when_pause);
        mVideoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (paused) {
                    simpleExoPlayer.setPlayWhenReady(true);
                    mVideoView.onResume();

                    paused = false;
                    when_pause.setVisibility(View.INVISIBLE);
                }
                else {
                    simpleExoPlayer.setPlayWhenReady(false);
                    mVideoView.onPause();
                    paused = true;
                    when_pause.setVisibility(View.VISIBLE);
                }

                ++number_of_clicks;
                if(!thread_started){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            thread_started = true;
                            try {
                                Thread.sleep(DELAY_BETWEEN_CLICKS_IN_MILLISECONDS);
                                if(number_of_clicks == 1){

                                } else if(number_of_clicks == 2){

                                    Looper.prepare();
                                    like_on_video.callOnClick();
                                  }
                                number_of_clicks = 0;
                                thread_started = false;
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                    }).start();
                }
            }
        });

        bucket_image_on_video = itemView.findViewById(R.id.bucket_image_on_video);
        bucket_image_on_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent a = new Intent(bucket_image_on_video.getContext(),buy_now.class);
                a.putExtra("videodatakey",view.getContentDescription());
                bucket_image_on_video.getContext().startActivity(a);
            }
        });

        followdata = firebaseutil.getDatabase().getReference().child("followstatus");
        textVideo_following = itemView.findViewById(R.id.textVideo_following);

        //onclick follow
        textVideo_following.setOnClickListener(view -> {
            if(currentuserid.equals("") || currentuserid == null)
            {
                new AlertDialog.Builder(view.getContext())
                        .setTitle("Login Is Required")
                        .setMessage("Please Login To follow Video")
                        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {

                            }
                        }).show();
            }
            else
            {
                String creatoridis = textVideo_following.getContentDescription().toString();

                followdata.orderByChild("followfrom").equalTo(currentuserid).addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot followsnapshot) {
                        if (followsnapshot.exists()) {
                            String key1 = null;
                            String exist = "false";
                            for (DataSnapshot ds1 : followsnapshot.getChildren()) {
                                key1 = ds1.getKey();
                                //when i am already follow to this user, then below if condition
                                if(Objects.equals(ds1.child("followto").getValue(String.class), creatoridis)) {
                                    followsnapshot.child(key1).getRef().removeValue();
                                    exist = "true";
                                    textVideo_following.setText("Follow");
                                }
                            }
                            //when i am exist in database but not for this user, then insert
                            if(exist.equals("false"))
                            {
                                //textVideo_following.setText("Following");
                                HashMap<String, Object> hashMap1 = new HashMap<>();
                                hashMap1.put("followfrom", currentuserid);
                                hashMap1.put("followto", creatoridis);
                                followdata.push().setValue(hashMap1);
                                textVideo_following.setText("Following");

                            }
                        }
                        else  //when i am not exist in database
                        {
                            //textVideo_following.setText("Following");
                            HashMap<String, Object> hashMap1 = new HashMap<>();
                            hashMap1.put("followfrom", currentuserid);
                            hashMap1.put("followto", creatoridis);
                            followdata.push().setValue(hashMap1);
                            textVideo_following.setText("Following");
                        }
                    }
                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });
            }
        });

        followdata.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                String creatoridis = textVideo_following.getContentDescription().toString();

                if(Objects.equals(dataSnapshot.child("followto").getValue(), creatoridis) && Objects.equals(dataSnapshot.child("followfrom").getValue(), currentuserid)) {
                     textVideo_following.setText("Following");
                }

            }
            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            }
            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                String creatoridis = textVideo_following.getContentDescription().toString();
                if(Objects.equals(dataSnapshot.child("followto").getValue(), creatoridis) && Objects.equals(dataSnapshot.child("followfrom").getValue(), currentuserid)) {
                    textVideo_following.setText("Follow");
                }
            }
            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });

    }

     @Override
    public void onClick(View view) {  //here all icon click call

       if(view.getId()==R.id.comment_image_on_video)
       {
           comment_BottomSheetDialog bottomSheetDialogFragment1 = new comment_BottomSheetDialog();
           bottomSheetDialogFragment1.commentforvideokey = textVideo_datakey.getText().toString();
           // user in comment_BottomSheetDialog file
           bottomSheetDialogFragment1.show(((FragmentActivity)ic_comment.getContext()).getSupportFragmentManager(), bottomSheetDialogFragment1.getTag());
       }
       if(view.getId() == R.id.share_image_on_video)
       {
           Intent sendIntent = new Intent();
           sendIntent.setAction(Intent.ACTION_SEND);
           sendIntent.putExtra(Intent.EXTRA_TEXT,
                   "Hey check out my app at: https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID);
           sendIntent.setType("text/plain");
           view.getContext().startActivity(sendIntent);
       }
        if(view.getId() == R.id.nofication_imag)
        {
            Intent a = new Intent(nofication_imag.getContext(),notification_and_message_view.class);
            a.putExtra("viewtype","notification_only");
            a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            nofication_imag.getContext().startActivity(a);

        }
        if(view.getId() == R.id.search_imag)
        {
            if(((Activity) context).getIntent().hasExtra("hidenotificationicon")) {

                ((Activity) search_imag.getContext()).onBackPressed();
                InputMethodManager imm = (InputMethodManager) search_imag.getContext().getSystemService(search_imag.getContext().INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(search_imag.getWindowToken(), 0);

                //in case from search box coming and go back,then show last state of search activity
            }
            else {
                Intent a = new Intent(search_imag.getContext(), search.class);
                a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                search_imag.getContext().startActivity(a);
            }

        }
        if(view.getId() == R.id.profile_image_on_video)
        {
            if(view.getContentDescription() =="" || view.getContentDescription() == null)
            {
                Toast.makeText(context, "Please Wait or Check internet working", Toast.LENGTH_SHORT).show();
            }
            else {
                Intent a = new Intent(profile_image_on_video.getContext(), other_user_profile.class);
                a.putExtra("useremailidclick", view.getContentDescription());
                a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                profile_image_on_video.getContext().startActivity(a);
            }

        }

    }

    void setVideoData(MainActivity_VideoItem videoItem){
        txtTitle.setText(videoItem.videoTitle);
        txtDesc.setText(videoItem.videoDesc);
        txtemail.setText(videoItem.videocreatoremail);
        textVideo_datakey.setText(videoItem.videodatakey);

        ImageView profile_image_on_video1 = itemView.findViewById(R.id.profile_image_on_video);
        profile_image_on_video1.setContentDescription(txtemail.getText());
        itemView.findViewById(R.id.bucket_image_on_video).setContentDescription(textVideo_datakey.getText());

        textVideo_following = itemView.findViewById(R.id.textVideo_following);
        textVideo_following.setContentDescription(txtemail.getText());
        itemView.findViewById(R.id.textVideo_following).setContentDescription(txtemail.getText());

        //Toast.makeText(itemView.getContext(),currentuserid.toString(),Toast.LENGTH_SHORT).show();

        userdata = firebaseutil.getDatabase().getReference().child("login");
        userdata.orderByChild("emailid").equalTo(videoItem.videocreatoremail).addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {

                    if (snapshot.exists()) {
                        String key2 = null;
                        for (DataSnapshot ds : snapshot.getChildren()) {
                            key2 = ds.getKey();
                            Glide.with(getApplicationContext()).load(snapshot.child(key2).child("photourl").getValue(String.class)).apply(new RequestOptions()).placeholder(R.drawable.ic_userprofile).error(R.drawable.ic_userprofile).circleCrop().into(profile_image_on_video1);
                        }
                    }
                }

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

            }
        });

        HttpProxyCacheServer proxy = App.getProxy(context);
        String proxyUrl = proxy.getProxyUrl(videoItem.videoURL);

       // mVideoView.pause(); //***
        SharedPreferences sharedPreferences = this.context.getSharedPreferences("currplayvideolink_forlike",MODE_PRIVATE);
        SharedPreferences.Editor mygmailedit = sharedPreferences.edit();
        mygmailedit.putString("linkisforlike", videoItem.videodatakey);
        mygmailedit.apply();

        if (simpleExoPlayer != null && simpleExoPlayer.isPlaying()) {

            simpleExoPlayer.stop(true);
            simpleExoPlayer.release();
            simpleExoPlayer = null;
        }

        simpleExoPlayer = new SimpleExoPlayer.Builder(context).build();
        String userAgent = Util.getUserAgent(context, context.getString(R.string.app_name));
        DefaultDataSourceFactory defdataSourceFactory = new DefaultDataSourceFactory(context,userAgent);
        Uri uriOfContentUrl = Uri.parse(proxyUrl);
        MediaSource mediaSource = new ProgressiveMediaSource.Factory(defdataSourceFactory).createMediaSource(uriOfContentUrl);  // creating a media source
        simpleExoPlayer.prepare(mediaSource);
        //video_for_add_text.hideController();
        //simpleExoPlayer.setPlayWhenReady(true); // start loading video and play it at the moment a
        simpleExoPlayer.setVideoScalingMode(VIDEO_SCALING_MODE_SCALE_TO_FIT);
        //simpleExoPlayer.play();

        simpleExoPlayer.setRepeatMode(Player.REPEAT_MODE_ONE); //to loop in video
        simpleExoPlayer.setVideoScalingMode(VIDEO_SCALING_MODE_SCALE_TO_FIT);
        mVideoView.setPlayer(simpleExoPlayer);
        /*mVideoView.setOnPreparedListener(mp -> {
            mProgressBar.setVisibility(View.GONE);

            float videoRatio = (float) mp.getVideoWidth() / (float)mp.getVideoHeight();
            float screenRatio = (float) mVideoView.getWidth() /(float)mVideoView.getHeight() ;
            float scale  = videoRatio / screenRatio;
            if (scale >= 1f){
                mVideoView.setScaleX(scale);
            }else {
                mVideoView.setScaleY(1f / scale);
            }
            // mp.pause();
        });
        mVideoView.setOnCompletionListener(mp -> {
           // mp.pause();
        });*/
    }

    public void setlikestatus() {
        //each swipe refresh like iamge
        likedata.orderByChild("userid").equalTo(currentuserid).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {

                SharedPreferences sh = itemView.getContext().getSharedPreferences("currplayvideolink_forlike", MODE_PRIVATE);
                String currentvidolinko = sh.getString("linkisforlike", "");

                if (snapshot.exists()) {

                    for (DataSnapshot ds : snapshot.getChildren()) {
                        key = ds.getKey();
                        if(Objects.equals(snapshot.child(key).child("videokey").getValue(), currentvidolinko)) {
                            like_on_video.setImageResource(R.drawable.ic_like);
                            //like_on_video.setImageDrawable(ContextCompat.getDrawable(itemView.getContext(), R.drawable.ic_like));
                        }
                    }

                } else {
                    like_on_video.setImageResource(R.drawable.ic_notlike);
                    //like_on_video.setImageDrawable(ContextCompat.getDrawable(itemView.getContext(), R.drawable.ic_notlike));

                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });
    }
     //each swipe refresh follow status *********
     public void setfollowstatus() {
         followdata = firebaseutil.getDatabase().getReference().child("followstatus");
         followdata.orderByChild("followfrom").equalTo(currentuserid).addListenerForSingleValueEvent(new ValueEventListener() {
             @Override
             public void onDataChange(@NonNull DataSnapshot followsnapshot) {
                 String creatoridis = textVideo_following.getContentDescription().toString();
                 if (followsnapshot.exists()) {
                     for (DataSnapshot ds1 : followsnapshot.getChildren()) {
                         if(Objects.equals(ds1.child("followto").getValue(String.class), creatoridis)) {
                             textVideo_following.setText("Following");
                         }
                         else {
                             textVideo_following.setText("Follow");
                         }
                     }
                 }
                 else
                 {
                     textVideo_following.setText("Follow");
                 }
             }
             @Override
             public void onCancelled(@NonNull DatabaseError error) {

             }
         });
     }

 }

}

`

but this program just playing multiple videos sound on swipe , even if i changes activity still exoplayer sound playing in background.

Expected result

  1. one videos in viewpager2 should play once.
  2. it should cached, like tiktok fast loading
  3. if i change activity , then exoplayer should stop.
  4. please check my code there is mistake but i don't found.

Actual result

-

Media

-

Bug Report

icbaker commented 2 years ago

I'm afraid we're unable to review such an enormous amount of code for correctness - we simply don't have the resources.

Please make your question more focussed in order for us to help you.

mayursancheti commented 2 years ago

ok i understand you are confusing code,

step 1) i have declare exoplayer in viewpager

simpleExoPlayer = new SimpleExoPlayer.Builder(context).build();
        String userAgent = Util.getUserAgent(context, context.getString(R.string.app_name));
        DefaultDataSourceFactory defdataSourceFactory = new DefaultDataSourceFactory(context,userAgent);
        Uri uriOfContentUrl = Uri.parse(proxyUrl);
        MediaSource mediaSource = new ProgressiveMediaSource.Factory(defdataSourceFactory).createMediaSource(uriOfContentUrl);  // creating a media source
        simpleExoPlayer.prepare(mediaSource);
        //video_for_add_text.hideController();
        //simpleExoPlayer.setPlayWhenReady(true); // start loading video and play it at the moment a
        simpleExoPlayer.setVideoScalingMode(VIDEO_SCALING_MODE_SCALE_TO_FIT);
        //simpleExoPlayer.play();

        simpleExoPlayer.setRepeatMode(Player.REPEAT_MODE_ONE); //to loop in video
        simpleExoPlayer.setVideoScalingMode(VIDEO_SCALING_MODE_SCALE_TO_FIT);
        mVideoView.setPlayer(simpleExoPlayer);

my code is 1) mixing multiple videos sound is playing when i swipe viewpager or change activity and 2) exoplayer loading very slow for url based video .

sayedsyfuzzaman commented 1 year ago

@mayursancheti I have solved the issue earlier. When the view pager is swiped, it creates another view holder, and every view holder holds a unique playerView instance. So, to control the player, you need to store all holder objects in a hashmap. The hasmaps key will be the adapter position, and the Value will be the viewHolderobject. Ex: var hashMap: HashMap<Int, ViewHolderClass> = HashMap()

In onBindViewHolder, // add holder with its index to map if (hashMap.containsKey(position)){ hashMap.remove(position) } hashMap[position] = holder

Now, pause the previous player when playing new videos. Just get the playing position in the adapter and control (play, pause, or release) the player view of that viewholder. This will help you to understand the video playback inside the view pager.

In Addition, when the page is swiped to another, it calls the onViewDetachedFromWindow function in the adapterclass, So overriding the function, Pause the current playing video. Also you can handle viewPagers OnPageChangeCallback() , override onPageSelected(position: Int). Make a public function inside adapter to pause the current play video and play new video, then call the function from here You can find the solution in my demo project. It will fix the mixing video playback issue. Make sure to release player from onDetachedFromRecyclerViewand onViewRecycled, to optimize the app. `

override fun onViewDetachedFromWindow(holder: VideoViewHolder) {
    super.onViewDetachedFromWindow(holder)
    holder.binding.videoFrame.player?.pause()
    simpleCache.release()

}

override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
    super.onDetachedFromRecyclerView(recyclerView)
    player?.release()
    simpleCache.release()
}

override fun onViewRecycled(holder: VideoViewHolder) {
    super.onViewRecycled(holder)
    holder.binding.videoFrame.player?.release()
    simpleCache.release()
}`

For your reference: https://github.com/sayedsyfuzzaman/Swipeable-Video-Player-Android

ashik024 commented 1 year ago

@mayursancheti I have solved the issue earlier. When the view pager is swiped, it creates another view holder, and every view holder holds a unique playerView instance. So, to control the player, you need to store all holder objects in a hashmap. The hasmaps key will be the adapter position, and the Value will be the viewHolderobject. Ex: var hashMap: HashMap<Int, ViewHolderClass> = HashMap()

In onBindViewHolder, // add holder with its index to map if (hashMap.containsKey(position)){ hashMap.remove(position) } hashMap[position] = holder

Now, pause the previous player when playing new videos. Just get the playing position in the adapter and control (play, pause, or release) the player view of that viewholder. This will help you to understand the video playback inside the view pager.

In Addition, when the page is swiped to another, it calls the onViewDetachedFromWindow function in the adapterclass, So overriding the function, Pause the current playing video. Also you can handle viewPagers OnPageChangeCallback() , override onPageSelected(position: Int). Make a public function inside adapter to pause the current play video and play new video, then call the function from here You can find the solution in my demo project. It will fix the mixing video playback issue. Make sure to release player from onDetachedFromRecyclerViewand onViewRecycled, to optimize the app. `

override fun onViewDetachedFromWindow(holder: VideoViewHolder) {
    super.onViewDetachedFromWindow(holder)
    holder.binding.videoFrame.player?.pause()
    simpleCache.release()

}

override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
    super.onDetachedFromRecyclerView(recyclerView)
    player?.release()
    simpleCache.release()
}

override fun onViewRecycled(holder: VideoViewHolder) {
    super.onViewRecycled(holder)
    holder.binding.videoFrame.player?.release()
    simpleCache.release()
}`

For your reference: https://github.com/sayedsyfuzzaman/Swipeable-Video-Player-Android

Issue solved . Thanks Brother

icbaker commented 2 months ago

Closing because it seems the question was answered above.