Calling View methods on another thread than the UI thread.錯誤

今天開發中有一項需求是webView顯示列表數據並分享到新浪 微信 朋友圈等。

分享接口是調用原生接口的:

    /**
     * 分享
     *
     * @param sns_Json 分享SnsShareEntity實體 --> json格式
     */
    @JavascriptInterface
    public void shareGood(String sns_Json) {
        Logger.e("分享  :"+sns_Json);
        final SnsShareEntity snsShareEntity = GsonUtil.GetFromJson(sns_Json, SnsShareEntity.class);
        if (snsShareEntity != null) {
        //調用Umeng的分享接口
        initShare();
        ShareUtils.sendVideoShare(context, topBar, new GoodShareInterFace(mController, snsShareEntity, context, ""));
        }
    }

webView中直接調用shareGood方法,分享到微信 微信朋友圈、QQ都是沒有問題,唯獨分享到新浪微博的是報錯:
Calling View methods on another thread than the UI thread

根據提示和結合自己的項目分析:
webview調用shareGood方法,本身是屬於webview裏js調用,不屬於UiThread;
當分享新浪微博的時候,新浪微博是打開一個網頁登錄界面的。所以需要運行在UiThread中,導致報錯。

最後在stackoverflow中搜索出一個解決方案:
java.lang.IllegalStateException: Calling View methods on another thread than the UI thread

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        // Code for WebView goes here
    }
});


// This code is BAD and will block the UI thread
webView.loadUrl("javascript:fn()");
while(result == null) {
  Thread.sleep(100);
}

所以最後我自己修改了shareGood方法,如下:

    /**
     * 分享
     *
     * @param sns_Json 分享SnsShareEntity實體 --> json格式
     */
    @JavascriptInterface
    public void shareGood(String sns_Json) {
        Logger.e("分享  :"+sns_Json);
        final SnsShareEntity snsShareEntity = GsonUtil.GetFromJson(sns_Json, SnsShareEntity.class);
        if (snsShareEntity != null) {
            //解決Calling View methods on another thread than the UI thread.錯誤
//          topBar.postDelayed(new Runnable() {
//              @Override
//              public void run() {
//                  // Code for WebView goes here
//                  initShare();
//                  ShareUtils.sendVideoShare(context, topBar, new GoodShareInterFace(mController, snsShareEntity, context, ""));
//              }
//          },1000);

            //解決Calling View methods on another thread than the UI thread.錯誤
            //http://stackoverflow.com/questions/20255920/java-lang-illegalstateexception-calling-view-methods-on-another-thread-than-the
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Code for WebView goes here
                    initShare();
                    ShareUtils.sendVideoShare(context, topBar, new GoodShareInterFace(mController, snsShareEntity, context, ""));
                }
            });
        }
    }

最後解決了問題,記錄下筆記,希望能幫助到其他朋友!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章