Wednesday, 15 February 2012

google cloud messaging - How to detect if your android app is in the foreground (API 21) -



google cloud messaging - How to detect if your android app is in the foreground (API 21) -

when receiving gcm message, behaviour of app depends on if in foreground or not. prior api 21 used following:

boolean onforeground = this.getpackagename().equalsignorecase( ((activitymanager) this.getsystemservice(context.activity_service)) .getrunningtasks(1).get(0).topactivity.getpackagename() );

now getrunningtasks() deprecated , behaving differently on api 21, best way on api 21 observe if app in foreground?

google recommends

public activitymanager.recenttaskinfo gettaskinfo ()

but not see how can info need there.

thank in advance.

edit: proposed @commonsware , @chris stratton, maintain track of onresume/onpause states. app-crash cause webview (content outside control) leave scheme in wrong state. sending gcm in such wrong state cause other crash confusing user (he/she not doing @ moment app).

i hence looking solution. (i using fragments , have 1 activity, implementing trivial)

you can utilize ordered broadcast approach you

create broadcastreceiver registered in manifest background behavior dynamically register broadcastreceiver in activity positive priority (the default 0), making sure register in onstart()/onresume() , unregistering in onstop()/onpause() - foreground behavior , should phone call abortbroadcast() ensure manifest registered broadcastreceiver not called

your gcm receiver can utilize sendorderedbroadcast() send broadcast (preferably custom action both other broadcastreceivers register for) received dynamically registered receiver if exists , manifest registered receiver if not exist.

android google-cloud-messaging android-5.0-lollipop

No comments:

Post a Comment