使用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。