I am doing a status bar notification in my android app that is triggered by c2dm. I don't want to display the notification if the app is running. How do you determine if the app is running and is in 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
Here is a method that I use (and supporting method):
Since API 16 you can do it like this:
There is no global callback for this, but for each activity it is onStop(). You don't need to mess with an atomic int. Just have a global int with the number of started activities, in every activity increment it in onStart() and decrement it in onStop().
Follow this
Starting support library version 26 you can use ProcessLifecycleOwner to determine app current state, just add it to your dependencies like described here, for example:
, Now you can query
ProcessLifecycleOwner
whenever you want to check app state, for example to check if app is running in foreground you just have to do this:Following up on Gadenkan's reply I needed something like this so I could tell if my app wasn't running in the foreground, but I needed something that was app wide and didn't require me setting/unsetting flags throughout my application.
Gadenkan's code pretty much hit the nail on the head but it wasn't in my own style and felt it could be tidier, so in my app its condensed down to this.
(Side note: You can just remove the ! if you want the check to work the other way around)
Although with this approach you need the
GET_TASKS
permission.As Vinay says, probably the best solution (to support newer android versions, 14+) is to use
ActivityLifecycleCallbacks
in theApplication
class implementation.And in Application
onCreate()
method:Then
ApplicationLifecycleManager.isAppVisible()
orApplicationLifecycleManager.isAppInForeground()
would be used to know the desired state.