I need to be able to pause and resume an app that uses a WebView based on whether the app is in the foreground or the background. Currently the app, which has audio, keep running in the background making sound when it loses focus, even when I go to the lock screen. This is very annoying to a user! Apart from that the app works well.
My Android app consists entirely of a single WebView that contains a single HTML page. The HTML page contains JavaScript which changes the HTML page over time, the app looks like a book and the book's pages turn. Each book page also has audio associated with it which plays when the page turns. The key point though is its a single self-changing HTML page inside a WebView.
I have read lots and lots of articles about storing state, Android lifecycle, onPause() and onResume() and it all seems to assume you have programmatic control of what's happening inside the app at runtime. But I just have one object, a WebView, and the single HTML page with CSS, JavaScript, audio and images running inside it, which is inaccessible to me.
Here is the cut-down code I thought would work and which seems to be trying to do the right thing, namely when the app pauses it tries to pause the WebView, and when the app resumes it tries to resume the WebView.
public class MainActivity extends AppCompatActivity {
private WebView mywebview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebview = (WebView)findViewById(R.id.webView);
WebSettings webSettings = mywebview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess();
webSettings.setAllowFileAccessFromFileURLs();
webSettings.setAllowUniversalAccessFromFileURLs();
mywebview.loadUrl("file:///android_asset/book.html");
mywebview.setWebViewClient(new WebViewClient());
}
// Pause/Resume webview on app going to background
@Override
public void onPause(){
super.onPause();
mywebview.onPause();
}
@Override
public void onResume(){
super.onResume();
mywebview.onResume();
}
}
Unfortunately it doesn't work.
Can someone please advise how to make this work, or if I am taking the wrong approach and what the right approach is. I would really appreciate code examples, I am new to Android Studio.