Call AsyncTask methods from another class/service (callbacks?) - android

I was wondering if it's possible to call specific methods defined within the AsynTask class from another class and/or service ?
In my specific case I have a Service playing some sounds, but the sound is selected from a List with available sounds...
When a sounds is selected it is downloaded from my home server, this takes some time (not much, let's say around the 3-4 seconds, the sounds/effects aren't big in size)...
So my problem at the moment is that I have a service to play those sounds, and when I select one I wanted to show a progressdialog... The way (if I understood correctly) is to use an AsyncTask, but the only thing the AsyncTask will do is telling my Service to play a specific sound from my server... So there is no "callback" from the service to the Asynctask...
How can I achieve that ?
How can I call a running AsyncTask, which sits in another class, and tell him all work is done and thus he can stop showing the ProgressDialog ?
Or am I over-engineering it and there are other ways ?
Thanks in advance...

I would use one asyncTask for every download. The download work is done in the doInBackground method. You can override the onPostExecute method to do all the work that should be done after the sound is downloaded. In your case I would think that would be hiding the progressdialog and telling the playing service that new music is available.
For more info on the AsyncTask have a look at the android documentation.

Actually, what I think you want is the opposite. The AsyncTask should be used to perform the long running process, not to display the progress dialog. In fact, you should not use the task's background process to access any part of the UI. So what you would do is display a dialog, start your task, then have the task dismiss the dialog in its onPostExecute method, which can manipulate UI components.

Related

How to decide whether to use ASyncTask or not in android?

I have a simple Android UI. When user clicks Button, it takes the user's location and then it goes to 4-5 websites and gets all the events in that hour. Then, according to the user's location, it compares the closest ones, and according to a radius given, it shows the event names in a new screen.
After clicking Button, it will go into another screen and will write something like searching for location or progress dialog, or location identified. After that, it'll show the events to the user. So, should I create 3 activities and 3 screens?
According to this link
how to use method in AsyncTask in android?
He says don't prefer AsyncTask for long network jobs.
I can't use location methods inside AsyncTask. Before executing I should send location as parameter. But again, computeDistance method needed. At post execute method, I can post events to new UI.
But when the user clicks these events, from onClick I can do jobs but I can't find or retrieve info of these events.
I decided to use AsyncTask after commenting somewhere here and someone answered me to use but I can't find that post.
And now i am unsure about to use or not.
I need webconnections, so I don't want to make them in main. So it is good to use AsyncTask for that but is it necessary?
This is what I would recommend:
Use AsyncTask. It will run a background thread and give you a way to display progress in the UI thread as each website is checked. This isn't a "long network job" compared to, say, streaming a video. IMHO, using a Service for something like your operation is just too heavyweight. So start out with an AsyncTask.
Once you have that, however, you will discover your next problem, which is that your web operation might take long enough that if you rotate the device, the Activity will be torn down and recreated in the new orientation. Then when your AsyncTask completes, the Activity it was supposed to call back to is no longer there. Oops, now your user doesn't get their results.
The best solution I have found for that is to use a special fragment to "host" the AsyncTask. This fragment will not create a view and use setRetainInstance(true) to keep the fragment alive during Activity re-creation.
You can read about this novel technique here: Handling Configuration Changes with Fragments
AsyncTask is an abstract class provided by Android which helps us to use the UI thread properly. This class allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.
Android implements single thread model and whenever an android application is launched, a thread is created. Assuming we are doing network operation on a button click in our application. On button click a request would be made to the server and response will be awaited. Due to single thread model of android, till the time response is awaited our screen is non-responsive. So we should avoid performing long running operations on the UI thread. This includes file and network access.

Does AsyncTask really do things in background?

I used AsyncTask to get html files from server. But when an activity starts, screen becomes white few seconds and displays data when fully downloaded.
I wanted it to display activity's basic layout first(e.g. actionbar) and downloaded data later. So I used Thread and the problem solved.(basic layout is first shown and data later)
I've been knowing AsyncTask do things asynchronously but in my case it didn't.(In doInBackground, I only did network connection)
Does AsyncTask really do things in background?
Does AsyncTask really do things background?
Yes.
Note, though, that AsyncTask is serialized by default, meaning that if you fork multiple AsyncTask instances, they will share a single thread, and the second and subsequent tasks will be queued up waiting until the first task completes. You can avoid this via using executeOnExecutor(), instead of execute(), to run the tasks.
There are other ways of misusing AsyncTask (e.g., calling get()) as well.

Android loading string array into activity using background thread

I have an activity where the user enters a value in an EditText and I search a string array that I have defined in a xml file for a match. Each time the user changes the text I look for a match. When I start this activity I load the string array resource.
Should the loading of the array and the match finding occur in a background thread?
From what I understand I can use an AsyncTask which I am familiar with or a IntentService which I have no experience with. Would IntentService be overkill? What is ideal for this operation?
In some cases it is possible to accomplish the same task with either an AsyncTask or a Service however usually one is better suited to a task than the other.
AsyncTasks are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed.
Services are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask that will run once, return the data, and be done.
If you need to be continually doing something in the background, though, a Service is your best bet. Examples of this include playing music, continually checking for new data, etc.
For the most part, Services are for when you want to run code even when your application's Activity isn't open. AsyncTasks are designed to make executing code off of the UI thread incredibly simple.
You should use AutoCompleteTextView and ContentProvider to do your implementation. Save your string array in database and access them by Cursor to popup and show in AutoCompleteTextView. There is an example available in the official document.

I want to play an Audio. Do I use Thread, AsyncTask or Service?

I want to play an audio file in my Activity.
I have three button for controlling the media: play/pause/stop. Additionally, I have a seekbar for the media which I can use to forward/backward the track.
I'm trying to update the seekbar progress every 1 sec. Then, I thought about Threads. Is it the right direction or I need to consider using Services or AsyncTasks ?
Does the MediaPlayer come with a seek bar? This will help me a lot.
Thanks,
I would set up a Service for controlling the media player, and AsyncTask for the application display.
Have your application send messages to the service to stop, start (using onClick of buttons), and get current position information when it needs to update screen information. This will separate the playing from the controlling.
Your application can use a simple AsyncTask to pause (SystemClock.sleep(1000)) in its background thread, and update any sliders etc in the update progress thread which runs on the UI. There's no need to write any Thread specific code if you separate the responsibilities in this way.
If you want to update every second, I would recommend TimerTask.
I think you should use asyntask : you play media in different thread and update to UI Thread.

Cancelling file download with httpclient and asynctask

In my app I need to download files from url locations. I want to display progress of the download in a dialogbox (or optionally in the notification area). I've come across several good resources on this subject (something like http://progrnotes.blogspot.com/2010/09/c-android.html). Unfortunately, all the examples don't provide a clear indication on how to properly cancel a download per the user's request. So my question is actually quite simple:
Given an asynctask which downloads the file in the background (with httpclient) and displays a dialogbox with download progress and a cancel button, how do I can cancel the download and stop the background task when the button is pressed?
I know killing threads is generally not a good idea, so I will probably need to work with a 'cancel'-variable in my background thread. How do I communicate a stop signal from the button to the asynctask?
Regards,
Ivo
Have your button call AsyncTask.cancel(true) and then check isCancelled() from inside doInBackground(Params... params). In this manner, you can communicate to the background thread that the download should be cancelled, and you can take the appropriate steps to stop it.
I would call cancel(true) on your AsyncTask object. This will interrupt your thread via normal interruption handling. You then can ask the AsyncTask if it isCancelled().
I would suggest you to go through this link for the dark-side of AsyncTasks: http://bon-app-etit.blogspot.in/2013/04/the-dark-side-of-asynctask.html .
Google has released a library called "Volley" that is used nowadays for faster and better networking .
It solves Bad points of AsyncTasks.
Canceling request using volley

Categories

Resources