AppStatusService
Java code
Package org. wp. activity;
Import java. util. List;
Import android. app. ActivityManager;
Import android. app. ActivityManager. RunningAppProcessInfo;
Import android. app. Service;
Import android. content. Context;
Import android. content. Intent;
Import android. OS. IBinder;
Import android. util. Log;
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 = (ActivityManager) 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 are running on the device
List <RunningAppProcessInfo> appProcesses = activityManager. getRunningAppProcesses ();
If (appProcesses = null) return false;
For (RunningAppProcessInfo appProcess: appProcesses ){
// Importance:
// The relative importance level that the system places
// On this process.
// May be one of IMPORTANCE_FOREGROUND, IMPORTANCE_VISIBLE,
// IMPORTANCE_SERVICE, IMPORTANCE_BACKGROUND, or IMPORTANCE_EMPTY.
// These constants are numbered so that "more important" values are
// Always smaller than "less important" values.
// ProcessName:
// The name of the process that this object is associated.
If (appProcess. processName. equals (packageName)
& AppProcess. importance = RunningAppProcessInfo. IMPORTANCE_FOREGROUND ){
Return true;
}
}
Return false;
}
}