How to detect when an Android app goes to the background and come back to the foreground

后端 未结 30 1322
独厮守ぢ
独厮守ぢ 2020-11-22 00:56

I am trying to write an app that does something specific when it is brought back to the foreground after some amount of time. Is there a way to detect when an app is sent to

30条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 01:19

    This is the modified version of @d60402's answer: https://stackoverflow.com/a/15573121/4747587

    Do everything mentioned there. But instead of having a Base Activity and making that as a parent for every activity and the overriding the onResume() and onPause, do the below:

    In your application class, add the line:

    registerActivityLifecycleCallbacks(Application.ActivityLifecycleCallbacks callback);

    This callback has all the activity lifecycle methods and you can now override onActivityResumed() and onActivityPaused().

    Take a look at this Gist: https://gist.github.com/thsaravana/1fa576b6af9fc8fff20acfb2ac79fa1b

提交回复
热议问题