Search code examples
javaandroidandroid-music-player

How to play music on Android while activities are on foreground


I want to play music in the background of my application:

public class BackgroundSoundService extends Service {

    MediaPlayer mediaPlayer;

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = MediaPlayer.create(this, R.raw.airport_lounge);
        mediaPlayer.setLooping(true);
        mediaPlayer.setVolume(100,100);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mediaPlayer.start();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.stop();
        mediaPlayer.release();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Then in my MainActivity :

public static Intent musicIntent;

//Start music service
        musicIntent = new Intent(this, BackgroundSoundService.class);
        startService(musicIntent);

 @Override
    protected void onPause() {
        super.onPause();
        stopService(musicIntent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startService(musicIntent);
    }

I stop it in my onPause the service because if the user switches the Application and doesn't close it the music would continue to play. The problem is that when we change Activity the onPaused is also called but I want the music to continue playing through the entire application.

So in my another Activity :

//start music
    startService(MainActivity.musicIntent);

But the music restarts and it's not very good to hear. Any solutions?


Solution

  • You can use ActivityLifecycleCallbacks in your application class.

    public class MusicApplication extends Application implements ActivityLifecycleCallbacks {
        int activitiesOnTop = 0;
    
        @Override
        public void onCreate() {
            super.onCreate();
            registerActivityLifecycleCallbacks(this);
        }
    
    
        @Override
        public void onActivityResumed(Activity activity) {
            // one of application activities is visible
            activitiesOnTop ++;
        }
    
        @Override
        public void onActivityStopped(Activity activity) {
            activitiesOnTop --;
            if(activitiesOnTop == 0){
                  // none of activities are on foreground
            }
        }
    }
    

    There are other solutions mentioned in the How to check if activity is in foreground or in visible background?.