Gabe
Gabe

Reputation: 6347

Best way to share httpClient instance between activities?

In an Android app what's the best way to share an http client instance?

I know I should probably just share the session data and create an http client instance for each activity but excluding that approach how can I achieve my objective without globally sharing an instance created in one of the activities (as described here)?

How can I share objects using getContext() in each activity?

Thanks

Upvotes: 1

Views: 192

Answers (1)

VikasGoyal
VikasGoyal

Reputation: 3376

You can create a singleton class with initializer method and after that all Activities can get http client by

ApiManager.getInstance().getClient();



   public static class ApiManager {
        private static ApiManager sInstance;
        private HttppClient mClient;
        private ApiManager(Context pContext){
            mClient = new HttpClient(pContext);
        }

        public static void initializer(Context pContext){
            if(sInstance == null){
                synchronized (ApiManager.class){
                    sInstance = new ApiManager(pContext);
                }
            }
        }

        public static ApiManager getInstance(){
            if(sInstance == null){
                throw new IllegalStateException("Get Instance can't be called before initializer");
            }
            return sInstance;
        }

        public HttppClient getClient() {
            return mClient;
        }
    }

Upvotes: 1

Related Questions