Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make WebView keep a video or audio playing in the background?

Let us suppose, I have the following basic application:

public class MainActivity extends AppCompatActivity {

   private WebView webView;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       webView = (WebView) findViewById(R.id.webview);
       webView.getSettings().setJavaScriptEnabled(true);

       webView.setWebViewClient(new WebViewClient(){

           @Override
           public boolean shouldOverrideUrlLoading(WebView view, String url){
               return true;
           }

       });

       webView.loadUrl("https://www.w3schools.com/html/html5_video.asp");
   }

}

Now, if a website, e. g. https://www.w3schools.com/html/html5_video.asp, includes a video or audio (the URL is unknown to me because the user can open any site) and the user opens another app or turns off the screen, the video or audio is stopped.

However, I would like it to continue. It should be similar to what Google Chrome does:

Videos continue playing in background when using Google Chrome

I have seen solutions, starting a background sound service, however, how can I find out the URL of the video/sound file if it is unknown to me? Do I need to inject some JavaScript or is there a cleaner solution?

UPDATE: I am able to get the video URL with JavascriptInterface, but it is often a blob (e. g. in YouTube). How can I proceed with that?

UPDATE 2: As you can see, I have found a solution. However, I am not sure whether this is a clean solution. Does anyone have a better solution – maybe with controls in the notification bar like in Chrome?

like image 667
Anonymous Avatar asked Aug 26 '18 18:08

Anonymous


1 Answers

After searching a lot, I found this thread. I did something similar: Just extend WebView and override onWindowVisibilityChanged.

public class MediaWebView extends WebView {

   public MediaWebView(Context context) {
       super(context);
   }

   public MediaWebView(Context context, AttributeSet attrs) {
       super(context, attrs);
   }

   public MediaWebView(Context context, AttributeSet attrs, int defStyleAttr) {
       super(context, attrs, defStyleAttr);
   }

   @Override
   protected void onWindowVisibilityChanged(int visibility) {
       if (visibility != View.GONE) super.onWindowVisibilityChanged(View.VISIBLE);
   }

}

This way, the audio continues to play if the screen is locked or another app is opened. However, there will be no controls in the notification bar or on the lockscreen.

like image 155
Anonymous Avatar answered Oct 20 '22 02:10

Anonymous