multithreading - Android AsyncTask context behavior -


I am working with AsyncTasks in Android and I'm dealing with a problem.

Simple example, working on an activity background with an AsyncTask does nothing great, it sleeps for just 8 seconds.

At the end of AsyncTask in OnPostExecute () method I'm just setting a visual visibility status to view. Visual, only to confirm your results.

Now, it works until the user can change the position of his phone unless the task is working in a casual (within 8 seconds sleeping window).

The Android Lifecycle Activity and I know that the activity is destroyed and rebuilt.

This is where the problem arises. AsyncTask is referring to a button and apparently holds the context reference in which AsyncTask first place.

I hope this old reference (since the user has made an orientation change) is either to become null and to see ASCNETK trying to throw the NPE for the reference of the button is.

Instead, no NPE is thrown, Async Task thinks that the button reference is not zero, it sets it visible. result? Nothing is happening on the screen!

Update: I have encountered this to keep this activity WeakReference and switching to a configuration change. It's cumbersome.

Here is the code:

  Public class main extended activity {Personal button mButton = null; Private button mTestButton = null; Override public null on @reate (bundle saved instainstate) {super.naught (savedinstenstate); SetContentView (R.layout.main); MButton = (button) Find ViewById (R.id.btnStart); MButton.setOnClickListener (New OnClickListener) {@Override Public Zero Click on (see V) {New Function DojoSaming (). Execute (0L);}}); MTestButton = (Button) findViewById (R.id.btnTest); } Private class workshops like some AsyncTask & lt; Long, integer, integer & gt; {@ Override protected integer doinbackground (long ... parameter) {log. I ("logger", "starting ..."); Try {Thread.sleep (8000); } Grip (Interrupted e) e.printStackTrace (); } Return 0; } @Override Secure Zero on postexec (integer result) {log. I ("LOGGER", "... done ..."); MTestButton.setVisibility (View.VISIBLE); }}}  

Try executing it and when AsyncTask is changing its phone orientation.

Async Task is not designed to be used again, once an activity is broken Is and has been restarted. The internal handler object becomes stale, as you said. In the Shelves example of Romain Guy, it cancels any currently running AsyncTask and then restarts the new orientation change.

This is possible to hand over your thread to the new activity, but it adds a lot about the pipeline is generally not agreed to do so, but here you read about my method Can:


Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -