I was using getRunningTask API in one of my application to find the Foreground application. This API has been deprecated since Lollipop. After this deprecation, I preferred
Get the list of RunningAppProcessInfo by ActivityManager.getRunningAppProcesses().
Choose the RuningAppProcessInfo with whose importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND and whose processState == ActivityManager.START_TASK_TO_FRONT.
(The former is easy, the latter is difficult because the reflection is necessary)
See my answer for this question getRunningTasks doesn't work in Android L