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, ""));
                }
            });
        }
    }

最后解决了问题,记录下笔记,希望能帮助到其他朋友!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值