Check if Activity is running from Service

前端 未结 8 419
星月不相逢
星月不相逢 2020-12-02 22:29

How can a Service check if one of it\'s application\'s Activity is running in foreground?

相关标签:
8条回答
  • 2020-12-02 23:01

    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; 
    } 
    
    0 讨论(0)
  • 2020-12-02 23:09

    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.

    0 讨论(0)
提交回复
热议问题