Volley的网络请求有内存溢出现象

来源:互联网 发布:知乎 装修 编辑:程序博客网 时间:2024/05/22 08:11
官网上有写,然后创建RequestQueue 的时候用Application的context。If your application makes constant use of the network, it's probably most efficient to set up a single instance of RequestQueue that will last the lifetime of your app. You can achieve this in various ways. The recommended approach is to implement a singleton class that encapsulates RequestQueue and other Volley functionality. Another approach is to subclass Application and set up the RequestQueue in Application.onCreate(). But this approach is discouraged; a static singleton can provide the same functionality in a more modular way.

A key concept is that the RequestQueue must be instantiated with the Application context, not an Activity context. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).


import android.content.Context;import com.android.volley.RequestQueue;import com.android.volley.toolbox.ImageLoader;import com.android.volley.toolbox.Volley;public class ByklVolley {private static RequestQueue mRequestQueue;private static ByklVolley mInstance;private Context context;private ByklVolley(Context context) {this.context = context;mRequestQueue = getRequestQueue();}public static synchronized ByklVolley getInstance(Context context) {if (mInstance == null) {mInstance = new ByklVolley(context);}return mInstance;}// public static void init(Context context) {// if (mRequestQueue == null) {// /**// * Volley的网络请求有内存溢出现象 整个项目中用一个RequestQueue// * ,可以弄成单例模式。官网上有写,然后创建RequestQueue 的时候用Application的context。If your// * application makes constant use of the network, it's probably most// * efficient to set up a single instance of RequestQueue that will// * last the lifetime of your app. You can achieve this in various// * ways. The recommended approach is to implement a singleton class// * that encapsulates RequestQueue and other Volley functionality.// * Another approach is to subclass Application and set up the// * RequestQueue in Application.onCreate(). But this approach is// * discouraged; a static singleton can provide the same// * functionality in a more modular way.// *// * A key concept is that the RequestQueue must be instantiated with// * the Application context, not an Activity context. This ensures// * that the RequestQueue will last for the lifetime of your app,// * instead of being recreated every time the activity is recreated// * (for example, when the user rotates the device).// */// mRequestQueue = Volley.newRequestQueue(context// .getApplicationContext());// }// }public RequestQueue getRequestQueue() {if (mRequestQueue == null) {// getApplicationContext() is key, it keeps you from leaking the// Activity or BroadcastReceiver if someone passes one in.mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());}return mRequestQueue;}}


0 0
原创粉丝点击