title: When should I free the native (Android NDK) handles?
body: <p>I have to use a native library (this is not my decision). The library already has a JNI wrapper, and the example Android NDK code works. But <strong>the library initialization routines return native handles and the developer is required to correctly close them</strong>.</p>
  
  <p>Now, there's an interesting question: <strong>where to call the close_handle routines from?</strong></p>
  
  <p>At least in theory, each incorrect termination may result in temporary files left somewhere on the disk or some other kind of resource leak.</p>
  
  <p>Library initialization takes from 0.5 to 1 sec and consumes a lot of memory.</p>
  
  <p>An <code>Activity</code> is a controller (in MVC sense), Android can kill it because of its own reasons, including turning the device, and the only function that is guaranteed to be called is <code>onPause()</code>. So <code>onPause</code>/<code>onResume</code> is a bad place for a long resource-consuming operation.</p>
  
  <p>(I know about <code>android:configChanges="keyboardHidden|orientation"</code>, but I would prefer a solution that does not need it.)</p>
  
  <p><code>Application</code> would be an ideal candidate (I consider the library to be a part of the model), but there is no "application terminates" event.</p>
  
  <p>A <code>Service</code> sounds promising, that native library <em>is</em> a service, but I just do not see how I can have the desired behavior: the handles must be closed when the application terminates.</p>
  
  <p>Timeouts: sounds like a trade-off, but in fact it guarantees that the memory will not be available the moment it is needed but will become available a few seconds later.</p>