title: onSaveInstanceState/onPause - wait until state is fully saved before allowing process to be killed
body: <p>I'm working on my first Android app. It has a model that is persisted to a database as the user makes updates.</p>
  
  <p>When <code>onSaveInsanceState</code> is called, I want to save an id that can be used to load the document the user was working on from the database. But this can only happen once the document has fully hit the database. In some cases, persisting a complex document can take several seconds (I'm hoping this will speed up once I take all the verbose logging out, and in actual use a complex document will be built up by the user in stages, each of which will be persisted to the database, so it's not very likely for a complex document to have to all be saved in one go).</p>
  
  <p>Now, the #1 rule of threading on Android is "don't block the UI thread", so of course the DB interactions happen on a separate thread. But my understanding of the Android lifecycle is that in many cases onSaveInstanceState is being called because the Android system wants to kill the process. That suggests I can't allow this method to return until the DB thread finishes saving the document (and in fact with my current design, I don't actually know what the id number of the document is until it's been saved to the DB, so I can't even put that in the bundle of saved state).</p>
  
  <p>Is it appropriate under these circumstances to block the UI thread waiting for the persist task to be done? When <code>onSaveInstanceState</code> is called because the process is being killed, the app is no longer visible in the foreground, so there's no interface to become unresponsive.</p>
  
  <p>But <code>onSaveInstanceState</code> is also called when the Activity instance is being trashed by a config update, which happens when the screen orientation changes. It's very unfortunate when rotating the screen sideways fails to do anything for several seconds. In this case the process (and therefore memory space) is still around, so I don't strictly need to ensure the document hits the database, if I can just store a reference to it in the Bundle instead of its id. But I'm not aware of a way to tell the difference between these two cases.</p>
  
  <p>Is there an accepted practice for these situations? Should I just block the thread to be safe? Can I just use normal Java thread primitives to block and wait? Is there something I can do that <em>doesn't</em> block the thread but ensures the persist task will be finished before Android closes the process?</p>
  
  <p>All this also applies to <code>onPause</code>, as <code>onSaveInstanceState</code> isn't necessarily going to be called.</p>