簡體   English   中英

Android,Volley Request,響應阻塞主線程

[英]Android, Volley Request, the response is blocking main thread

使用 Volley 處理大響應時發生了一些不好的事情:

String url = AppHelper.DOMAIN + "/service/pages/profile_update.json";

this.infoTextView.setText(getString(R.string.profile_info_updating));

final StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject json = new JSONObject(response);

                    if (json.getBoolean("success")) {
                        // manage JSON object here
                    } else {
                        Toast.makeText(ProfileActivity.this,
                                getString(R.string.connection_problem_server),
                                Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    ProfileActivity.this.infoTextView.setText(
                            getString(R.string.profile_info_updating_error));

                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        ProfileActivity.this.infoTextView.setText(
                getString(R.string.profile_info_updating_error));

        if (error.networkResponse != null && error.networkResponse.statusCode == 401) {
            Toast.makeText(ProfileActivity.this,
                    getString(R.string.connection_problem_permission),
                    Toast.LENGTH_LONG).show();
        }

        new android.os.Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ProfileActivity.this.swipeRefreshLayout != null) {
                    ProfileActivity.this.swipeRefreshLayout.setRefreshing(false);
                }
            }
        }, 1000);

        error.printStackTrace();
    }
}) {
    @Override
    protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<>();
        params.put("auth_token", ProfileActivity.this.defaultUser.getAuthenticationToken());
        return params;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new HashMap<>();
        params.putAll(super.getHeaders());
        params.put("Accept-Encoding", "gzip,deflate");
        return params;
    }

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        StringBuilder output = new StringBuilder();
        try {
            GZIPInputStream gStream = new GZIPInputStream(new ByteArrayInputStream(response.data));
            InputStreamReader reader = new InputStreamReader(gStream);
            BufferedReader in = new BufferedReader(reader, 16384);

            String read;

            while ((read = in.readLine()) != null) {
                output.append(read).append("\n");
            }
            reader.close();
            in.close();
            gStream.close();
        } catch (IOException error) {
            error.printStackTrace();
            return Response.error(new ParseError());
        }

        return Response.success(output.toString(), HttpHeaderParser.parseCacheHeaders(response));
    }
};

stringRequest.setRetryPolicy(new RetryPolicy() {
    @Override
    public int getCurrentTimeout() {
        // 40 seconds
        return 40000;
    }

    @Override
    public int getCurrentRetryCount() {
        return DefaultRetryPolicy.DEFAULT_MAX_RETRIES;
    }

    @Override
    public void retry(VolleyError error) throws VolleyError {
        throw error;
    }
});

Volley.newRequestQueue(this).add(stringRequest);

此代碼阻塞主線程,凍結應用程序。

此外,我設置了一些標頭值以允許 gzip 響應和處理數據的代碼。 但這不是導致不良行為的部分。 應用程序僅在onResponse(String response)啟動時凍結。

我該怎么做才能避免這種情況?

onResponse 和 onErrorResponse 在 UI 線程上調用,因此在這些方法中完成的任何繁重操作都會使您的應用程序響應速度變慢。 我猜您正在嘗試解析 onResponse() 中的響應,這是不正確的。

您必須轉到 parseNetworkResponse 的解析邏輯,因為這是在后台線程中調用的方法。 有關更多詳細信息,請參閱以下鏈接:

https://developer.android.com/training/volley/request-custom.html

如果它對某人有幫助,請嘗試在 onResponse 內的方法中創建一個新線程,在該線程內執行您的解析數據。 我希望答案對你有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM