Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell the activity has been covered by the notification area?

Usually, Android calls onPause on your Activity when it starts being obscured or hidden, followed by onStop when it's no longer shown at all. In my game, I pause the game in onPause, so the user doesn't lose the game while looking elsewhere.

However, when the user drags down the notification bar, it covers my Activity, but neither onPause nor onStop are called. This doesn't seem to be mentioned in the documentation. The game ticks away in the background with nobody looking at it. Is there some other way to tell my Activity has been obscured when this happens, so I can pause the game before the user loses? I can't find anything at all about this on the Android Developers site.

like image 477
Dan Hulme Avatar asked Oct 02 '12 11:10

Dan Hulme


1 Answers

The onWindowFocusChanged(boolean hasFocus) of Activity should serve the required purpose. It is called with false when the notification area is dragged down, and with true once the area is dragged back up. The corresponding Android documentation states that this method "is the best indicator of whether this activity is visible to the user". It also explicitly states that the callback is triggered when the "status bar notification panel" is shown.

It is important to note that this method is also called in other situations. A good example is the display of an AlertDialog. onWindowFocusChanged is even called when the activity itself shows an AlertDialog. This might require consideration, depending on if your game uses AlertDialogs or something else which causes a focus change.

In a scenario similar to the one described in this question, we've used the onWindowFocusChanged method successfully, e.g. on a Nexus 5 with Android 4.4, or a Sony Xperia Tablet with Android 4.1.

like image 91
Stephan Palmer Avatar answered Sep 27 '22 16:09

Stephan Palmer