Logic is to get the running stack of the system, at the top of the stack is in the foreground app, and then compare the package name, the difference is that the app is in the background, conversely, it means the app is in the foreground.
/** * App is in the background * * @param context * @return true is false not */public Static Boolean IsBackground (Context context) { Activitymanager am = (activitymanager) context.getsystemservice (context.activity_service); list<activitymanager.runningtaskinfo> tasks = am.getrunningtasks (1); if (!tasks.isempty ()) { ComponentName topactivity = tasks.get (0). topactivity; Staticmethod.debugemsg (Topactivity.getpackagename () + ":" + context.getpackagename ()); if (!topactivity.getpackagename (). Equals (Context.getpackagename ())) { return true; } } return false; }
Android to determine if the app is in the foreground