Created
December 1, 2015 07:02
-
-
Save bitristan/2e150547813e7a4cd6a7 to your computer and use it in GitHub Desktop.
Check whether app is in background.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.ActivityManager; | |
import android.content.ComponentName; | |
import android.content.Context; | |
import android.os.Build; | |
import java.util.List; | |
public class AppUtil { | |
private static final int KITKAT_WATCH = 20; | |
/** | |
* Detect whether our app is in foreground or background. | |
* | |
* @param context | |
* @return | |
*/ | |
public static boolean isAppIsInBackground(Context context) { | |
boolean isInBackground = true; | |
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); | |
if (Build.VERSION.SDK_INT > KITKAT_WATCH) { | |
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses(); | |
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) { | |
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { | |
for (String activeProcess : processInfo.pkgList) { | |
if (activeProcess.equals(context.getPackageName())) { | |
isInBackground = false; | |
} | |
} | |
} | |
} | |
} else { | |
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); | |
ComponentName componentInfo = taskInfo.get(0).topActivity; | |
if (componentInfo.getPackageName().equals(context.getPackageName())) { | |
isInBackground = false; | |
} | |
} | |
return isInBackground; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment