1

I am making an app where bgm start from main page. But I couldn't find a way to turn it off when starts learning.

Can I remotely switch off bgm from different java file

This is my 1st java,mainmenu.class

public class mainmenu extends AppCompatActivity {
MediaPlayer bkgrdmsc;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mainmenu);
    Button btn = (Button) findViewById(R.id.mula);
    assert btn != null;
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent ke_belajar_latihan = new Intent(getApplicationContext(), taqi.mengaji.belajar_latihan.class);
            startActivity(ke_belajar_latihan);

        }
    });

    bkgrdmsc = MediaPlayer.create(this, R.raw.song);
    bkgrdmsc.setLooping(true);
    bkgrdmsc.start();


}


}

This is the other file I want to remotely off the bgm when starting the learning session(as student start to learn)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.belajar_hija_baris);

    Button btn=(Button) findViewById(R.id.hijaiyyah);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent ke_hijaiyah=new Intent(getApplicationContext(),taqi.mengaji.hijaiyyah.class);
            startActivity(ke_hijaiyah);
        }
    });

}

I want R.id.hijaiyyah to navigate to learn xml also stop bgm

Please help I'm a newbie XD

Bhugy
  • 711
  • 2
  • 8
  • 23
T-dean
  • 11
  • 6

1 Answers1

1

Make an singleton class and add you music playing code into it for stopping and starting and use that singleton class in all your 2 activities for eg:

public class MusicManager {

    private static MusicManager refrence = null;

    public static MusicManager getInstance(){
        if(refrence == null){
            refrence = new MusicManager ();
        }
        return refrence;
    }

}

Add a public method to this singleton class to start and stop music

public void initalizeMediaPlayer(Context context, int musicId){

// add initalization of media player in it and loop it 
MediaPlayer bkgrdmsc;
bkgrdmsc = MediaPlayer.create(this, R.raw.song);
bkgrdmsc.setLooping(true);
}

public void startPlaying(){
bkgrdmsc.start();
}

public void stopPlaying(){
bkgrdmsc.stop();
}

//Add stuff like pausing and resuming if you desire

To use this class add this to any activity you want to play music:

    MusicManager.getInstance().initalizeMediaPlayer(this, R.raw.menu); // to initalize of media player
    MusicManager.getInstance().startPlaying();// to start playing music
    MusicManager.getInstance().stopPlaying(); // to stop playing music

You can also use service to perform this task as service runs in background. You can start and stop service any time in your code.

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40