What is the benefit of implementing a DownloadCallback interface? - android

I want to control a RaspberryPi via android app and plan to do this by defining an api on the raspberry and accessing it via the app.
On the Android Developer Guides I found the recommendation to implement a DownloadCallback interface.
My question is, why would I want to do that, if I can alternatively simply use an AsyncTask and make an HttpRequest?

Using an AsyncTask for network calls is considered a bad idea. First, AsyncTask does not handle orientation correctly so you need to have more code put in so that the asynctask properly terminates (making sure it doesn't make calls to the finishing activity, making sure it doesn't hold any strong references to the finishing activity). You also cannot halt AsyncTask so lets say in your main UI thread, you want to stop the AsyncTask from performing the network call but you already started it. Well you are out of luck and you need to wait until it terminates on its own. (As mentioned in the comment below, this is not true. You can halt interrupt the thread of the AsyncTask to "cancel") Also, you cannot make parallel network requests in an AsyncTask easily.
Also this is more of a preference but using AsyncTask is more boilerplate code than I would like. Retrofit is my most preferred way of network operations.
DownloadCallback isn't about replacing the AsyncTask. It is just a way to communicate between your fragment (the one who started the network call) and the activity (the one who wants to know what the progress of the network call is) about the progress of your network operations. You can see here https://developer.android.com/training/basics/network-ops/connecting that they are still using AsyncTask for network operations but they are using the DownloadCallback to notify the activity about the progress of your operation.

Related

What is the difference between thread and service in android , when downloading an image

What is the difference between thread and service in android,when downloading an image
There are lots of difference between Normal thread and a Service
Service: Due to android component it runs on UI thread but without any view shown to user. It runs in background with the same kind of property that an activity have, like you cannot run network operations (downloading image, calling web service) in service for that you have to use Thread which will run on worker thread other than UI thread.
Thread: Its an independent path of execution which can consist network operation, complex coding, huge amount of data transfer and accept. Thread is not related to android but in android it is used to perform different task. You can download an image on Thread but to show it on any UI part you have to update downloaded image on UI thread using runOnUIThread method
Please let me know if this explanation clears your doubt. If not let me know which part you did not understand and what exactly is your question.
With rare exceptions, you should never explicitly create a Thread. Threads are expensive and prone to programmer error. Use AsyncTask because it handles the complexity of thread safety and provides the optimization of thread pooling. Or better yet, if network activity is your reason for doing work outside the main thread, use one of the many network libraries that manages all of these concerns for you. Which approach is fastest is not something that can be answered generally, and should never even be a concern until you've tried the simple and clear solution and demonstrated that its performance is inadequate.
Regardless of how you make your network activity asynchronous, any network activity that is not started and completed (or cancelled) within the lifetime of a single Activity instance needs to be hosted in something else. If it only needs to survive across configuration changes, host it in a retained Fragment. If it needs to survive between different activities, host it in a Service. When choosing between these options, remember that your Activity may be destroyed any time it goes into the background or backstack.

Using excessive amount of network calls in android

I am developing an android application that needs to communicate a lot with a remote server. For this task I wrote a class that handles all the network communication.
Do I need to make for every single method as an Asynctask? What about methods that I am dependent on for the rest of the code execution? (thus needs to be done synchronously - like waiting for an answer on registration?)
I am asking this because I already had a small app before to communicate with a remote server and I didn't use any Asynctasks, this one crashes on every method being called though.
Edit -
Meanwhile - before making a class of my own I found a great tutorial related to a google libraray that already handle that the libraray name is Volley the tutorial I looked on is this one
Yes, every network call has to asynchronous. You don't need to make every single method in you class async, but i would refactor the code in a way that only one peace of code actually does the calls and this peace has to be async. If you have following code that depends on the response from the server, then use a callback.
In pseudo code that would look something like this:
void makeNetworkCall(command, listener){
async(){
result = command.execute();
listener.onCommandSuccess(result);
}
}
Do I need to make for every single method as an Asynctask?
Yes. Android requires networking code to be executed asynchronously, so the user interface never gets blocked.
What about methods that I am dependent on for the rest of the code execution?
You can wait for an Asynchtask to finish execution. Refer to this question.

Which should I use Handler, AsyncTask or Thread?

This may be a common question but I couldn't find my exact scenario. I understand that its down to developer choice in a lot of ways but I don't know enough to choose best.
I have my initial app splash screen which will just display a logo whilst checking the user is logged in. If their login details are already stored in a sharedPreference then I want to check those details against my online database of details for verification. Once this is all checked I'll either pass the user through to the main app screen or a registration screen.
So when doing this check of user details, and then verifying them. Should I do this in a separate or use a handler? I don't think AsyncTask is needed as I'm not wanting to pass any progress details back to the UI?
TIA
I suggest using AsyncTask.
First of all, because AsyncTask is a complete threading framework (that uses Thread and Handlers behind the scenes) that allows for a nicer control of single thread operations. Including cancel() for example, in case the user decices to leave the application before the splash screen is done.
I don't think AsyncTask is needed as I'm not wanting to pass any
progress details back to the UI?
actually, yes you do, even to start the new activity (either Login or AlreadyLoggedIn) you have to call startActivity() from the UI thread
You should probably do this in a separate thread because it is network activity. IntentService is a good option. I think your main concern is that whatever method you choose needs to work even if the user rotates the screen and the activity is destroyed and recreated.
Maybe use a Fragment for the splash screen with setRetainInstance(true), so it will get reattached to the activity after configuration change. Then you can either pass the service a Handler (or a Messenger to be more accurate), or have the service send out a broadcast intent when it finishes working.
When to use an Async Task?
AsyncTask helps in offloading memory intensive/blocking call to a background thread while, your UI operations can still carry on in the UI thread.
If any operation blocks the UI thread for more than 4-5secs, you might also get an ANR(Android Not Responding) dialog. AsyncTask come handy when you want to update the UI after doing the process (onPostExecute) and also before starting it (onPreExecute).
Using a Thread
Whatever you do in doInBackground using an AsyncTask can also be achieved using a Thread. But incase you need to do any UI operation you will need to use a Handler or runOnUiThread to accomplish your task. Refer to Painless Threading in android in case you wish to use threads.
Also what Budius said is true.
In your case you can use an AsyncTask to check for user creds in sharedPref and then appropriately authenticate with your middleware and finally in onPostExecute navigate to a new activity.
In the meanwhile you can show a progress bar to the user signifying the on going auth process.
To add on to that. I had a very similar situation where I had to verfiy a users login (which was stored in the phone) in the background from a "home screen". I used the IntentService ResultReceiver pattern. At first it took a bit for me to get up-to-speed on it, but once its implemented its very simple to manage.
Basically, you start the activity that is your intent service, passing it any parameters that are needed (username, password, etc...). In my case it was a separate class that used REST to verify the user. Once the REST class has done its work, the ResultReceiver method onReceiveResult, returns back the data to the UI activity from the REST activity.

Android: How to retain AsyncTask instance when Activity gets destroyed?

In my app, I have a class that inherits from AsyncTask and which downloads huge amounts of data from the server. I am using a ProgressBar to indicate the progress of the download.
When the user hits the HOME key, the Activity to which this AsyncTask is attached, is destroyed but, download goes on.
How can I reattach this AsyncTask and show the progress to user? I tried using onRetainNonConfigurationInstance but Android 4.0 doesn't seem to invoke this method. My application does not use Fragments API.
What I did in this situation was as follows:
I created an IntentService to handle communication with the server. This has some of the benefits of AsyncTask (e.g., worker thread), but also some benefits of a Service (available any time, from anywhere).
The IntentService can be invoked either by a user action in my main Activity, or via an inexact repeating alarm.
The data is stored in an SQLite database, fronted by a ContentProvider. I dodge the issue of when/how to create my database and tables by using an SQLiteOpenHelper and calling getWritableDatabase() from the safety of my background IntentService.
When the task is done, it posts a Notification if my main Activity is not active.
One nice thing about this arrangement is, no progress bar is necessary. In fact, no UI is necessary. The user keeps using the application while the service is running, and the UI automatically refreshes itself as new data comes into the ContentProvider. Another nice aspect of it is it's less code to write than an AsyncTask. It automatically picks up where it last left off by reading the server-side metadata of the last entry from the database and asking the user to start after that point. Since it's not tied to any Activity instance, it doesn't care about onPostExecute() or configuration changes or any of that. And you don't have to worry about single-shot execution like AsyncTask.
If there is a need to download huge amount of data in background I would use service rather then AsyncTask. There is a good presentation from Google IO about using services.
Quote from AsyncTask documentation:
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 pacakge such as Executor, ThreadPoolExecutor and
FutureTask.
and
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
As I understand, you cannot proceed with your last AsyncTask.
Still, you can load your data partially and save amount of data read and then start new AsyncTask which will start from last saved point. From my point of view this is not the best idea to pause loading when activity goes to background and it is better to use service to finish what was started.
Have you considered using a service to attach your AsyncTask to? Seeing as a permanently running service would probably be the best solution for your task at hand. All you'd have to do then will be to check if the service is running and if your download is running (easily done using static boolean variables) then you just create a progress dialog using some state saving variable in your service (maybe a percentage of the total file size downloaded etc.) in the onCreate method of your main activity.

Android asynchronous service calls strategy

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...

Categories

Resources