Try it.
private static boolean isInForeground; onResume(){ isInForground = true; } onPause(){ isInForground = false; }
if isInForground is true , then the Activity is in Forground (Showing), otherwise it is not displayed.
if you want to know from anywhere, add the following to MainActivity.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); onResume(){ pref = PreferenceManager.getDefaultSharedPreferences(this); prefEditor = prefs.edit(); prefEditor.putBoolean("isInForeground",true); prefEditor.commit(); } onPause(){ pref = PreferenceManager.getDefaultSharedPreferences(this); prefEditor = prefs.edit(); prefEditor.putBoolean("isInForeground", false); prefEditor.commit(); }
Then from your service.
pref = PreferenceManager.getDefaultSharedPreferences(this); if(pref.getBoolean("isInForeground", false)){ //MainActivity is in forground } else{ //not in forground }
source share