Check if Activity is running from Service

前端 未结 8 461
星月不相逢
星月不相逢 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:00

    Starting from Lollipop, getRunningTasks is deprecated:

     * 

    Note: this method is only intended for debugging and presenting * task management user interfaces. This should never be used for * core logic in an application, such as deciding between different * behaviors based on the information found here.

    * * @deprecated As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method * is no longer available to third party applications.

    One way to do this is to bind to the service on app start. Then: 1. If you need to check any of the app's activity is running, you can create a base class for your activities and override onPause and onResume. In onPause, call a service method to let it know it is on the background. In onResume, call a service method to let it know it is on the foreground. 2. If you only need to do this on some specific activity, just override onResume and onPause on those activities or create a base activity for those activities.

提交回复
热议问题