I need to run WebView
in a Service
. The markup containing the WebView I take from browser.xml
. Here is my code snippet:
public class OverlayWindow extends Service {
private WindowManager windowManager;
private View browserView;
private WebView webView;
private WindowManager.LayoutParams browserViewParams;
@Override
public void onCreate() {
super.onCreate();
browserView = layoutInflater.inflate(R.layout.browser, null);
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
webView = (WebView) browserView.findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webView.loadUrl(url);
return true;
}
}
browserViewParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_FULLSCREEN,
PixelFormat.TRANSLUCENT);
windowManager.addView(browserView, browserViewParams);
}
Everything works well, but often the application crashes with the error:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application at android.view.ViewRootImpl.setView(ViewRootImpl.java:571) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:246) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) at android.app.Dialog.show(Dialog.java:281) at android.app.AlertDialog$Builder.show(AlertDialog.java:951)
The reason for this error is that the Context, but in my case I don't set the Context to WebView.
How this problem can be solved?
Thanks.