Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 退出全屏到正常屏幕后,视频停止并进入初始阶段_Android_Video_Android Videoview_Mediacontroller_Android Fullscreen - Fatal编程技术网

Android 退出全屏到正常屏幕后,视频停止并进入初始阶段

Android 退出全屏到正常屏幕后,视频停止并进入初始阶段,android,video,android-videoview,mediacontroller,android-fullscreen,Android,Video,Android Videoview,Mediacontroller,Android Fullscreen,我正在开发一款视频播放器,在该播放器中,我使用了自定义播放/暂停、全屏等控制按钮用于正常屏幕,并使用了默认媒体控制器用于全屏,我通过添加一个控制按钮进行了自定义,以便可以退出全屏并切换回正常的小屏幕。我可以全屏显示视频,但在全屏模式下单击控制按钮后,视频停止并返回初始状态,尽管全屏可以切换到正常屏幕模式。我应该怎么做或修改我的代码,以便视频可以继续播放?我在谷歌搜索了三个小时,仍然找不到确切的答案 这是我的密码: VideoFragment.java @Override public V

我正在开发一款视频播放器,在该播放器中,我使用了自定义播放/暂停、全屏等控制按钮用于正常屏幕,并使用了默认媒体控制器用于全屏,我通过添加一个控制按钮进行了自定义,以便可以退出全屏并切换回正常的小屏幕。我可以全屏显示视频,但在全屏模式下单击控制按钮后,视频停止并返回初始状态,尽管全屏可以切换到正常屏幕模式。我应该怎么做或修改我的代码,以便视频可以继续播放?我在谷歌搜索了三个小时,仍然找不到确切的答案

这是我的密码:

VideoFragment.java

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_movies, container, false);



        frame = (FrameLayout)rootView.findViewById(R.id.frame);
        frame2 = (FrameLayout)rootView.findViewById(R.id.frame2);
        frame3 = (FrameLayout)rootView.findViewById(R.id.frame3);


        marquee = (TextView)rootView.findViewById(R.id.marquee);
        marquee.setSelected(true);//focusing the marquee

        video = (VideoView) rootView.findViewById(R.id.videoview1);

        seekBar = (SeekBar)rootView.findViewById(R.id.seekBar1);

        runtime = (TextView)rootView.findViewById(R.id.runtime);
        current = (TextView)rootView.findViewById(R.id.current);

        list = (ListView)rootView.findViewById(R.id.list);


            //list.setTextFilterEnabled(true);
            list.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 

           // _context=this;

            listTest = new ArrayList<String>( );
            listSoundNames=new ArrayList<String>();

            play = (ImageButton)rootView.findViewById(R.id.play);
            back = (ImageButton)rootView.findViewById(R.id.prev);
            next = (ImageButton)rootView.findViewById(R.id.next);
            full = (ImageButton)rootView.findViewById(R.id.full);

            //adding listeners
            play.setOnClickListener(this);
            back.setOnClickListener(this);
            next.setOnClickListener(this);
            seekBar.setOnSeekBarChangeListener(this);
            full.setOnClickListener(this);

            //action bar controls
            bar = getActivity().getActionBar();
            bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
            //bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent))); 

            seekBar.setBackgroundColor(Color.BLACK);
           seekBar.setProgressDrawable(getResources().getDrawable( R.drawable.seekbar));
            seekBar.setScaleY(1f);
            ShapeDrawable thumb = new ShapeDrawable(new OvalShape());

            thumb.getPaint().setColor(Color.CYAN);
            thumb.setIntrinsicHeight(20);
            thumb.setIntrinsicWidth(20);

            seekBar.setThumb(thumb);

            EditText editText = new EditText(getActivity().getApplicationContext());
            getActivity().getActionBar().setCustomView(editText);

            Scanner("/sdcard/");//storage path


            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            /////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            if(listTest.size() != 0)
            {

                listAdapter=new VideoListAdapter(getActivity().getApplicationContext(),listSoundNames);
                list.setAdapter(listAdapter);

                list.setOnItemClickListener(new OnItemClickListener() 
                {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
                    {
                        dm=new DisplayMetrics();
                        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
                        //////////////////changing list item background on click///////////////////
                        list.setVisibility(View.GONE);

                        //frame = (FrameLayout)view.findViewById(R.id.frame);
                        //video = (VideoView) view.findViewById(R.id.videoview1);
                        //list.setSelection(position);
                        view.setSelected(true);
                        ///////////////////PROBLEM/////////////

                        for(int a = 0; a < parent.getChildCount(); a++)
                        {
                            list.clearChoices();
                            parent.getChildAt(a).setBackgroundColor(Color.BLACK);


                        }

                        selected_item=position;
                       // view.setBackgroundColor(Color.RED);


                        ////////////////////////////////////////////////////////////////////////////
                        //accessing song path

                        list.setItemChecked(position, true);
                        list.setSelection(position);

                        //accessing the song name
                        String name = (String) ((TextView) view).getText();
                        title = name;
                        marquee.setText(title);
                        //bar.setTitle(title);
                        //Log.e(TAG, name);

                        //Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
                        try{

                            index = position;
                            play.setImageResource(R.drawable.pause);

                            frame2.setVisibility(View.VISIBLE);
                            frame3.setVisibility(View.VISIBLE);
                            frame.setVisibility(View.VISIBLE);      ///is this the problem?
                            video.setVideoPath(listTest.get(position));
                            video.requestFocus();
                            video.start();
                            video.setOnCompletionListener(new OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mp) {

                                    play.setImageResource(R.drawable.play);
                                    video.stopPlayback();
                                    video.clearFocus();
                                    list.setVisibility(View.VISIBLE);
                                    frame.setVisibility(View.GONE);
                                    //seekBar.refreshDrawableState();
                                    frame2.setVisibility(View.GONE);
                                    frame3.setVisibility(View.GONE);


                                }
                            });



                        }



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


                         video.setOnPreparedListener(new OnPreparedListener() {

                                @Override
                                public void onPrepared(MediaPlayer mp) {

                                    seekBar.setMax(video.getDuration());
                                    seekBar.postDelayed(onEverySecond, 1000);

                                    time= video.getDuration();


                                    long sec = (time / 1000) % 60;
                                    long min = (time / (60 * 1000))%60;
                                    long hour = time / (60 * 60 * 1000);

                                    String s = (sec < 10) ? "0" + sec : "" + sec;
                                    String m = (min < 10) ? "0" + min : "" + min;
                                    String h = "" + hour;

                                    String time = "";
                                    if(hour > 0) {
                                        time = h + ":" + m + ":" + s;
                                    } else {
                                        time = m + ":" + s;
                                    }
                                    runtime.setText(""+time);

                                }
                            });
                    }


                });




                }
            return rootView;
            }

     private Runnable onEverySecond=new Runnable() {

            @Override
            public void run() {

                if(seekBar != null) {
                    seekBar.setProgress(video.getCurrentPosition());
                    run = video.getCurrentPosition();
                    long sec2 = (run / 1000) % 60;
                    long min2 = (run / (60 * 1000))%60;
                    long hour2 = run / (60 * 60 * 1000);

                    String s2 = (sec2 < 10) ? "0" + sec2 : "" + sec2;
                    String m2 = (min2 < 10) ? "0" + min2 : "" + min2;
                    String h2 = "" + hour2;

                    String run = "";
                    if(hour2 > 0) {
                        run = h2 + ":" + m2 + ":" + s2;
                    } else {
                        run = m2 + ":" + s2;
                    }
                    current.setText(""+run);

                }

                if(video.isPlaying()) {
                    seekBar.postDelayed(onEverySecond, 1000);
                }

            }
        };

                            ///////////////////orientation change//////////////////////
    /* @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);

             //Checks the orientation of the screen
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

                Toast.makeText(getActivity().getApplicationContext(), "landscape", Toast.LENGTH_SHORT).show();
                video.setLayoutParams(new FrameLayout.LayoutParams(600,270));//changing layout size

            } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){

                Toast.makeText(getActivity().getApplicationContext(), "portait", Toast.LENGTH_SHORT).show();
                video.setLayoutParams(new FrameLayout.LayoutParams(350, dm.widthPixels));//changing layout size
            }


        }*/

                        /////////////////////////////////////////////////////////////////////


     private void Scanner(String path) {
            // TODO Auto-generated method stub
            {
                try 
                {
                        File fl = new File(path);
                        File[] listOfFiles = fl.listFiles();              

                        for (File listOfFile : listOfFiles)
                         {
                            String s = listOfFile.getName();

                            if(s.endsWith(".mp4"))
                            {

                            songpath = listOfFile.getPath();
                            listTest.add(songpath);//adding song names to list
                            //listTest.toString().replaceFirst(songpath, s);



                            // store file name in listSoundNames
                            int pos = s.lastIndexOf(".");
                            if (pos > 0)
                            {
                                song = s.substring(0, pos);
                            }
                            listSoundNames.add(song);

                            }


                            /////////////////////////////////
                            File f = new File(path+s+"/");
                            if (f.exists() && f.isDirectory()) {
                            Scanner(path+s+"/");
                            }
                            ////////////////////////////////


                        }



                }
            catch (Exception e) { }
            }

            }







    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub


        if (v.equals(play))
        {
            if(video.isPlaying())
            {

                video.pause();
                 progress=video.getCurrentPosition();

                //change in button image//
                play.setImageResource(R.drawable.play);

            }
            else
            {
                video.start();
                seekBar.setProgress(video.getCurrentPosition());
                seekBar.setMax(video.getDuration());
                seekBar.postDelayed(onEverySecond, 1000);


                //change in button image//
                play.setImageResource(R.drawable.pause);
                //
            }
        }


            if (v.equals(back))
            {
                video.stopPlayback();
                video.refreshDrawableState();
                //bar.setTitle(song);

                if(index!=0)
                {
                index = index -1;
                selected_item=index;
                listAdapter.notifyDataSetChanged();//shifting the highlight to the song played
                }
                else
                {

                    index = (list.getAdapter().getCount()-1);
                    selected_item=index;
                    listAdapter.notifyDataSetChanged();

                }

                Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
                try {


                    //mp.setDataSource(getActivity().getApplicationContext(), uri);//setting new data source 
                     video.setVideoURI(uri);


                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(getActivity().getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
                }

                try {
                    //video.prepare();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }        
                video.start();
                title = uri.getLastPathSegment();
                marquee.setText(title);

                play.setImageResource(R.drawable.pause);
            }


            if (v.equals(next))
            {

                video.stopPlayback();
                video.refreshDrawableState();

                index = index +1;
                if(index>(listSoundNames.size()-1))
                {
                    index=0;
                }

                play.setImageResource(R.drawable.pause);

                //index = index +1;

                selected_item=index;
                listAdapter.notifyDataSetChanged();
                //Toast.makeText(MP3.this, ""+selected_item, Toast.LENGTH_SHORT).show();
                Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song

                try {


                    //mp.setDataSource(getActivity().getApplicationContext(), uri);//setting new data source 
                     video.setVideoURI(uri);

                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(getActivity().getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
                }

                try {
                    //mp.prepare();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }        
                video.start();
                title = uri.getLastPathSegment();
                marquee.setText(title);


            }

            if(v.equals(full))
            {
                Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
                /*Uri uri = Uri.parse(listTest.get(index).toString());
                Toast.makeText(getApplicationContext(), "full", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Intent.ACTION_VIEW );
                intent.setDataAndType((uri), "video/*");
                startActivity(intent);*/
                Intent intent = new Intent(getActivity().getApplicationContext(),Full.class);  
                Bundle b2 = new Bundle();
                b2.putString("path", uri.toString());
                b2.putInt("progress", video.getCurrentPosition());
                intent.putExtras(b2);
                this.startActivity(intent);

            }


    }

    @Override
    public void onPause() {
        super.onPause();


    }







    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        // TODO Auto-generated method stub

        if(fromUser) {
            // this is when actually seekbar has been seeked to a new position
            video.seekTo(progress);
        }

    }






    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub

    }



    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        // TODO Auto-generated method stub
        int progress = seekBar.getProgress();
                      if (video != null && video.isPlaying()) {
                          // Set the position of the currently playing
                         video.seekTo(progress);
                      }
    }

    ///////////////////////////stopping the current audio/video when tab is swiped/////////////////////////////////

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        // Make sure that we are currently visible
        if (this.isVisible()) {
            // If we are becoming invisible, then...
            ///video.start();
             //Log.e("MyFragment", "Visible again.  Starting audio.");
            //video.clearFocus();
            //play.setImageResource(R.drawable.pause);
            if (!isVisibleToUser) {
                Log.e("MyFragment", "Not visible anymore.  Stopping audio.");
                // TODO stop audio playback

               /* play.setImageResource(R.drawable.play);
                video.stopPlayback();
                video.clearFocus();
                list.setVisibility(View.VISIBLE);
                frame.setVisibility(View.GONE);
                //seekBar.refreshDrawableState();
                frame2.setVisibility(View.GONE);
                */

                //video.stopPlayback();
                video.pause();
                //video.clearFocus();
                play.setImageResource(R.drawable.play);

            }
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
fullsc.xml//全屏布局

  @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.fullsc);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

            Bundle bundle = getIntent().getExtras();
            path = bundle.getString("path");
            pos = bundle.getInt("progress");

            Uri uri = Uri.parse(path);
            video = (VideoView) findViewById(R.id.fullv);
            getActionBar().hide();
           /* video.setMediaController(new MediaController(this){
                public boolean dispatchKeyEvent(KeyEvent event)
                {
                    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
                        ((Activity) getContext()).finish();

                    return super.dispatchKeyEvent(event);
                }
            });*/

            controller = new CMediaController(this);

           /* controller.setPrevNextListeners(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                    //next button clicked
                      Toast.makeText(getApplicationContext(), "next", Toast.LENGTH_SHORT).show();
                      getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                      getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                      v.requestLayout();
                  }
                }, new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                        //previous button clicked
                          Toast.makeText(getApplicationContext(), "prev", Toast.LENGTH_SHORT).show();
                      }
                    });*/

            video.setMediaController(controller); 
            video.setVideoURI(uri);
            video.seekTo(pos);

            video.requestFocus();
            video.start();


        }


}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:background="#000000">

    <VideoView
        android:layout_gravity="center"
        android:id="@+id/fullv"

        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:keepScreenOn="true" 
        />






  </LinearLayout>

任何人真的需要一些建议你能发布错误日志吗?我认为OnPreparedListener是这样的,但我需要查看日志:
public class CMediaController extends MediaController {
     Context mContext;
     //private OnMediaControllerInteractionListener mListener;
    public CMediaController(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        mContext = context;

    }
     @Override 
     public void setAnchorView(View view) {
         super.setAnchorView(view);

         ImageButton full = new ImageButton(mContext);
         full.setBackgroundResource(R.id.full);

         full.setOnClickListener((new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                    //next button clicked
                      Toast.makeText(mContext, "return to small", Toast.LENGTH_SHORT).show();
                      ((Activity) getContext()).finish();//exiting but stopping the video and setting it to initial state


                     /* 
                      Intent intent = new Intent(mContext,VideoFragment.class);  
                    //Bundle b2 = new Bundle();
                    b2.putString("path", uri.toString());
                    b2.putInt("progress", video.getCurrentPosition());
                    intent.putExtras(b2);
                    mContext.startActivity(intent);*/


                  }}));
         /*full = (ImageButton)findViewById(R.id.full);*/
         //full.setOnClickListener(this);
                 FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
         params.gravity = Gravity.RIGHT;
         addView(full, params);
    }
    /*@Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Toast.makeText(mContext, "small", Toast.LENGTH_SHORT).show();

    }*/

    }