Hey I am trying to make multiple http requests and wondering the best way to perform this in android. Currently I am using an IntentService with threads, however this doesnt work too well because onhandleintent returns before the threading is complete. Should I Switch to A regular service and start my own threads in there or would asyncTask be more approiate?
Thanks
Any time you deal with threads you're going to have to deal with synchronization. For example, when onHandleIntent() is called you may need to synchronize with your HTTP request thread(s) and wait for it to complete.
If you know ahead of time you will be doing this a lot it may be worth looking at something like ThreadPoolExecutor to save a bit on the pains of creating and tearing down threads. Again you will still need to synchronize your threads if you want to wait for their termination before moving on. Android has many ways of doing this including abstractions that make it fairly trivial to implement.
If you're already starting new threads anyway (whether directly or indirectly), then yes you should use a Service instead of an IntentService. The whole point of an IntentService is for it to handle threading for you.
Related
In the current app that I am developing with a co-worker, we're using IntentServices with Volley calls inside to process RESTful API network requests. It's just simple JSON string data, and some small images.
My question to those experienced in processing network requests is this: is there something more appropriate, or cleaner to implement out there?
From what I understand, the advantage of using an IntentService is that it runs in the background off the main thread, and is typically one of the last things killed by the Android OS. The downside being that IntentServices are run sequentially.
I've been reading a lot about RxJava, and Retrofit, and feel like our needs could be better served with that combination. Retrofit may be enough on its own, but I'd really appreciate some third-party insight.
My general rule of thumb is:
If the network I/O should be under a second, and you don't mind if it does not run to completion, any asynchronous option should be fine.
If the network I/O should be more than a second, or you really want to increase the odds that it will run to completion, use a Service. Whether you use IntentService or some other Service implementation is up to you, but you want to have a Service as an indicator to the OS that you're doing work, so it doesn't terminate your process quite so quickly once your app moves to the background. Remember that "moves to the background" is not always something initiated directly by the user, as incoming phone calls and such also move you to the background.
If the network I/O will take more than 15 seconds, not only do you need to use a Service, but you need to think about a WakeLock (via my WakefulIntentService, or WakefulBroadcastReceiver, or your own carefully-managed WakeLock) and possibly a WifiLock. 15 seconds is the minimum auto-screen-off period in Settings, which is where that figure comes from.
With all that in mind:
The downside being that IntentServices are run sequentially.
I am translating this as "an IntentService has a single thread for processing requests". This is true. In cases where you need a Service and you need parallel processing, create your own Service. Just be sure to call stopSelf() when you have no outstanding work.
I've been reading a lot about RxJava, and Retrofit, and feel like our needs could be better served with that combination
This has nothing to do with whether or not you use a Service. Just don't try doing asynchronous stuff (e.g., a Retrofit call using a Callback) from an IntentService, as you defeat the purpose of the IntentService (indicating to the OS that you're doing work). So, from an IntentService, you would use Retrofit's synchronous API, sans a Callback.
Using IntentServices just to perform a simple network request, IMO, is to much. You should use an AsyncTask if you don't want to use a library or if you prefer to go for Retrofit, Volley... (I would recommend Retrofit).
IMO, Services, or in this case IntentService are designed to execute long background tasks.
The real question is: do you load data to populate an Activity in the foreground or for doing background work, even when no UI is visible?
For background work, a Service is the way to go. You don't even need an IntentService if you rely on the threading management of Volley.
For foreground work, consider using Loaders, or Volley or Rxjava calls directly inside your Activity/Fragment.
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
.
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.
I am aware this is most likely a very stupid question, but I just cannot completely understand the point of Handlers. I know the idea is that Handlers execute on the main thread, and they seem to be most commonly used along with worker threads, but why cannot the worker thread just invoke methods on the calling Activity instead of said Activity creating the thread along with a Handler to receive messages?
Again, I apologise for the ignorance of my question, but all I've found online is tutorials on how to use Handlers and my Pro Android 3 book does not clear up my question (or I'm too stupid to understand it properly!)
Or, for that matter, why use them over AsyncTasks, which can modify the UI without problem?
Thank you.
When using handler (or message) each task becomes "serialized".
This has the advantage that there is NO concurrency and therefore no need to lock.
It is much easier to make a message driven system stable than an multi-threaded one.
By the way AsyncTask uses Handlers, too
Using handlers directly give you more flexibility.
For example you could schedule a message to be send in the future.
Or you could abort an scheduled message.
Handlers are a very powerful tool.
I'm building this client for a web service.
Pretty much everything makes requests to a server and now what I do is, I open a new thread and put all my requests in the same thread. That means I'm making all my requests in a serial way inside the thread and that turns into a lot of waiting for the user. Aiming to make the application faster, I want to make every server request in an asynchronous way.
I have a Networking class that handles all the HTTP requests I need and I'm thinking of making it so that every request starts its own thread.
I'm thinking of using ASyncTask for this but I noticed that with ASyncTask I'd need a class for each of my http requests (a class for GET, POST, PUT, etc). Is that the best way of doing it? is there a more efficient/clean way of doing this? What do you guys suggest.
Seems like a design decision that will depend on exactly what you are up to. There are various ways in Android to execute tasks depending on whether the user is waiting for some data or is being notified later on once the background task completes.
I would suggest you to look at this post that compares various task mechanisms in Android. Apart from this also go through the java.util.concurrent package.
I'm sorry this is not a concrete answer, but take it from me - it mostly depends on how are you trying to serve the user. So one can only suggest ideas. Hope this helps.
Here's scenario:
Client makes remote call to the service (returns void) and provides
a callback object
Service executes some long running logic on the background thread
and then uses callback object to trigger ether success or failure
which (since these manipulate visual elements) execute in
Activity#runOnUiThread block
The scenario runs fine. The question is - can I use AsyncTask to make
code less verbose (how?) and would be there any advantages in doing it
that way?
Or should I just get away from client callbacks alltogether and
execute remote service calls retrofitted to return some value within
AsyncTask#doInBackground?
It is difficult to say whether AsyncTask will make things less verbose, since we don't know the verbosity of your current implementation.
For me, AsyncTask means I don't have to worry about cleaning up threads myself (e.g., post some sort of kill job to a LinkedBlockingQueue my background thread is waiting on). It also eliminates the custom Job classes I used to create for using with LinkedBlockingQueues. And, it simplifies a bit doing final work back on the UI thread.
In your case, with a remote service, the UI thread issue is less critical, since the activity needs to handle that itself.
I don't see what the difference is between your #2 and your last paragraph. In both cases, your service will call the callback object, which will use something like runOnUiThread() to arrange for the work to be done on the UI thread.
AFAIK, the only two ways to have a service doing any sort of asynchronous work let the client know that work is done is by a broadcast Intent or a callback object. Broadcast Intents are convenient but public (i.e., other code can watch for them).
I suspect I probably have not helped much here, but I just don't know enough of your scenario to provide greater detail.
I'm having quite the same question : i'm developping a map activity, with a 'lazy-loading' functionnality (xml from Network, parsing it, then updating my map with the 'items' created from that parsing...)
i wondered what would be 'the best' way to implement it...
async service launched from a thread, an update notification via Intent?
just a thread (no service, since i don't need to expose it to other applications) w/ callback
asyncTask with callback
i'm comparingthese in terms of speed, using the Android SDK performance analysis Tool traceview
I guess a more precise answer might be found from Android contributors on the Android-developper-group...