0

I have the following task:

I have to do a Wi-Fi scan and then send some RSSs to the a server to obtain a location from the server. After that I should display the location on a map.

I have one activity in my application. What is the best way to implement it? I haven't implemented a thread nor AsyncTask in android before. So I don't know a lot about it. I have read about threads and AsyncTask on android developer website. But I still can't understand everything.

I would appreciate it if anyone can tell me when its the best to use threads, and how AsynTask is different from threads and when to use AsyncTask instead of threads.

EDIT: the task that I have to implement should run only when the user click on actioBar item

.

Alaa
  • 539
  • 3
  • 8
  • 29

1 Answers1

2

If you can't understand the read documentation, I'd suggest starting with an AsyncTask, as it already implements a Thread when doInBackground() is fired and it already implements some mechanisms that you would probably have to implement by hand when using Threads (concurrency, Thread start/stop processes, sending information to UI thread, ...).

However, you don't specify what exactly want to do. If you plan to do a long-running process, instead of Threads or AsyncTasks, it's recommended using Service that would start a Thread as implementation, as contrary to popular beliefs, AsyncTasks are meant for short-lasting tasks.

In any case, if you're starting with this, I'd recommend using AsyncTask first, and when understood what it's doing and how, decide by yourself what's the best way to implement what you're planning to do: if running a Service with a Thread inside, a Thread itself or an AsyncTask.

nKn
  • 13,691
  • 9
  • 45
  • 62
  • the task that I mentioned is supposed to run for long time. I mean it should continuously detect the location and show it on the map. But as a start you recommend me to use AsyncTask in order to understand it right? – Alaa Apr 07 '14 at 14:11
  • 1
    Correct. Probably the most smooth introduction to `Thread`s is an `AsyncTask` because it already has a "built-in" `Thread` and this way you can run it and see what happens, but as you comment it's a long-run task, at the end you should definitely migrate it to a `Service` with a `Thread` inside running it. – nKn Apr 07 '14 at 14:48
  • I have changed the design so that the task is done only when the user click on item in actionBar so AsyncTask would be enough? – Alaa Apr 07 '14 at 16:43
  • 1
    The same answer applies here, if your goal is making an long-lasting task, set it to a `Service`. How it starts is not relevant here, just *how long* does it take to run is. If it will be a short task, an `AsyncTask` is enough, but if it's undetermined or a long task, switch it to a `Service`. – nKn Apr 07 '14 at 16:46