Retrofit 2错误:NetworkOnMainThreadException

时间:2016-03-04 13:05:15

标签: android multithreading retrofit retrofit2

我试图在Android中对我的服务器进行同步请求。 (代码在普通的Java项目中完美运行)

我知道同步请求不应该在主线程上完成,所以我开始一个新的线程来完成网络连接。我也知道可以进行异步调用,但同步调用更适合我的用例。

bool networkingIsDoneHere(){
  dostuff();
  int number = doNetworkCall();
  if(number < 500){
    return true;
  }
  return false
}

问题是我仍然得到&#34; NetworkOnMainThreadException&#34;错误。改装是否以某种方式在主线程上运行,同时在侧线程上执行?

开始新主题:

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();
    }

改造代码

    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)

2 个答案:

答案 0 :(得分:4)

Retrofit可以自动在单独的线程上执行请求,而不是自己启动新线程。您可以致电enqueue();来完成此操作。

Call<MapApiCall> call = api.getDurationJson(foo);

call.enqueue(new Callback<MapApiCall>() {
       @Override
       public void onResponse(Call<MapApiCall> call, Response<MapApiCall> response) {
           //Do something with response
       }

       @Override
       public void onFailure(Call<MapApiCall> call, Throwable t) {
           //Do something with failure
       }
   });

如果您想要同步请求,请在单独的帖子中使用execute()

Call<MapApiCall> call = api.getDurationJson();  
MapApiCall apiCall = call.execute().body();  

如果您出于某种原因想要在不使用线程的情况下禁用NetworkOnMainThreadException

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

但是,如果您不知道StrictMode做了什么,请不要使用它。

答案 1 :(得分:0)

您的问题是在主线程上调用了 createRetrofitAdapter 方法。您正在构建新的Retrofit实例,但绝对无法在UI线程上完成。最简单的快捷方式是在AsyncTask中执行此操作。