How can a Service
check if one of it\'s application\'s Activity
is running in foreground?
I think you can getRunninTasks on Android and check with your packagename if the task is running or not.
public boolean isServiceRunning() {
ActivityManager activityManager = (ActivityManager)Monitor.this.getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
isServiceFound = false;
for (int i = 0; i < services.size(); i++) {
if (services.get(i).topActivity.toString().equalsIgnoreCase("ComponentInfo{com.lyo.AutoMessage/com.lyo.AutoMessage.TextLogList}")) {
isServiceFound = true;
}
}
return isServiceFound;
}
With Android Architecture Components it is quite straight forward to check this
annotationProcessor 'android.arch.lifecycle:compiler:1.1.1'
implementation 'android.arch.lifecycle:extensions:1.1.1'
The lifecycle observer class, keeping a pref flag
public class AppLifecycleObserver implements LifecycleObserver {
public static final String TAG = "AppLifecycleObserver";
@OnLifecycleEvent(Lifecycle.Event.ON_START)
void onEnterForeground() {
Log.d(TAG, "onEnterForeground");
PreferencesUtils.save(Constants.IN_FOREGROUND, true);
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onEnterBackground() {
Log.d(TAG, "onEnterBackground");
PreferencesUtils.save(Constants.IN_FOREGROUND, false);
}
}
Application Class observers the lifecycle
public class App extends Application {
private static App instance;
public static App getInstance() {
return instance;
}
@Override
public void onCreate() {
super.onCreate();
AppLifecycleObserver appLifecycleObserver = new AppLifecycleObserver();
ProcessLifecycleOwner.get().getLifecycle().addObserver(appLifecycleObserver);
}
Now, you can use the Pref flag to check anywhere you please.