我有一个如下所示的实现,它将动态创建的js返回到webview的shouldInterceptRequest方法,但是我需要在它之前创建一个请求并在返回inputStream之前等待它的答案。我怎么能让它等待呢。
我可以为此准备和同步请求,它解决了问题,但我只是想知道有没有办法在新线程中执行此操作。
MRURLProtocol.mapDomain("gamification.fs", new MRProtocolResponseHandler() {
@Override
public InputStream handle(Uri uri) {
InputStream stream = null;
myApplication.getChamp().getImpulser().invokeRequest(method, body,new OnWebApiResponseArrived() {
@Override
public void OnSuccess(Object obj) {
String configString = "(function () { if (typeof(window) === 'undefined') ..... %s ....";
configString = String.format(configString, obj);
stream = new ByteArrayInputStream(configString.getBytes());
}
@Override
public void OnFail(String errMsg) {
String configString = "(function () { if (typeof(window) === 'undefined')..... %s ....";
configString = String.format(configString, errMsg);
stream = new ByteArrayInputStream(configString.getBytes());
}
});
// NEED TO WAIT FOR stream before return
return stream;
}
});
调用请求(以显示它正在处理新线程)
public void invokeRequest(String entryPoint,String body,final OnWebApiResponseArrived callback ){
GameApiRequest request = new GameApiRequest();
request.setEntryPoint(entryPoint);
request.setBody(body);
request.setUIResponseHandler(new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.obj != null){
if(msg.what == MCStatics.ResponseMessageCode)
callback.OnSuccess(msg.obj);
else
callback.OnFail("please,try again later.");
}
}
}
});
Thread thread = new Thread(request);
thread.start();
}
答案 0 :(得分:0)
我使用countdownlatch解决了这个问题,
private final CountDownLatch responseLatch = new CountDownLatch (1);
MRURLProtocol.mapDomain("gamification.fs", new MRProtocolResponseHandler() {
@Override
public InputStream handle(Uri uri) {
InputStream stream = null;
myApplication.getChamp().getImpulser().invokeRequest(method, body,new OnWebApiResponseArrived() {
@Override
public void OnSuccess(Object obj) {
String configString = "(function () { if (typeof(window) === 'undefined') ..... %s ....";
configString = String.format(configString, obj);
stream = new ByteArrayInputStream(configString.getBytes());
responseLatch.countDown();
}
@Override
public void OnFail(String errMsg) {
String configString = "(function () { if (typeof(window) === 'undefined')..... %s ....";
configString = String.format(configString, errMsg);
stream = new ByteArrayInputStream(configString.getBytes());
responseLatch.countDown();
}
});
try {
responseLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return stream;
}
});