Android does not provide a native way to be notified of applications starting and stopping. This project solves that problem. Make your Activities inherit from ApplicationSessionActivity, and you can run code when the app starts and stops.
Java

README.md

ApplicationSessionActivity

Android does not provide a native way to be notified of applications starting and stopping. This project solves that problem.

Usage

For reference, the project includes a working example Android application composed of two Activities.

  1. Copy ApplicationSessionActivity into your project.
  2. Add the android.permission.GET_TASKS permission to your AndroidManifest.xml
  3. Make all of the Activities defined in your project extend ApplicationSessionActivity.
  4. Create an ApplicationSessionActivity.SessionStartedListener and ApplicationSessionActivity.SessionStoppedListener, and place the code you want to be run at app start and stop into their listener methods.