maxsap
maxsap

Reputation: 3001

Android background work scenario

This is the scenario:

  1. User has a main activity used for UI.
  2. Program needs to communicate with peers and keep connection and wait for messages
  3. When a message comes it is shown in the main activity.

So the question is should I use a service for the communication and what type of service?

And also should I use AsyncTask in the service in order to keep my UI responcive and why?

Upvotes: 0

Views: 248

Answers (1)

Trevor Johns
Trevor Johns

Reputation: 15762

The important thing here is that any CPU intensive work or blocking I/O (including waiting for incoming network connections) occurs in a thread separate from your main UI thread.

If you just need network communication to stay running while your activity is alive, then use a second thread within your activity. If you need to maintain network communication even after your activity has been killed, you'll need to use a service.

Keep in mind that default behavior is for a service to share the same process and thread as anything else in the same application (including the activity that provides your UI). For this reason, even if you use a service, you'll still need to spawn a new thread to get the desired effect.

AsyncTask is used to perform a task in a separate thread that will eventually terminate and return a result. If this sounds like your application, then feel free to use it. But if you're keeping a port open across several requests (meaning you don't have a single return value), using this class would just be a burden.

Upvotes: 5

Related Questions