我正在尝试在Android中对我的服务器进行同步请求。(代码在普通Java项目中可以完美运行)
我知道同步请求不应该在主线程上执行,所以我启动了一个新的线程来处理网络请求。我也知道可以使用异步调用,但是同步调用更适合我的用例。
bool networkingIsDoneHere(){
dostuff();
int number = doNetworkCall();
if(number < 500){
return true;
}
return false
}
问题在于我仍然收到“NetworkOnMainThreadException”错误。Retrofit是否在主线程上运行,同时在侧线程上执行?
启动新的线程:
Thread timerThread = new Thread() {
@Override
public void run() {
while (true) {
try {
networkingIsDoneHere();
sleep(getExecutionInterval());
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
@Override
public void startRule() {
timerThread.start();
}
Retrofit 代码
private Retrofit createRetrofitAdapter() throws Exception {
return retrofit = new Retrofit.Builder()
.baseUrl("https://maps.googleapis.com/maps/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public interface ApiGoogleMapsService {
@GET("url...")
Call<MapApiCall> getDurationJson(@Query("origins") String origin, @Query("destinations") String destination);
}
错误:
Caused by: android.os.NetworkOnMainThreadException
be.kul.gj.annotationfw W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
be.kul.gj.annotationfw W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.shutdownAndFreeSslNative(OpenSSLSocketImpl.java:1131)
be.kul.gj.annotationfw W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.close(OpenSSLSocketImpl.java:1126)
be.kul.gj.annotationfw W/System.err: at okhttp3.internal.Util.closeQuietly(Util.java:105)
be.kul.gj.annotationfw W/System.err: at okhttp3.internal.http.StreamAllocation.deallocate(StreamAllocation.java:260)
be.kul.gj.annotationfw W/System.err: at okhttp3.internal.http.StreamAllocation.connectionFailed(StreamAllocation.java:289)
be.kul.gj.annotationfw W/System.err: at okhttp3.internal.http.HttpEngine.close(HttpEngine.java:429)
be.kul.gj.annotationfw W/System.err: at okhttp3.RealCall.getResponse(RealCall.java:270)
be.kul.gj.annotationfw W/System.err: at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198)
be.kul.gj.annotationfw W/System.err: at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160)
be.kul.gj.annotationfw W/System.err: at okhttp3.RealCall.execute(RealCall.java:57)
be.kul.gj.annotationfw W/System.err: at retrofit2.OkHttpCall.execute(OkHttpCall.java:177)
be.kul.gj.annotationfw W/System.err: at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:87)
be.kul.gj.annotationfw W/System.err: at model.GoogleMapsAccess.getTravelDuration(GoogleMapsAccess.java:52)
be.kul.gj.annotationfw W/System.err: at rule.RoutePickupRule.condition(RoutePickupRule.java:40)
execute()
?我已经更新了我的答案。 - Niels Masdorp