Search code examples
androidserviceandroid-mediaplayer

How to play music only in foreground


I have trouble to play music across all activity, I had implement service and handle onPause to stop the music when going to background (not visible to user).

The problem is when i navigate to another activity, the onPause method is called that make my music stop. How to fix this issue? I need to play my music across all my activity in foreground only and dont wan to play it when the application in the background. Appeciate anyone know how to solve this.

This is my base activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    startIntent = new Intent(getApplicationContext(), MusicService.class);
    if(binder==null){
        bindService(startIntent,this, Context.BIND_AUTO_CREATE);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if(binder.getMyService()!=null){
        stopService(startIntent);
        unbindService(this);
    }


}


@Override
protected void onStart() {
    super.onStart();

}


@Override
protected void onPause() {
    super.onPause();

    if(binder!=null) {
        binder.getMyService().pauseMusic();
    }


}



@Override
protected void onResume() {
    super.onResume();
    if(binder!=null){
        binder.getMyService().resumeMusic();
    }
}




@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    binder = (MusicService.Binder) service;

}

@Override
public void onServiceDisconnected(ComponentName name) {

}

this is my mainactivity extends base activity

@Override
protected void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startIntent = new Intent(MainActivity.this, MusicService.class);
    startService(startIntent);


}


@Override
protected void onDestroy() {
    super.onDestroy();

}

public void how(View view) {
        Intent intent = new Intent(this, AboutActivity.class);
        this.startActivity(intent);



    }

Solution

  • You could implement code that will track current activity in your app. (Good example: How to get current activity)

    And stop music only when "current activity" is null.

    PS: depending on your implementation of tracking current activity you might want to check current activity not onPause() right away but with some delay .