rootpanthera
rootpanthera

Reputation: 2771

Problems with activity lifecycle (How to detect if activity is in foreground)

I have broadcast receiver which fires off when user receives sms. Code within broadcast receiver should fire only when my activity is in foreground OR device is in sleep mode. But i have a small problem with detecting if my activity is in foreground. onResume i put boolean value "isActive" set to true and onStop i put boolean value "isActive" set to false. (it seems quite logical to detect if activity is in foreground this way ).

In following code i check either if screen is off or activity is in foreground and if one of expressions is true, then execute following code.

@Override
public void onReceive(Context context, Intent intent) {
if(!pm.isScreenOn() || HandleActivity.isHandleActivityActive) { 

// unnecessary code omitted

    //start activity
    intent = new Intent(MainService.this, HandleActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //Clear top is necessary otherwise would be a lot of new activites (depends on received sms)       
    startActivity(intent);
    }

}

But i don't know what is happening with activity lifecycle. When i receive sms first time its working perfectly. Boolean "isActive" has following values:

03-04 07:31:49.989: I/APP(7604): is handle activity active: true
03-04 07:31:50.169: I/APP(7604): is handle activity active: false
03-04 07:31:50.979: I/APP(7604): is handle activity active: true

When i receive SMS second time (activity is still in foreground. No sms was read or anything ) i got these values:

03-04 07:32:04.828: I/APP(7604): is handle activity active: true
03-04 07:32:06.849: I/APP(7604): is handle activity active: false

Because "isActive" is now false, "if" code cannot be executed. Can someone point me to right direction, what could be wrong or how to check if my activity is in foreground or something. I'm getting frustrated past 2 days because of this.

Thanks for any help.

Upvotes: 0

Views: 151

Answers (2)

aeliusd
aeliusd

Reputation: 469

I gather from your code:

if(!pm.isScreenOn() || HandleActivity.isHandleActivityActive) { 

that the isHandleActivityActive is a static variable right? In that case you might be checking if a previous activity was/is running instead of the actual activity you're in. Try changing that variable to a private instance variable instead and see if it works out.

Upvotes: 0

Rohit
Rohit

Reputation: 1001

Make your HandleActivity as SingleTop and let the activity get started every time a message arrives, it will work fine see this link http://developer.android.com/guide/topics/manifest/activity-element.html

Upvotes: 1

Related Questions