After loading the first activity, my application immediately starts downloading some files in a background process (I use new Thread() for this).
In the first activity, there is also a button which opens the second activity. It is crucial for the second activity that the background download is finished.
My task:
If user clicks on the button while the background download is not yet finished, the application must wait and not open the second activity. It must show a message like "Please wait" instead.
If in XX seconds after clicking download is not finished either, another message (with OK button) appears: "You have a too slow connection."
Have your thread broadcast a "completed" action to the main thread and stash this result.
Then on the UI thread you can check this variable to proceed.
you can check using
Thread myThread; //your thread that is downloading thigns
if(myThread.isAlive())
{
//do what you want here
}
You need to use AsyncTask for this.
Using its override methods.
Related
I have an "Create Ad" activity and async tasks for creating in my app. It's working but waiting with a progress dialog and this is boring sometimes because there is a file upload method it may take a while. I want to when user clicked the "Create" button; activity dont destroy, just hide then Async tasks work on behind and progress.
Is there any special keyword for when clicked create button and work on background and hide the creating activity?
Thanks for your help!
We use Async Task for operations less than 10 seconds because it works on main thread. If your operation is more than this, you should use intent service. It works on background thread.
you can use service for this .here is the documentation
in my activity, i have an asynctask that downloads a series of images...(it may take some time depending on the size of the images)... before i execute the asynctask, i display a progress dialog in onPreExecute and a notification (when user clicks on notification it is redirected to my activity with the progress dialog). when my asynctask completes, in onPostExecute, i remove the dialog and the notification.. i handle screen orientation by using onRetainNonConfigurationInstanceto save my asynctask so that when screen is rotated, i check if task is still running and i display the progress dialog if it is still running in onCreate
Problem : sometimes: my asynctask downloads only 1 file and it seems that it gets killed...(no exception in logcat)... as a result, my notication is always there and my progress dialog also... and they remain there indefinitely....
i have tried the solution by Jeff Axelrod there: How can I ensure an AsyncTask is completed before my activity is killed?:
It looks like if I override the onPause() event in my activity, and from within the overridden onPause(), I call cancel(false) on the AsyncTasks, then the activity is not destroyed until the AsyncTasks are completed.
seems to do the trick but problem is that my onPostExecute is not called anymore; all images download fine but as onPostExecute is not executed, notification and progress dialog still remain there forever.
waiting for your solutions guys! i read use asyntask only for short task; will the use of thread and handler solves my problem? will android kills my activity or thread if the latter is not finished??
Best way how to handle Asynctask is described in this article.
In short, the idea is to keep AsyncTask in fragment with setRetainInstance(true); these will keep You AsyncTask alive all time user is in activity holding this fragment and won't be destroyed on configuration change (orientation change).
If You need Your AsyncTask to run after user leaves Activity, for example goes to next Activity but You wish download to continue You should use services.
I have a file downloading android application.Here file is downloaded when user click on listview items.It works fine.
Now,I want to cancel current file download and start next file while user taps on other items and another download is already progressing and show user confirmation before canceling the download task.
How can i do this?
Thanks in Advance
First, you must check in your AsyncTask
// in doInBackground, check if asynctask is canceled manually
if (isCancelled()) break;
In your activiy, whenever you try to cancel, just cancel AsyncTask manually, and of course, start a new one to download another file!
mDownloadingTask.cancel(true);
Simply , you store your Asynctask to a variable:
mDownloadingTask = new Asynctask(){...};
mDownloadingTask.execute();
When you want to stop this task and start new one:
//close the current task if it # null
mDownloadingTask.cancel(true);
mDownloadingTask = null;
//Start new one
mDownloadingTask = new Asynctask(){...};
mDownloadingTask.execute();
Cancel(false) sets a flag, which you can check in doInBackGround() and stop your code from doing what its doing. cancel(true) does the same except it also interrupts the thread. See more info about interrupts here.
This is all good when you have a looped code in your task. Every iteration of the loop, you can check isCancelled().
But as in your question, some tasks like downloading a file do not use loops, perhaps you are just calling an external API method, so here, you are on the mercy of this blocking method. If well designed, it will throw an exception when interrupted, and the thread will terminate.
Also, have a look at a better implementation, SafeAsyncTask
I know how can we use the horizontal Progress bar from this link http://android-er.blogspot.in/2010/11/progressbar-running-in-asynctask.html
But I want to stop the running progress bat in between if my task is finished. I tried stop() and resume() methods but not worked.
I want to stop the running one and then restart it on click of some dialog box ok button.
I am new in android. Please support me.
If you are willing to resume stop a process that is being executed in a thread or an Asynctask the best way would be using a handler and sending messages that would act as requests to the process itself.
Sending a stop message (you define the message) so the process will handle the message and stop the thread and notify the main thread that is has been stopped.
Here are some useful articles about thread messageing and handlers:
http://developer.android.com/reference/android/os/Handler.html
http://codinghard.wordpress.com/2009/05/16/android-thread-messaging/
For example you could implement an animation with handlers sending messages to a handler which then executes an animation step, the step will then send another message to execute the next step: http://code.google.com/p/android-page-curl/source/browse/trunk/src/com/mystictreegames/pagecurl/PageCurlView.java
Here are some examples of a digg like app I made a while ago: http://code.google.com/p/meneameandroid/source/search?q=handleMessage&origq=handleMessage&btnG=Search+Trunk
I have a comment activity that loads a Thread and sends some data to a server; the activity is immediately finished once the submit button is pressed.
The user is then free to do other things in my application.
When the server responds an AlertDialog is shown.
The problem is that since the initial context has been destroyed, my application crashes.
I tried getApplicationContext() but still get an exception.
Put your network stuff in a Service, then show a status bar notification instead of a dialog.
Take a look at AsyncTask
From JavaDocs:
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.