I'm very new to android technologies. I've recently read that android only allows a REST web service invocation from inside an AsyncTask... Is this true?? I'm developing an app for the university, I have to finish it for tomorrow and I would realy like to know if I can just call the REST WS inside an ordinary function, despite the fact that it may not be a good practice...
Thank you in advice!!
José.
The main thing is that you may not call it on the UI-thread (otherwise you will get an exception). Besides this restriction, it does not matter from where you call it.
A benefit of using AsyncTasks is that they are a very easy way of using additional threads in Android, since it comes with many callbacks (which are run on the UI-thread)
Another alternative could be to use an ExecutorService.
Related
I am a Java developer with no Android experience, and I am trying to quickly put an app together. It seems that what I would normally do in Java isn't helping.
At this stage, ease of implementation is more important than efficiency or style - I will sort the latter out when there is more time and I will have educated myself properly when it comes to Android.
People can use the app to ask for support, or offer it to those who need it. Asking for support posts a request with the details to the server, and that's done.
Now I would like the app to post an asynchronous request to the server, to be notified of outstanding support requests once a minute. I guess it's the same principle of WhatsApp checking if there is any new message on the server.
I tried doing that in a separate thread with an infinite loop which sleeps for 60 seconds but for some reasons that stops the UI from working.
From what I now understand, I should use a service with a Looper, a Timer and a Handler. Is that correct?
Could anybody point me to a tutorial which explains exactly what to do, step by step? Or at least suggest keywords I should look for?
All I found so far are snippets of code which don't work together when I try to assemble it. Possibly because I am not searching for the right terms?
Thanks, Dan
You could try the following approach:
Create a service that runs in the background to check for newly added data in the server.
If you prefer to make it user-driven, you can let users refresh the list on the device to actually trigger the requests to the server.
Libraries like Retrofit can make your life easier when it comes to making http requests - always avoid the main UI thread when doing this.
Another library that you could use to decouple your application using Events is EventBus. Assuming you are running a background service to check for updates, you can use EventBus to update your User Interfaces when something new is retrieved from the server through a GET request.
I hope this gives you an idea on how to proceed with the solution. Good luck!
My question is kinda theorical, hope I can get a clear explanation on this.
I've been looking for a nice rest api consumer for android (or some clear info on how to develop a solid one) and I found the rest api design talk from google IO 2010.
"Developing Android REST Client Applications - Google"
It's been 4 since this talk and I think there might exitst new designs and techniques for this matter, or not ?
The scenario that I think that would work the best for me is this one:
So my first question is, does this architecture is still valid for a new app (Starting from the beginning) ?
I've found Retrofit, which seems a pretty nice and stable Api for the rest service, but I can't quite understand how it works, like if it is a good approach to call my api endpoints from activities (or frags) and the library handles the resume/pause (delivering results when activity is on hold, or not) or I must implement this myself.
Sorry for the long post and thanks for the patience !
You must implement how to handle that yourself, to answer your question.
Yes, that architecture is valid, but RetroFit only forms part of the "Rest Method" block. How would you implement it? That depend on what you want. You could use Retrofit (AKA the REST Method) inside the service, and that would be ok, however you can also skip using services and use it inside of an activity or fragment. However if you do the second option(activities/fragments) you can not think in handling the activity life cycle within retrofit(onStart, onPause, etc..) because since these are network calls, you must perform them on worker threads(AsyncTasks for instance).
So in conclusion, whatever option you decide, being Services or worker threads, you must think in using perhaps observers to control your activity/fragment, and remember that requesting network data is always done out of the ui thread. Implementations of how to handle the situation may be done by you depending on your needs and complexity of the application.
I'm a beginner in android development and I'm trying to implement an android udp client, which connects to a java server and sends/receives some packets from it.In this process it collects some data (like round-trip delay etc), which is used to measure the QoS of that particular network. I have tried implementing the connection and sending/receiving data using Java Threads, but the application crashes, and hangs if i try to use more than 2 threads. So I'm looking for alternatives. While going through this site as well as some other links I found that in android multiple threads can be implemented using AsyncTask, Handler etc. Also I found that the Service class also helps to run a background service in an app. Please suggest which approach among these would be the best to achieve my purpose.
Thanks in advance.
You can use AasyncTask to do this and as you mentioned service may be useful too, where u can let your application do whatever it wants in background , if user needs to use application by its interface then AsyncTask must be used to avoid Crashing
There is not one right answer that can be applied as a broad stroke to how to do Android multi-threading. There are a few different ways to approach it based on what your specific needs are.
Any long running, blocking call, in Android will result in the application crashing.
The most common solution is to use an AsyncTask though. For example, when I want to make a call out to a web API endpoint for some XML data within an Activity I would in this case use an AsyncTask and kick off the calls from within doInBackground.
This is not an appropriate solution though if the wait time is longer, or possibly an unknown wait time. Or in a situation where there will always be waiting such as a message queuing service. In this type of situation it may be best to write a separate app based on extending the Service class. Then you can send/receive notifications to/from the service from your primary application in a similar manner to how you would communicate with a web service.
I want to better understand how to structure an Android app where an activity fires off an API call (for example).
I'd currently implement it by putting the API call into an AsyncTask subclass, passing it a reference to the activity so it can update the UI in onPostExecute. But my gut-feel is that this is creating overly-coupled code.
I'm wondering whether instead I should put an API call like that into a service, and use a BroadcastReceiver to update the activity.
What say you, AsyncTask, or BroadcastReceiver?
I usually follow the Local Service pattern. I have a strong suspicion that this is how the official Twitter app works and that this is the pattern most of the Google apps use. This also solves the issue of your app going away (getting killed or going into the background) before the task finishes, or if the phone switches configuration during a background task.
BroadcastReceiver and service is an overhead here. A request to web-service should not go to long. Service is appropriate in case of downloading files or something similar.
AsyncTask way is the right one here. But I would suggest you showing a progress dialog to let user know that your application isn't freezed, but doing some useful work.
See the example here.
AsyncTask is just fine. Only thing you should worry about is referencing you Activity using WeakReference to avoid whole Activity be memory leaked. It isn't overly-coupled code imo if you using observer or events patterns.
I would go with a service only if the call is going to take long, so that the user can leave the app while it's completing.
I'd use the AsyncTask if the task is short enough that it almost wouldn't go ANR if done in UI thread.
(disclaimer: I consider myself a beginner, and I'm expecting comments from more experienced people)
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...