Android : how to know when an app enters or the “background” mode?

前端 未结 1 880
情歌与酒
情歌与酒 2021-02-20 13:44

I am trying to achieve the following with Android :

  • when the app is in background, a thread polls a server every now and then to retrieve data and notifies th

1条回答
  •  花落未央
    2021-02-20 14:32

    I'm going to reference the Activity Lifecycle. In between onResume and onPause your Activity is 'active', i.e., it's on the screen and the user can interact with it. If your activity's onPause method is called then you should assume that it is no longer 'active' and the user cannot interact with it anymore until onResume is called again. If you wish to track this in your service you're going to have to do this manually.

    This is probably most easily achieved by calling a method in your service in Activity#onResume that increments a counter or sets a flag and in onPause reverting that change. If you have multiple activities then you're most likely going to need a counter, probably an AtomicInteger, and use it to determine when you should resume your polling.

    I would probably wait for a small bit of time when the counter reaches 0, recheck it, and if it is still 0 resume polling. This would account for the gap between one activity's onPause and another's onResume.

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