Skip to content Skip to sidebar Skip to footer

Stop Android App Audio Playing When Device Locked

I have a situation where we have an Android app using a webview. When the user navigates to a YouTube video, it starts playing (with audio), and then the user locks the device usin

Solution 1:

I had the same problem with Google rejecting the app because the the webview continues to play the audio from the youtube video when you pressed the power button to turn off the screen.

For some reason it seems that pressing the power button doesn't trigger the webview's onPause(), which is why the audio continues to play. While this is useful for say to keep the music playing while the screen is off, Google doesn't like this behavior for youtube videos.

To make Google happy, you can override onPause() of your activity/fragment like this:

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

Pressing the power button will now also trigger the webview's onPause(). This however creates another problem: what about the audio that you actually want to keep playing while the screen is off?

One fix I came up with is to override the WebViewClient's onLoadResource(), which allows me to check whether the resource is from youtube, which determines whether the webview's onPause() should be called when the time comes. Something like this:

myCustomWebView.setWebViewClient(new WebViewClient() {
    @Override
    public void onLoadResource(WebView webview, String url) {
        super.onLoadResource(webview, url);
        if (url.contains("youtube.com")) mShouldPause = true;
    }

    //...... plus any other method you want to override

});

Of course, this does mean that any resource that has "youtube.com" in it's url will trigger the flag, but for my need this will suffice. So the onPause() method will now look something like this:

@Override
public void onPause() {
    super.onPause();
    // mShouldPause is just a private boolean
    if (mShouldPause) {
        myCustomWebView.onPause();
    }
    mShouldPause = false;
}

So this is the solution I came up with without messing around with the webview's internal workings using reflection. You may want to create a notification that has a button to stop the audio or brings the user back to your app so the user does't forget which app is making the sound and think the phone is haunted!!!


Post a Comment for "Stop Android App Audio Playing When Device Locked"