简体   繁体   中英

Android Networking Class

I currently have an app that requires connection to a server in multiple activities. I am currently trying to create a class that handles the connection between multiple activities and provides getters to get the output streams, I have looked at a service class but I do not need to keep the connection when the app is not running.

I am not entirely sure what i need to do to get an object to be globally accessed from multiple activities without having to be instantiated the object in each activity.

You have 2 choices:

  1. Make a singleton class. (I bet there is a lot of example in Google.)

  2. Implement an "application" class. http://developer.android.com/reference/android/app/Application.html

The differences:

  1. For (1) it will instantiate the first time you access it. (But depending on design). For (2) it will instantiate together with the app process.

  2. For (1) it is more complex to handle the object life cycle. For (2) you can manage your objects life cycle easily by controlling the access to the object in application.

A Service is still the best idea. You just have to make it keep track of how many Applications are connected to it (in onBind/onStartCommand/onUnbind), and make it shutdown when it goes to zero.

What is a bit tricky is that Applications are not really closed in Android when they don't have focus: you would have to decide if an Application unbinds from the Service on onPause or onStop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM