Reputation: 621
I have a worker thread run by my activity. When exiting the activity (e.g. onPause()), I'm sending a message to this thread and it should finish shortly (milliseconds) after, unless something goes wrong. Normally, I would use join() in onPause(), but in this case, this thread has to use the UI thread in order to perform its shutdown sequence (closing an Accessory file descriptor doesn't work from any other thread it seems). So attempting to block the UI thread will cause a deadlock. I'm looking for a solution that will somehow postpone the app exit until after the thread exits. Possibly, if I could just abort the exit in such a case, I could later call finish() manually, but I'm not sure whether this (aborting) can be done.
Just assuming that the thread will eventually finish its cleanup and exit seems like a very unsafe practice.
Upvotes: 1
Views: 983
Reputation: 2153
As you said, you cannot keep the UI thread waiting for the background thread to stop indefinitely.
You can do the following things.
1) Interrupt the thread in onPause().(This won't persist any info if you want during cleanup)
2)If you want to persist some information and perform a clean exit, you can start an Androiod service in onPause() and do the cleanup there. (Check for a boolean flag timely inthe thread) ex : A pseudo example
void run(){
while(true){
if(bExit){
doCleanupWork();
}
//Do work
doWork();
}
}
void doCleanupWork(){
startCleanupService();
}
void onPause(){
bExit = true;
}
3)Override onBackPressed() of Activity class so that it won't exit directly.Start an AsyncTask and show a dialog to the user indicating processing while cleanup calls occur in doInBackground() .If you are unsure that the cleanup might get hanged, you need to recheck the code and if required Interrupt the thread after a timeout.
Upvotes: 1
Reputation: 2924
declare a handler in the UI thread. When the other thread has finished, send an (empty) message from the other thread to that handler, which will cause the handleMessage method to exectue on the UI thread. Do your final UI cleanup in handleMessage.
Upvotes: 0