I have an Activity that starts an AsyncTask. The activity is allowed to show in Portrait or Landscape orientation. When the orientation is
The best way I found after some research was to create an application class and rely on onTrimMemory() method. A problem with this approach - onTrimMemory() does not get called if screen times out or screen gets locked by pressing power button so I had to implement that logic separately.
/**
* When your app's process resides in the background LRU list:
* TRIM_MEMORY_BACKGROUND
* TRIM_MEMORY_MODERATE
* TRIM_MEMORY_COMPLETE
*
* When your app's visibility changes:
* TRIM_MEMORY_UI_HIDDEN
*/
@Override
public void onTrimMemory(final int level) {
super.onTrimMemory(level);
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
|| level == ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
|| level == ComponentCallbacks2.TRIM_MEMORY_COMPLETE
|| level == ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
// App went in background
}
}
Following code is to detect screen lock. I implemented this code in one of the ActivityLifecycleCallbacks method - onActivityStopped()
final PowerManager powerManager = (PowerManager) getAppContext().getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (!powerManager.isScreenOn()) {
// Screen locked
}
} else {
if (!powerManager.isInteractive()) {
// Screen locked
}
}