在android中使用volley调用web api时出现内存不足错误

时间:2016-04-12 05:45:06

标签: android android-volley

我制作了名为BaseActivity.java的通用类,并在其中定义了齐射功能。我还将BaseActivity类扩展到每个活动并使用方法来调用web api。 代码如下。

    public void callVolley(final Context cContext, String mMethodType, final String mMethodname, String URL,
                       final HashMap<String, String> mMap, int initialTimeoutMs, boolean shouldCache, int maxNumRetries,
                       Boolean isProgressDailogEnable, Boolean isCancelable, final Activity aActivity) {

    // TODO Auto-generated method stub
    mMap.put("deviceType", "1");
    SharedPreferences setting = getSharedPreferences(Constant.PREFRENCE_NAME, MODE_PRIVATE);
    mMap.put("loginUserId", setting.getString("userId", "") + "");
    mMap.put("deviceToken", "" + setting.getString("deviceToken", ""));
    mMap.put("deviceId", setting.getString("deviceId", "") + "");

    if (Constant.d) Log.i(mMethodname + "==>", mMap.toString() + "");
    if (!isOnline(cContext)) {
        showErrorDailog(aActivity, Constant.PleaseCheckInternetConnection, R.drawable.icon);
    } else {
        StringRequest jsObjRequest;
        int reqType = 0;
        String RequestURL = URL.trim();
        queue = Volley.newRequestQueue(cContext);

        if (isProgressDailogEnable) {
            customLoaderDialog = new CustomLoaderDialog(cContext);
            customLoaderDialog.show(isCancelable);

            customLoaderDialog.dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    //  finish();
                }
            });
        }
        if (mMethodType.trim().equalsIgnoreCase("GET"))
            reqType = com.android.volley.Request.Method.GET;
        else if (mMethodType.trim().equalsIgnoreCase("POST"))
            reqType = com.android.volley.Request.Method.POST;

        if (RequestURL.equals(""))
            RequestURL = Constant.WEBSERVICE_URL;
        else
            RequestURL = URL;

        if (Constant.d) Log.d("reqType", reqType + "");
        jsObjRequest = new StringRequest(reqType, RequestURL, new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (Constant.d) Log.d("response==>" + mMethodname, "" + response);
                if (customLoaderDialog != null) {
                    try {
                        customLoaderDialog.hide();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                if (response == null || response.length() == 0) {
                    IVolleyRespose iVolleyRespose = (IVolleyRespose) aActivity;
                    iVolleyRespose.onVolleyResponse(RESPONSE_ERROR, response, mMethodname);
                } else {

                    JSONObject json_str;
                    try {
                        json_str = new JSONObject(response);
                        int status = json_str.getInt("status");

                        if (status == 101) {

                            AlertDialog alertDialog = new AlertDialog.Builder(aActivity).create();
                            alertDialog.setTitle(Constant.Alert_Name);
                            alertDialog.setMessage(json_str.getString("message") + "");
                            alertDialog.setCancelable(false);
                            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                            SharedPreferences setting = getSharedPreferences(Constant.PREFRENCE_NAME, MODE_PRIVATE);
                                            setting.edit().clear().commit();
                                            ExitActivity.exitApplication(aActivity);
                                            finish();
                                            System.exit(0);
                                        }
                                    });
                            alertDialog.show();
                        } else {
                            IVolleyRespose iVolleyRespose = (IVolleyRespose) aActivity;
                            iVolleyRespose.onVolleyResponse(RESPONSE_OK, response, mMethodname);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                // TODO Auto-generated method stub
                IVolleyRespose iVolleyError = (IVolleyRespose) aActivity;
                iVolleyError.onVolleyError(RESPONSE_ERROR, "Error", mMethodname);

                if (customLoaderDialog != null) {
                    customLoaderDialog.hide();
                }

            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                String strRequest = "";
                try {
                    strRequest = getWebservicejsObjRequestforvolley(mMethodname, mMap);
                    if (Constant.d) Log.d("Request==>", strRequest + "");
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Map<String, String> params = new HashMap<>();
                params.put("json", strRequest);

                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("Content-Type", "application/x-www-form-urlencoded");
                return params;
            }
        };
        //if(Constant.d) Log.d("Request==>", jsObjRequest+"");
        jsObjRequest.setTag(mMethodname);
        jsObjRequest.setShouldCache(shouldCache);

        jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(initialTimeoutMs, maxNumRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(jsObjRequest);
    }
}

上面是我使用的代码,它提供了一些时间OutOfMemoryError除外 崩溃日志如下:

0   java.lang.OutOfMemoryError: thread creation failed
1   at java.lang.VMThread.create(Native Method)
2   at java.lang.Thread.start(Thread.java:1050)
3   at com.android.volley.RequestQueue.start(RequestQueue.java:142)
4   at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:67)
5   at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:79)
6   at com.truepal.truepalapp.activity.BaseActivity.callVolley(BaseActivity.java:211)
7   at com.truepal.truepalapp.activity.QuestionActivity.callforAnswerList(QuestionActivity.java:875)
8   at com.truepal.truepalapp.activity.QuestionActivity.onResume(QuestionActivity.java:487)
9   at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1157)
10  at android.app.Activity.performResume(Activity.java:4539)
11  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2446)
12  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2484)
13  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1998)
14  at android.app.ActivityThread.access$600(ActivityThread.java:127)
15  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1159)
16  at android.os.Handler.dispatchMessage(Handler.java:99)
17  at android.os.Looper.loop(Looper.java:137)
18  at android.app.ActivityThread.main(ActivityThread.java:4507)
19  at java.lang.reflect.Method.invokeNative(Native Method)
20  at java.lang.reflect.Method.invoke(Method.java:511)
21  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
22  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
23  at dalvik.system.NativeStart.main(Native Method)

问题是当我使用应用程序5到10分钟时,我无法找到为什么会出现这种错误。 如果任何人面对这种类型的错误,那么解决方案是值得赞赏的。

2 个答案:

答案 0 :(得分:1)

临时解决方案但不推荐。

在清单文件中添加此行

<application
     android:largeHeap="true"

OR

还要查看这些链接 Android Volley give me an outOfMemory exception

Strange out of memory issue while loading an image to a Bitmap object

答案 1 :(得分:0)

将bigheap属性添加到清单文件中的application标记,如下所示:

android:largeHeap="true"