RoadMovie

write down memos or something I found about tech things

AndroidアプリのonResumeとonPause

かなりラフな記事になるけど、Androidでアプリがforeground(起動中)の時とbackgroundにある時とでの挙動に手を加えたかったり、そうなるタイミングで何か処理を行いたいということがあると思う。

Lifecycleを調べると、onResumeonPuase がそれぞれforegroundとbackgroundに対応しているように思われるが、これは必ずしも100%保証された動作ではない。

これらの検知をどう正確に実現するのかは下記のStackOverflowが役に立つのでそちらに譲ることにする。

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


私が手こずらされた原因になったのは下記。知っていればなんてことないが、あまりAndroidアプリの経験がないと困る可能性がある。

android - OnPause is called right after OnResume - Stack Overflow

Note: When the system calls your activity's onPause() method, the system may be signaling that the activity will be paused for a moment and the user may return focus to your activity, or that the app is running in multi-window mode. However, this method call may also be the first indication that the user is leaving your activity.

ここにあるように、ユーザーがactivityを離れるときにもonPauseは呼ばれる。要はあなたのアプリでactivityを複数使っている場合(多くはそうだと思われるが)、そのactivity間の遷移でもonPauseは呼ばれる。

Keep in mind that onResume is not the best indicator that your activity is visible to the user; a system window such as the keyguard may be in front. Use onWindowFocusChanged(boolean) to know for certain that your activity is visible to the user

また、上記もある特定のユースケース(私が関わっているアプリはそうだった)では面倒な事になるので、正確に onResumeonPause の挙動を理解する必要がある人は頭に入れておきたい内容。