安卓webview子线程网络请求,怎么获得结果?

向webview注入网络上的js,就需要请求js的url。但不允许在主线程直接发http请求,需要开子线程,开了子线程后,子线程就自己运行,主线程也自己运行,但是我的主线程需要子线程的结果才能继续往下操作,不然没有意义。我这个不适合网络请求回调,如下是一种简单的解决方式。

就是把请求结果绑定到成员变量。然后检查成员变量。这样就不会造成子线程还没运行完,就迅速获取js的内容,导致是空的,向注入webview注入js失败,。

 

package com.xx.view;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by wj49476 on 2018/3/23.
 */

public class ScriptDownloader {

    private static final String urlPrefix = "http://10.0.4.147:8301/jss/crawl/";
    private String  scriptName;
    private byte[] jsScriptContent;
    private int times = 0;

    public  ScriptDownloader(String scriptNmae){
        this.scriptName = scriptNmae;
    }

    private void get() {
        final String  url = urlPrefix + scriptName;
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Request.Builder builder = new Request.Builder();
                final OkHttpClient client = new OkHttpClient.Builder()
                        .readTimeout(30, TimeUnit.SECONDS)
                        .connectTimeout(30, TimeUnit.SECONDS)
                        .writeTimeout(30, TimeUnit.SECONDS)
                        .build(); //设置各种超时时间
                builder.url(url);
                System.out.println("请求的js脚本url是:" + url);
                final Request request = builder.build();
                try (Response response = client.newCall(request).execute()) {
                    jsScriptContent = (response.body().bytes());
                    System.out.println(new String(jsScriptContent));
                }catch (Exception e){
                    System.out.println("请求脚本出错");
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public byte[] getJsScriptContent(){

        if (times % 5 == 0){
            get();
        }
        times += 1;
        try{
            Thread.sleep(1000);
        }catch (Exception e){
            e.printStackTrace();
        }

        if (jsScriptContent != null){
            return  jsScriptContent;
        }else{
            if (times < 20){
                return getJsScriptContent();
            }
            else{
                return null;
            }
        }
    }
    public static void main(String[] args) {
        byte[] jsConet = new ScriptDownloader("credit/crccReport.js").getJsScriptContent();
        System.out.println("注入的脚本内容是: " + new String(jsConet));
    }
}

 

 

安卓不让做阻塞的io网络请求,但没说不让sleep。

posted @ 2018-03-23 18:08  北风之神0509  阅读(1072)  评论(0编辑  收藏  举报