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 the background or brought to the foreground?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
ProcessLifecycleOwner
seems to be a promising solution also.An implementation can be as simple as
According to source code, current delay value is
700ms
.You can use:
To differ between new starts and restarts.
Here is my solution. Just register this ActivityLifecycleCallbacks in your main Application class. In the comments, I mention a user profile Activity edge case. That Activity is simply one with transparent edges.
This appears to be one of the most complicated questions in Android since (as of this writing) Android doesn't have iOS equivalents of
applicationDidEnterBackground()
orapplicationWillEnterForeground()
callbacks. I used an AppState Library that was put together by @jenzz.It turned out this is exactly what I needed, especially because my app had multiple activities so simply checking
onStart()
oronStop()
on an activity wasn't going to cut it.First I added these dependencies to gradle:
Then it was a simple matter of adding these lines to an appropriate place in your code:
Depending on how you subscribe to the observable, you may have to unsubscribe from it to avoid memory leaks. Again more info on the github page.
Since I did not find any approach, which also handles rotation without checking time stamps, I thought I also share how we now do it in our app. The only addition to this answer https://stackoverflow.com/a/42679191/5119746 is, that we also take the orientation into consideration.
Then, for the callbacks we have the resume first:
And onActivityStopped:
And then, here comes the addition: Checking for orientation changes:
That's it. Hope this helps someone :)
This is my solution https://github.com/doridori/AndroidUtils/blob/master/App/src/main/java/com/doridori/lib/app/ActivityCounter.java
Basically involved counting the lifecycle methods for all Activity's with a timer to catch cases where there is no activity currently in the foreground but the app is (i.e. on rotation)