Checking if an Android application is running in the background

前端 未结 30 2851
无人共我
无人共我 2020-11-21 06:19

By background, I mean none of the application\'s activities are currently visible to the user?

30条回答
  •  灰色年华
    2020-11-21 07:11

    The best solution I have come up with uses timers.

    You have start a timer in onPause() and cancel the same timer in onResume(), there is 1 instance of the Timer (usually defined in the Application class). The timer itself is set to run a Runnable after 2 seconds (or whatever interval you think is appropriate), when the timer fires you set a flag marking the application as being in the background.

    In the onResume() method before you cancel the timer, you can query the background flag to perform any startup operations (e.g. start downloads or enable location services).

    This solution allows you to have several activities on the back stack, and doesn't require any permissions to implement.

    This solution works well if you use an event bus too, as your timer can simply fire an event and various parts of your app can respond accordingly.

提交回复
热议问题