Home  >  Q&A  >  body text

java - 怎样才能在UI线程中等待okhttp返回结果才进行下一步

PHP中文网PHP中文网2765 days ago422

reply all(6)I'll reply

  • PHPz

    PHPz2017-04-18 10:03:13

    Use Handler:

    //在onCreate()方法外定义一个Handler :
    Handler myHandler = new Handler() {  
        public void handleMessage(Message msg) {   
            switch (msg.what) {   
                case UI_OPRATION:   
                    doSomething();  
                    break;   
            }   
            super.handleMessage(msg);   
        }   
    };
         
    //调用处
    ...
    String version = response.body().string();
    myHandler.sendMessage(UI_OPRATION);
    ...
    

    reply
    0
  • 阿神

    阿神2017-04-18 10:03:13

    Recommend rxjava+retrofit

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:03:13

    //方法一
    message.obj = version;
    
    //方法二
    Bundle bundle = new Bundle();
    bundle.putCharSequence("你的KEY",version);
    message.setData(bundle);
    
    //UI里的handle里面用
    Bundle bundle = message.getData();
    String version = bundle.getCharSequence("你的KEY");
    
    //或者直接
    String version = message.getData().getCharSequence("你的KEY");
    
    //当然,注意判空哦
    

    reply
    0
  • PHPz

    PHPz2017-04-18 10:03:13

    No code, just an idea.
    Originally, in addition to avoiding anr for asynchronous network requests, there is another important reason, which is to achieve parallel operations. And the effect you want is actually the effect of synchronous execution.
    So the implementation method is to use the handler to process the data, and use a loading view to isolate user operations. Process it after getting the callback.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:03:13

    After you request the data, just versionmsg.obj=version装进去,然后在OnCreate中handleMessage(Message msg)get the version and continue to request the data asynchronously

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:03:13

    The answers above are all good. Let me add something extra. Okhttp in the square family is very easy to use. It will be even easier to use if retrofit of the family itself is added. Retrofit+Rx is very good at handling between threads and exception handling is also very good.

    reply
    0
  • Cancelreply