You can do this using the WebView evaluateJavascript()
method.
First of all you need to create an event in your webpage javascript, and add the event handler:
window.appResumeEvent = new Event('appresume');
window.addEventListener('appresume', yourFunction, false);
function yourFunction() {…}
It's important that you set create the app resume event in global scope (which can be achieved by setting it as a property of the window
).
Now, in your Android onResume()
method, run the evaluateJavascript()
method:
@Override
protected void onResume() {
super.onResume();
mainWebView.evaluateJavascript("(function() { window.dispatchEvent(appResumeEvent); })();", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
}
});
}
Note the javascript has to be wrapped in an immediately-invoked function expression. Also note dispatchEvent()
takes the event variable as the argument, not the event name string.
More info: Creating and dispatching events in javascript (MDN)
For my full MainActivity.java
click show snippet:
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView mainWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainWebView = findViewById(R.id.activity_main_webview);
mainWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mainWebView.loadUrl("file:///android_asset/www/index.html");
}
@Override
protected void onResume() {
super.onResume();
mainWebView.evaluateJavascript("(function() { window.dispatchEvent(appResumeEvent); })();", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
}
});
}
}