Webview重新加载页面获得强制关闭

时间:2014-01-31 20:13:42

标签: android webview forceclose

我正在使用webview加载网页,然后每5秒重新加载此页面。页面加载正常,但5s后应该开始重新加载我得到这个:

特别是在第48行,其中是方法:wvNovaMenzaCammera.reload();

 01-31 21:01:06.198  26188-26361/com.pfittech.menzauniza E/AndroidRuntime﹕ FATAL EXCEPTION: Timer-0
    java.lang.RuntimeException: java.lang.Throwable: Warning: A WebView method was called on thread 'Timer-0'. All WebView methods must be called on the UI thread. Future versions of WebView may not support use on other threads.
            at android.webkit.WebView.checkThread(WebView.java:2093)
            at android.webkit.WebView.reload(WebView.java:955)
            at com.pfittech.menzauniza.CommunityFragment$1$1.run(CommunityFragment.java:48)
            at java.util.Timer$TimerImpl.run(Timer.java:284)
     Caused by: java.lang.Throwable: Warning: A WebView method was called on thread 'Timer-0'. All WebView methods must be called on the UI thread. Future versions of WebView may not support use on other threads.
            at android.webkit.WebView.checkThread(WebView.java:2084)
            at android.webkit.WebView.reload(WebView.java:955)
            at com.pfittech.menzauniza.CommunityFragment$1$1.run(CommunityFragment.java:48)
            at java.util.Timer$TimerImpl.run(Timer.java:284)

有我的代码:

public class CommunityFragment extends Fragment {
WebView wvNovaMenzaCammera;
private static final String TAG = "Cammera 1";
private ProgressDialog progressBarWV1;
public CommunityFragment(){}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_community, container, false);
    wvNovaMenzaCammera = (WebView)rootView.findViewById(R.id.wvCammera1);
    getActivity().runOnUiThread(new Runnable() {
        public void run() {
            WebSettings webSettings = wvNovaMenzaCammera.getSettings();
            wvNovaMenzaCammera.getSettings().setJavaScriptEnabled(true);
            wvNovaMenzaCammera.loadUrl("http://zuzo.sk/ftp/akt-a.jpg");
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    wvNovaMenzaCammera.reload();
                }
            }, 5000, 5000);
        }
    });
    return rootView;
}

1 个答案:

答案 0 :(得分:3)

将TimerTask更改为以下内容:

new TimerTask() {
    @Override
    public void run() {
        runOnUiThread(new Runnable() {
            public void run() {
                wvNovaMenzaCammera.reload();
            }
        });      
    }
}

正如错误日志所示,您必须在UI线程中重新加载WebView,并且您的TimerTask在后台线程中运行。