Web 视图 - 无法添加窗口 - 令牌空不适用于应用程序



我需要在Service中运行WebView。包含我从 browser.xml 中获取的 Web 视图的标记。这是我的代码片段:

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);
}

一切正常,但应用程序经常崩溃并出现错误:

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)

此错误的原因是上下文,但就我而言,我没有将上下文设置为 WebView。

如何解决这个问题?

谢谢。

我可以提供另一个建议。与其直接打开WebView,不如创建一个在其 XML 布局中具有WebViewActivityService Activity并使用

Intent intent = new Intent(getBaseContext(), WebViewActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);

这将永久消除BadTokenException的可能性。此外,WebView的 URL 可以作为额外内容在从Service传递到ActivityIntent中传递。

最新更新