Skip to content

Commit

Permalink
Fix playing music in bg when sign out
Browse files Browse the repository at this point in the history
  • Loading branch information
iamoscarliang committed Nov 23, 2024
1 parent 307c4dc commit 81504e3
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
17 changes: 15 additions & 2 deletions app/src/main/java/com/oscarliang/spotifyclone/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import androidx.navigation.ui.NavigationUI;

import com.oscarliang.spotifyclone.core.auth.AuthManager;
import com.oscarliang.spotifyclone.core.player.MusicPlayer;
import com.oscarliang.spotifyclone.databinding.ActivityMainBinding;

import java.util.Objects;
Expand All @@ -35,6 +36,9 @@ public class MainActivity extends AppCompatActivity implements HasAndroidInjecto
@Inject
AuthManager authManager;

@Inject
MusicPlayer musicPlayer;

private ActivityMainBinding binding;
private NavController navController;
private View navView;
Expand Down Expand Up @@ -79,8 +83,7 @@ private void initToolbar() {
private void initDrawer() {
binding.drawer.navView.setNavigationItemSelectedListener(item -> {
if (item.getItemId() == R.id.action_logout) {
authManager.signOut();
navigateWelcomeFragment();
signOut();
}
item.setChecked(true);
binding.drawerLayout.close();
Expand Down Expand Up @@ -172,6 +175,16 @@ private void subscribeAuthState() {
);
}

private void signOut() {
// Clear all the music to prevent playing
// the music in bg when user is not log in
musicPlayer.clearMusic();

// Sign out and navigate to welcome page
authManager.signOut();
navigateWelcomeFragment();
}

private void navigateWelcomeFragment() {
// Pop up all the backstack to prevent navigating back
navController.navigate(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,15 @@ public void addPlaylist(@NonNull List<Music> musics, @NonNull String playlistId)
this.musics.onNext(musics);
}

@Override
public void clearMusic() {
// Stop the current music and clear all the media items.
// Note that we do not call release(), or the player
// will be unavailable when later the user re-login.
mediaController.stop();
mediaController.clearMediaItems();
}

private MediaItem createMediaItem(Music music) {
return new MediaItem.Builder()
.setMediaId(music.getId())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,6 @@ public interface MusicPlayer {

void addPlaylist(@NonNull List<Music> musics, @NonNull String playlistId);

void clearMusic();

}

0 comments on commit 81504e3

Please sign in to comment.