【问题标题】:WebView - Unable to add window -- token null is not for an applicationWebView - 无法添加窗口 - 令牌 null 不适用于应用程序
【发布时间】:2015-03-15 19:13:35
【问题描述】:

我需要在Service 中运行WebView。包含我从browser.xml 获取的 WebView 的标记。这是我的代码 sn-p:

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)

这个错误的原因是Context,但在我的情况下我没有将Context设置为WebView。

如何解决这个问题?

谢谢。

【问题讨论】:

  • 你用的是什么版本的安卓?通常,您应该避免在 Service 中使用 webview,因为它不能很好地工作。
  • 尝试在您的 webViewClient 中放置一个空的 onRecievedError() 方法(覆盖它),因为如果在服务中运行,默认实现可能会导致崩溃。另外,不要无条件覆盖 shouldOverrideUrlLoading,因为它是can result in errors
  • @LittleChild ,不,它不是重复的,因为 OP 正在询问特定的错误消息。
  • 感谢您的回答! @JonasCz 我在 Android 4.4.4 上有两台平板电脑。在一台平板电脑上工作正常,但在另一台平板电脑上出现错误。但是onRecievedError() 在页面加载时没有捕捉到错误。

标签: java android android-intent android-webview android-service


【解决方案1】:

我可以提供另一个建议。与其直接打开WebView,不如创建一个在其XML 布局中具有WebViewActivity,然后从Service 使用

开始这个Activity
Intent intent = new Intent(getBaseContext(), WebViewActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-28
    • 2019-01-04
    • 2011-12-17
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多