AsyncTask中的Android networkonmainthread异常

时间:2017-07-07 06:19:59

标签: android android-asynctask

即使我的网络调用位于asynctask内,我也遇到networkonmainthread异常。我调用MyAsynctask获取okhttp响应并在之后将其转换为我的对象。

我读了一些像这样的帖子

1. Calling doInBackground       - 我没有调用doInBackground,如回答我所说的那样执行然后得到。

我的代码在调用请求时是。

Response response = new MyAsyncUtils.MyTask().execute(params).get();

方法

public MyObject getMyObject(){
    GenericAsyncParams params = new GenericAsyncParams(customParams.....);
    Response response = new MyAsyncUtils.MyTask().execute(params).get();
    final MyObject myObject =
      om.readValue(response.body().string(), new TypeReference<MyObject>() {
      });

    return myObject;
}

我的AsyncTask位于我重用的Utility类中。

public static class MyAsynctask extends AsyncTask<GenericAsyncParams, Void, Response>{

    @Override
    protected Response doInBackground(GenericAsyncParams... genericAsyncParamses) {
        Response response = null;
        GenericAsyncParams genericAsyncParams = genericAsyncParamses[0];
        String url = genericAsyncParams.getUrl();
        String method = genericAsyncParams.getMethod();
        RequestProcessor requestProcessor = genericAsyncParams.getRequestProcessor();

        try {
            Request.Builder builder;
            if(method.equalsIgnoreCase("POST")){
                builder = new Request.Builder()
                        .post(genericAsyncParams.getRequestBody())
                        .url(url)
                        .headers(headers);
            } else  {
                builder = new Request.Builder()
                        .headers(headers)
                        .get()
                        .url(url);
            }
            final Request request = builder.build();
            response = requestProcessor.client().newCall(request).execute();
            return response;
        } catch (Exception e){
            Log.e(TAG, String.format("ERROR.. %s", ExceptionUtils.getMessage(e)));
        }

        return response;
    }
}

现在,我可能对此有一个解决方案,我可以在postExecute上使用回调,然后使用CountDownLatch等待回调响应,然后将其返回给方法调用者,但如果有更好的方法,请告诉我们!

谢谢!

0 个答案:

没有答案