prevent aynctask getting killed before completion? - android

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.

Related

proper way to know if an activity has been finished

I've read
"How to know activity has been finished?
" and "Proper way to know whether an Activity has been destroyed"
but none of them got real answers
I've a background task updating a screen with it's progress
The user has a button to cancel the background task at any moment, and if he does that the background task will be stoped and activity will be finished...
BUT as all of this happen in an asynchronous enviroment the following situation may happen:
1- the background task stacks some notification to update progress activity
2- the user cancel the background task
3- the background task is stopped (i mean, stops having progress) and activity is finished (activity.finish())
4- the previous stacked updates are delivered to the activity which tries to perform some update on its fields and lead to error
I would like an "oficial android approach" better than having a boolean which is set to true during onDestroy()
Since you're finishing the activity by calling finish() then I think checking isFinishing() before updating the UI would work in your use case.
For more advanced use cases I suggest you should look into RxJava for doing asynchronous background tasks that are tightly coupled with activity lifecycle.

android: onPostExecute of Asynchtask after Activity finished

AsynchTask got onPostExecute() method tied to UI thread. Assume that we close an activity by pressing back button while AsynchTask doInBackground() method is still in progress.
I want to know will onPostExecute executes by considering that activity is not displaying on screen anymore?
In case answer is yest, will it cause exceptions or not? (because of accessing UI objects which are not longer displayed on screen).
1-I want to know will onPostExecute executes by considering that
activity is not displaying on screen anymore?
yes!
2-In case answer is yest, will it cause exceptions or not? (because of
accessing UI objects which are not longer displayed on screen).
Yes! it may cause Exception because your Instance of your Activity and Views which you use in your AsyncTask are not exist anymore
This Link will help you more : AsyncTask won't stop even when the activity has destroyed

How to show progressdialog when the main UI thread is blocked?

Before I'm lampooned, for blocking the main UI thread, here is the scenario:
A Service runs once a day - takes around 15 secs to complete. Heavy database transactions
By coincidence the user starts the app during that time
The home screen loads data from the database
But because the database is locked (step 1), this throws an error.
So I need to FREEZE the UI thread till the service is completed. No AsyncTask because the UI will continue to execute and throw an error. I've managed to put the "onResume" function to sleep till the service finishes. But during that time I'm unable to show any dialogs telling the user to wait or any progress bar telling the user to sit tight.
If I try
start onResume
if (service is running?)
show progress dialog
while the service is running, thread.sleep
dismiss progress dialog
end onResume
The thread sleeps fine and wakes up great. But the damn progress dialog doesn't show till onResume...resumes! Bottom line, how do I show an indicator (progressdialog or dialog) before I put the main thread to sleep?
I'm open to solutions that load another activity till the service resumes. I've tried that, but the previous activity continues on happily :|
You can not show a progress dialog if you are blocking the UI thread.
I guess you want to invoke the dialogue in onResume, but the UI won't start to show the dialog before onResume and onPaused are done. But as you are blocking the UI thread in OnResume this will not be reached until the blocking is over. Therefor its not possible.
You need to put the waiting in an async task and callback to your UI thread when done.
Good would be to take a loading-activity that starts your actual activity when the DB update is finished.

why does the ProgressBar in my DialogFragment stop spinning?

I have the following structure:
in UIActivity1:
MyMyProgressDialogFragment progressDialog = MyMyProgressDialogFragment.newInstance();
progressDialog.show(getFragmentManager(),"dialog");
getFragmentManager().executePendingTransactions();
..do some heavy work and send messages to progressDialog
The DialogFragment gets created and the ProgressBar in this fragment starts spinning.
But when I now start the heavy work in the activity which created the dialog fragment the progress bar within the fragment stops.
When reading through the fragment doc I understand that a fragment has its own activity - same as the Ui Activity1. And afaik each activity runs in a separate thread.
So why does the progressbar in the dialog fragment stop when the UIActivity1 starts with its heavy work?
Shouldn't they be independant?
ps when I run the heavy work outside the UIActivity in a different task again, the progress bar keeps spinning without problems.
Where is my mistake in understanding here?
Thanks!
Its not clear from the information you have shared, however looks like you are doing all your heavy execution in your UI Thread. That is the activity's main thread. Whether the activity you spin off with your fragment is meant to do just this work is irrelevant, the UI thread has to be used only to update the UI elements and generally avoid tasks that take longer than 100 - 200 ms. This is as per android Non-Responsive Application documentation. This is probably the problem, any long standing or long executing tasks have to be done in a background thread.
Take a look at this example of using the progressbar in Android.

Loading an Alert Box from a Thread when the activity has gone away

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.

Categories

Resources