How can a Service check if one of it\'s application\'s Activity is running in foreground?
Erian has the correct answer, but its not safe to use "getDefaultSharedPreferences". When you start a Service it use a differente instance that the Activity. Any changes of preferences in the activity, doesnt update the default shared preferences in the Service. So i will change Erian code with ".getSharedPreferences" like this:
In Activity:
@Override
public void onPause() {
super.onPause();
getApplicationContext().getSharedPreferences("preferences", MODE_MULTI_PROCESS).edit().putBoolean("isActive", false).commit();;
}
@Override
public void onDestroy() {
super.onDestroy();
getApplicationContext().getSharedPreferences("preferences", MODE_MULTI_PROCESS).edit().putBoolean("isActive", false).commit();
}
@Override
public void onResume() {
super.onResume();
getApplicationContext().getSharedPreferences("preferences", MODE_MULTI_PROCESS).edit().putBoolean("isActive", false).commit();
}
In Service:
if (getApplicationContext().getSharedPreferences("preferences", MODE_MULTI_PROCESS).getBoolean("isActive", false)) {
return;
}