Added MainActivity lifecycle code that is necessary because of the ugly way MainActivity is tightly coupled with application state.