5

Problems with the life cycle of the activity (How to detect if the activity is i...

 2 years ago
source link: https://www.codesd.com/item/problems-with-the-life-cycle-of-the-activity-how-to-detect-if-the-activity-is-in-the-foreground.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Problems with the life cycle of the activity (How to detect if the activity is in the foreground)

advertisements

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.


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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK