Performing long running operation in onDestroy

前端 未结 2 715
滥情空心
滥情空心 2021-01-18 08:13

I have a \"long-running\" cleanup operation that I need to perform in onDestroy() of my Activity. What is the best way to do this?

If I use

相关标签:
2条回答
  • 2021-01-18 08:16

    I ended up doing what I had asked in the question - I start a Thread to perform the long-running operation in onDestroy().

    One case I had to consider was when the user re-opens my app even before the long-running has completed. In my app, this means a new instance of JmDNS gets created. So, I clean up each instance separately in my onDestroy.

    Your use case might differ - you might want launch the cleanup thread only if it is not already running (using Thread's isAlive() method or some such technique).

    Here's some sample code. To appreciate the "clean up each instance separately" part, perform the following sequence of steps:

    1. Launch the app
    2. Press the back button. You will see the clean up operation in LogCat
    3. Re-launch the app.
    4. Again, exit the app. Now, you will see two sets of cleanup logs - the first one representing cleanup for the first instance; and the second set corresponding to the second instance.

      public class DelayedExitActivity extends Activity {
      
          private static final String LOG_TAG = "DelayedExit";
          private final  Runnable longOperation = new Runnable(){
              @Override
              public void run() {
                  for (int i=0 ; i < 50; i++){
                      Log.d(LOG_TAG, "Iteration "+i);
                      try {
                          Thread.sleep(2 * 1000);
                      } catch (InterruptedException e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                  }
              }
          };
          private Thread longThread ;
      
          /** Called when the activity is first created. */
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
          }
      
          @Override
          protected void onDestroy() {
              if(longThread == null){
                  longThread = new Thread(longOperation);
              }
              longThread.start();
              super.onDestroy();
          }
      }
      
    0 讨论(0)
  • 2021-01-18 08:30

    Try to start your thread in onBackPressed() and call destroy() when your thread will be finished.

    0 讨论(0)
提交回复
热议问题