Hi.

My activity has a thread that performs a long-running operation and
then notifies the UI thread via the activity handler.

When the activity is destroyed (no matter why), I want the thread and
its notification to die as quickly as possible.

Based on the "Handling Expensive Operations in the UI Thread" FAQ,
here is the outline of my solution:

public class MyActivity extends Activity {

   [ . . . ]
   // Need handler for callbacks to the UI thread
   final Handler mHandler = new Handler();
   private boolean destroyed = false;
   private Thread mThread = null;

   // Create runnable for posting
   final Runnable mUpdateResults = new Runnable() {
       public void run() {
           if (!destroyed) updateResultsInUi();
       }
   };

   [ . . . ]

   protected void startLongRunningOperation() {

       // Fire off a thread to do some work that we shouldn't do
directly in the UI thread
       mThread = new Thread() {
           public void run() {
               mResults = doSomethingExpensive();
               mHandler.post(mUpdateResults);
           }
       };
       mThread.start();
   }

   private void updateResultsInUi() {

       // Back in the UI thread -- update our UI elements based on
the data in mResults
       [ . . . ]
   }

       @Override
       protected void onDestroy() {
               super.onDestroy();
               destroyed = true;
               mHandler.removeCallbacks(mUpdateResults);
               if (mThread != null) {
                       Thread aux = mThread;
                       mThread= null;
                       aux.interrupt();
               }
       }
}

Is this "good enough"? Does somebody know a better way to implement
this? Is the "destroyed" boolean necessary (isFinishing is not
enough)?

Thank you!
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Android Beginners" group.
To post to this group, send email to android-beginners@googlegroups.com
To unsubscribe from this group, send email to
android-beginners-unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-beginners?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to