public class Appstatusservice extends Service {private static final String TAG = "Appstatusservice"; Private Activitymanager Activitymanager; Private String PackageName; @Override public IBinder onbind (Intent Intent) {return null; } @Override public int onstartcommand (Intent Intent, int flags, int startid) {Activitymanager = (activit Ymanager) This.getsystemservice (Context.activity_service); PackageName = This.getpackagename (); New Thread () {public void run () {try {while (true) { Thread.Sleep (1000); if (Isapponforeground ()) {log.i (TAG, "true"); } else {log.i (TAG, "false"); }}} catch (Exception e) {e.printstacktrace (); } } }.Start (); Return Super.onstartcommand (Intent, flags, Startid); } private Boolean Isapponforeground () {//Returns a list of application processes that is running on the de vice List<runningappprocessinfo> appprocesses = Activitymanager.getrunningappprocesses (); if (appprocesses = = null) return false; for (Runningappprocessinfo appprocess:appprocesses) {//importance://The relative importance level, the system places//on this process. May is one of Importance_foreground, importance_visible,//Importance_service, Importance_background, or Importance_empty. These constants is numbered so, "more important" values is//always smaller than "less important" va Lues. ProcessName://The name of the process, the this object was associated with. if (AppProcess.processName.equals (PackageName) && appprocess.importance = = runningappprocessinfo.importance_foreground) {return T Rue }} return false; } }
Android Judging program front and back status