Reputation: 7233
I am in quite a dilemma about how to solve my problem regarding network access.
All of my REST based requests are routed through my own HttpRequestExecutor class that will execute each request asynchronously and results will be sent back via handler passed to it per request.
Some of these requests are originating from UI and needs to end there as well for example Sign in request. In most cases user has to wait till it finishes. I would like to write some high level and specialized class for each of such use case as it may do some business level processing before and/or after request is executed. The result will be handed down to the originating Activity.
This could be done either using a Service or simple Java class both using thread. I am not sure which way to go.
A simple Java class would be straight forward and simple solution but I feel Service may be the correct way to do it. What I am really concerned about using Service is the boiler plate code that goes into using it i.e. binder or messaging to communicate with Activity.
For this problem which is the correct way to solve? Also does Service provide some extra advantages in this case?
Upvotes: 0
Views: 125
Reputation: 29285
In my opinion, using Java multi-threading mechanisms may be better than Android Services for lightweight and short tasks.
As far as I know, Google recommended to use Services for long and continuous tasks. (e.g. file watchdogs, network-based updating agents)
I myself usually use the following pattern for multi-threading tasks.
// Bind a handler to the main thread.
Handler handler = new Handler();
new Thread(new Runnable(){
@Override
public void run(){
// Do the task
// Inform main thread, e.g. calling callbacks
handler.post(new Runnable(){
@Override
public void run(){
// Inform task requester here
}
});
}
}).start();
Also some notes:
Upvotes: 2