Doing Long Term Work at onDestroy

I have a “lengthy” cleanup operation that I need to perform in onDestroy() my Activity . What is the best way to do this?

If I use Thread for this, my onDestroy() will immediately return; but what happens with the thread reference? I am looking for advice on any consequences of / gotchas / trip -wire that I need to know here, since I assume that the process will still be available even after the Activity is destroyed.


History:

I am using JmDNS in my application. When the user has finished working with my application, I want to clear the JmDNS instance. I do this using the close() method of the JmDNS class. However, this method takes more than 5 seconds . As a result, the user sees my Activity on the screen for a long time after touching the "Back" key.

I have yet to find out why close() takes so long, but at the same time, I also realized that I really don't need to wait for completion to complete successfully. All I need to do is to “start” the closure and do it with it.

+6
source share
2 answers

I finished work on what I asked in the question. I run Thread to perform a lengthy operation in onDestroy() .

In one case, I had to think about when a user opens my application again before the work is completed. In my application, this means that a new instance of JmDNS is being created. So, I clean up each instance separately in onDestroy .

Your use case may differ - you can start the cleanup thread only if it is not already running (using the Thread isAlive() method or some other such method).

Here is a sample code. To evaluate the “clear each instance separately” part, follow these steps:

  • Run the application
  • Click the back button. You will see the cleanup operation in LogCat
  • Launch the app.
  • Exit the application again. You will now see two sets of cleanup logs - the first one representing the cleanup for the first instance; and a 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(); } } 
+3
source

Try starting the thread in onBackPressed() and call destroy() when your thread is complete.

+1
source

Source: https://habr.com/ru/post/909530/


All Articles