How to check if my activity is the current activity running in the screen

virsir picture virsir · Jul 16, 2010 · Viewed 51k times · Source

I used Toast to make notification, but it seems it will appear even its activity is not in the current screen and some other activity has been started.

I want to check this situation, when the activity is not the current one, I'd not send the Toast notification. But how to do ?

Answer

Andy Zhang picture Andy Zhang · Jul 16, 2010

When your Activity comes to the foreground, its onResume() method will be invoked. When another Activity comes in front of your Activity, its onPause() method will be invoked. So all you need to do is implement a boolean indicating if your Activity is in the foreground:

private boolean isInFront;

@Override
public void onResume() {
    super.onResume();
    isInFront = true;
}

@Override
public void onPause() {
    super.onPause();
    isInFront = false;
}