I\'ve searched many threads and still cannot find the answer to my question. I\'m working on an Android
app which uses WebView
.
I use
As user2113581 commented, moving the WebView into a context of the application rather than the Activity is a potential solution. This still has all of the pitfalls that user2113581 mentioned, including not working (because it creates a window, but an application context does not have a window token).
I have extended my Application to manage my webview...
MyApplication.java:
public class MyApplication extends Application {
private WebView mWebView;
private boolean mWebViewInitialized;
// ...
@Override public void onCreate() {
super.onCreate();
mWebView = new WebView(this);
mWebViewInitialized = false; // we do some initialization once in our activity.
}
public WebView getWebView() { return mWebView; }
public boolean isWebViewInitialized() { return mWebViewInitialized; }
public void setWebViewInitialized(boolean initialized) {
mWebViewInitialized = initialized;
}
}
In our activity:
@Override protected void onCreate(Bundle savedInstanceState) {
// ...
MyApplication app = (MyApplication) getApplication();
mWebView = app.getWebView();
if (!app.isWebViewInitialized()) {
/* first time initialization */
app.setWebViewInitialized(true);
}
}
Finally, in your Activity, you will want to add the mWebView
to a container view (FrameLayout, or similar) during a lifecycle event that makes sense. You'll need to remove it from the container when the activity is being paused or stopped. I've used onResume
and onPause
with good results.