your issue can be solved if you use a custom Application class. say like
public class MyApp extends android.app.Application
{
}
and inside this put your code that you want to be called anywhere in your app.
Now only you require to get the application object in your Activity
like this
MyApp app = (MyApp) getApplication();
app.setUpBeforeClosingApp();
and you can put this inside every onDestroy()
of Activity and from here code handling before closing actions can be achieved.