WebView - Youtube videos playing in background on rotation and minimise

后端 未结 2 1798
南旧
南旧 2021-02-10 16:08

I have an issue with WebView, basically I am loading in a forum that has embedded videos in places, if you play a video then rotate the device the video keeps playing in the bac

2条回答
  •  隐瞒了意图╮
    2021-02-10 16:55

    Pausing/Resuming the Video

    The simple way to do this is to pause the WebView when you wish the video to stop playing (i.e. when the app goes into the background). This is simply accomplished by the following code:

    WebView view = (WebView) findViewById(R.id.webView);
    view.onPause();    // This will pause videos and needs to be called for EVERY WebView you create
    view.pauseTimers(); // This will pause JavaScript and layout for ALL WebViews and only needs to be called once to affect all WebViews
    

    The best place to handle this logic is to put your pausing code in the onPause() method of your Activity, and to resume the WebView when the activity comes back in view of the user in onResume:

    WebView mWebView; // Initialize this somewhere
    
    @Override
    protected void onPause(){
        super.onPause();
        if(mWebView != null){
            mWebView.onPause();
            mWebView.pauseTimers();
        }
    }
    
    @Override
    protected void onResume(){
        super.onResume();
        if(mWebView != null){
            mWebView.onResume();
            mWebView.resumeTimers();
        }
    }
    

    You may be interested in the onPause and onResume as well as the pauseTimers/resumeTimers methods in the WebView.

    Handling Orientation Changes

    If you don't want your Activity to restart when you rotate the screen (which will stop the WebView from being recreated) then just put

    android:configChanges="orientation|screenSize|keyboardHidden|keyboard"
    

    in the tag of your Activity in your AndroidManifest file. This is not a good practice to follow normally, but when you are using a complex native view like the WebView, it is okay to do (Android web browsers use this to avoid being recreated on rotate). What will happen when using this tag is that the layout will just be resized to fit the landscape orientation and you will have to manually handle any layout specific changes that were being handled using -port or -land folders in your resources. If you are only using one layout though then it is not a problem.

    Please see this question/answer for more info on this, and note that it is not encouraged but it will work.

提交回复
热议问题