Volley crashing app on service after long run

前端 未结 1 1863
广开言路
广开言路 2020-12-19 23:38

Am implementing a service to get updates from server as below:

public class Myupdates extends Service {

    private static final String TAG = \"AutoUpdates\         


        
相关标签:
1条回答
  • 2020-12-20 00:35

    This is occurring because you are creating the RequestQueue instance multiple times by passing the activity context. You should create the instance once using an Application class and then use it again and again whenever needed. Create an application class like this,

    public class AppController extends Application {
        private static AppController sInstance;
        private RequestQueue mRequestQueue;
    
        @Override
        public void onCreate() {
        super.onCreate();
    
        sInstance = this;
        }
    
        public static synchronized AppController getInstance() {
        return sInstance;
        }
    
        public RequestQueue getRequestQueue() {
    
                if (mRequestQueue == null) {
                    mRequestQueue = Volley.newRequestQueue(getApplicationContext());
                }
    
                return mRequestQueue;
            }
    
    }
    

    Then use it like this

    RequestQueue queue=AppController.getInstance().getRequestQueue();
    

    NOTE : By passing the context to request queue again and again , you are filling up your ram, which leads to an OutOfMemoryException when no more space can be allocated

    As mentioned in android's official docs here ,

    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).

    0 讨论(0)
提交回复
热议问题