I want to use intent for my homework application. When i click button1, my SoundActivity opening, after playing sound1.mp3 file. But i wanna when i clicked button2, sound2.mp3 file playing in SoundActivity..
This is my MainActivity.java codes:
button1=findViewById(R.id.button1);
button2=findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(this, SoundActivity.class);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(this, SoundActivity.class);
}
});
This is my Sound Activity side:
sound1 = MediaPlayer.create(this, R.raw.bell);
sound2 = MediaPlayer.create(this, R.raw.siren);
sound1.start();
'Another way is that you just pass a key like which song you want to play on button click listener like'
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(this, SoundActivity.class);
intent.putExtra("SOUND", "sound1");
startActivity(intent);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(this, SoundActivity.class);
intent.putExtra("SOUND", "sound2");
startActivity(intent);
}
});
'get this key in sound activity and pass the sound on the basis of condition like'
Bundle bundle = getIntent().getExtras();
String sound = bundle.getInt("SOUND");
if(sound.equals(sound1)){
play_sound = MediaPlayer.create(this, R.raw.bell);
}else if(sound.equals(sound2)){
play_sound = MediaPlayer.create(this, R.raw.siren);
}
play_sound.start();
'Hope you get the best'