1

I a am building an android application and at some point I need to build a new specific "Thread", let's call it A.

  • A will communicate with a distant server (download pictures and send some small data)
  • A will communicate with several activities of my application (send int/string)
  • A need to stay alive even if the application is closed
  • A will stay alive for a specific duration (around 10 minutes)

What should A be ? a Service ? an AsyncTasck ? I think it can't just be a thread because a thread is linked to a specific activity butI might be wrong.

Bonus question : what is the best way to communicate between A and my Activities ?

Thank you for your help.

Fabich
  • 2,768
  • 3
  • 30
  • 44

3 Answers3

2

Make a Bounded service. It will work for all the points.

Malwinder Singh
  • 6,644
  • 14
  • 65
  • 103
1

In AsyncTask documentation you can see:

"AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask."

So is no for this case

manolodewiner
  • 504
  • 3
  • 26
1

A service is the best way to wrap your thread and keep it active after the UI is closed. You service would then communicate with the activity in two ways: either by broadcasting intents or by implementing callbacks. I personally prefer callbacks for a general case.

A main problem based on my experience is keeping the service alive and keeping Android from killing it to save memory. Just because I know this issue might come up I will say that you either have to add a START_STICKY flag to the service or create a foreground service instead of background to keep the service running.

Community
  • 1
  • 1
SoroushA
  • 2,043
  • 1
  • 13
  • 29
  • Check out [my other answer](http://stackoverflow.com/questions/35434147/how-to-get-progressbar-to-show-while-onclicklistener-is-running/35435446#35435446) on how to implement callbacks. – SoroushA Feb 26 '16 at 17:49