java - 怎样才能在UI线程中等待okhttp返回结果才进行下一步
PHP中文网
PHP中文网 2017-04-18 10:01:13
0
6
427
PHP中文网
PHP中文网

认证0级讲师

reply all(6)
PHPzhong

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);
...
阿神

Recommend rxjava+retrofit

Ty80
//方法一
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");

//当然,注意判空哦
PHPzhong

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.

Ty80

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

Peter_Zhu

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template