Android开发 WebView TextToSpeech异常

使用WebView的Activity在finish后抛出异常:

E/ActivityThread: Activity XXXActivity has leaked ServiceConnection android.speech.tts.TextToSpeech$Connection@xxxxxxxx that was originally bound here

android.app.ServiceConnectionLeaked: Activity XXXActivity has leaked ServiceConnection android.speech.tts.TextToSpeech$Connection@xxxxxxxx that was originally bound here


转载请注明出处:http://blog.csdn.net/u013258802/article/details/54380384


我的代码:

webView = (WebView) findViewById(R.id.webview);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true); // 支持JS
webView.loadUrl(StringUtil.nullToEmpty(url));
webView.setWebViewClient(new WebViewClient(){
      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
           view.loadUrl(url);
           return true;
      }
});
webView.setWebChromeClient(new WebChromeClient() {
      @Override
      public void onProgressChanged(WebView view, int newProgress) {
           super.onProgressChanged(view, newProgress);
           //...
});

主要问题出在WebView开启了JavaScript后TextToSpeech模块抛出异常:

settings.setJavaScriptEnabled(true);


解决方式是在实例化WebView时使用ApplicationContext(),方法很多,例如动态创建WebView:

ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
webView = new WebView(getApplicationContext());
webView.setLayoutParams(lp);
再添加到事先XML定义好的容器内

// 添加到视图容器
RelativeLayout rlContainer = (RelativeLayout) findViewById(R.id.rl_find_detail_container);
rlContainer.addView(webView);

答案来源(by Vikram):http://stackoverflow.com/questions/18038772/leaked-window-exception-even-though-no-service-is-used/18798305#18798305

关键点:

The problem: TextToSpeech.connectToEngine() uses Context to call bindService(). The context is your Activity's context (passed on from WebView).When your Activity is destroyed and recreated on screen rotation, the TTS service is still bound while the context isn't valid anymore. This is what the exception refers to.

Activity的Context生命周期太短,所以需要使用全局的context创建WebView。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值