Well, when your application goes into the background, the function onPause() of your current Activity is called.
You can easily override it and place your logic there
@Override
protected void onPause() {
// Another Activity has started, user has closed the application
// or started another one...
}
When your Activity comes into the foreground again, then onResume() is triggered.
@Override
protected void onResume() {
// the user re-opened your application, or came back from
// another activity
}
Note that onResume() is also always called after onCreate().
EDIT:
If I understood correctly all you need to know it's if there is a visible Activity. Not which one...
In that case @Journey's answer below should suit your needs.
I was wondering though, from where your will be checking if your Actvities are visible or not. I guess you will be using a Service or some sort of background mechanism.
In that case, a pattern commonly used pattern is the LocalBroadcastManager.
I had written a related answer here though you can find many others on SO.
Basically, in each of your activities, you register a Receiver when your Activity is visible, and un-register it when it goes into the background.
From your Service you send an Intent, and the Activity that is visible, if any, will respond to it.
Create the Receiver in your Activities.
this.localBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Do what you have to do here if you receive data from the Service / Background Task
}
}
Set up a Filter that will distinguish your signal from others:
public static final IntentFilter SIGNAL_FILTER = new IntentFilter("com.you.yourapp.MY_SIGNAL");
Remember to register the Receiver every time any of your Activities is visible.
@Override
protected void onResume() {
// Listen if a Service send me some data
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(this.localBroadcastReceiver, SIGNAL_FILTER);
}
When the Activity is closed stop listening to the signal:
@Override
protected void onPause() {
// I'm going to the background, no need to listen to anything anymore...
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(this.localBroadcastReceiver);
}
When your Service, or Background Task wants to send data to the currently visible Activity, you can call
final Intent intent = new Intent();
intent.setAction(SomeActivity.SIGNAL_FILTER);
// put your data in intent
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
If an Activity is visible it will receive the Intent, otherwise nothing will happen.