make the UI counter, cast preference state, resumed state synchronized

This commit is contained in:
Domingos Lopes 2016-04-19 00:05:55 -04:00
parent 78b2ceab57
commit 3a5b43a67d
1 changed files with 28 additions and 27 deletions

View File

@ -27,9 +27,10 @@ public abstract class CastEnabledActivity extends AppCompatActivity
public static final String TAG = "CastEnabledActivity";
protected CastManager mCastManager;
private volatile int castUICounter;
private final Object UI_COUNTER_LOCK = new Object();
private volatile boolean isResumed = false;
protected SwitchableMediaRouteActionProvider mMediaRouteActionProvider;
protected volatile boolean isCastEnabled;
protected volatile boolean isCastEnabled = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
@ -38,7 +39,6 @@ public abstract class CastEnabledActivity extends AppCompatActivity
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
registerOnSharedPreferenceChangeListener(this);
castUICounter = 0;
mCastManager = CastManager.getInstance();
mCastManager.addCastConsumer(castConsumer);
isCastEnabled = UserPreferences.isCastEnabled();
@ -72,46 +72,47 @@ public abstract class CastEnabledActivity extends AppCompatActivity
@Override
protected void onResume() {
super.onResume();
castUICounter++;
synchronized (UI_COUNTER_LOCK) {
isResumed = true;
if (isCastEnabled) {
mCastManager.incrementUiCounter();
castUICounter++;
}
}
}
@Override
protected void onPause() {
super.onPause();
castUICounter--;
synchronized (UI_COUNTER_LOCK) {
isResumed = false;
if (isCastEnabled) {
mCastManager.decrementUiCounter();
castUICounter--;
}
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (UserPreferences.PREF_CAST_ENABLED.equals(key)) {
isCastEnabled = UserPreferences.isCastEnabled();
Log.d(TAG, "onSharedPreferenceChanged(), isCastEnabled set to " + isCastEnabled);
mMediaRouteActionProvider.setEnabled(isCastEnabled);
if (isCastEnabled) {
//Test if activity is resumed but without UI counter incremented
if (castUICounter==1) {
boolean newValue = UserPreferences.isCastEnabled();
Log.d(TAG, "onSharedPreferenceChanged(), isCastEnabled set to " + newValue);
synchronized (UI_COUNTER_LOCK) {
if (isCastEnabled != newValue && isResumed) {
if (newValue) {
mCastManager.incrementUiCounter();
castUICounter++;
}
} else {
if (castUICounter > 1) {
mCastManager.decrementUiCounter();
castUICounter--;
}
if (!PlaybackService.isRunning) {
}
isCastEnabled = newValue;
}
mMediaRouteActionProvider.setEnabled(isCastEnabled);
// PlaybackService has its own listener, so if it's active we don't have to take action here.
if (!isCastEnabled && !PlaybackService.isRunning) {
CastManager.getInstance().disconnect();
}
}
}
}
CastConsumer castConsumer = new CastConsumerImpl() {
@Override