Reputation: 21
Hi I am making app when I am using Media player function. And when for example I close app this media still working in background. How to stop whole tasks in app?
final Random rand = ThreadLocalRandom.current();
tv3.setText(kombosy[new Random().nextInt(kombosy.length)]);
int resourceID=R.raw.rin1;
switch (tv3.getText().toString()) {
case "1-2":
resourceID = R.raw.rin1;
break;
case "1-1-2":
resourceID = R.raw.rin2;
break;
case "1-2-3-2":
resourceID = R.raw.rin3;
break;
case "1-2-5-2":
resourceID = R.raw.rin4;
break;
case "1-6-3-2":
resourceID = R.raw.rin5;
break;
case "2-3-2":
resourceID = R.raw.rin6;
break;
}
plyer=MediaPlayer.create(this,resourceID);
plyer.start();
}
Upvotes: 1
Views: 59
Reputation: 2905
Create media player instance globally
MediaPlayer player;
Your switch case should look like this
You can get your ringtone resource ID in switch-case statement, then create a single media player object.
int resourceID = R.raw.rin1;
switch (tv3.getText().toString()) {
case "1-2":
resourceID = R.raw.rin1;
break;
case "1-1-2":
resourceID = R.raw.rin2;
break;
case "1-2-3-2":
resourceID = R.raw.rin3;
break;
case "1-2-5-2":
resourceID = R.raw.rin4;
break;
case "1-6-3-2":
resourceID = R.raw.rin5;
break;
case "2-3-2":
resourceID = R.raw.rin6;
break;
}
Create a MediaPlayer
instance just like this
player = MediaPlayer.create(this, resourceID);
player.start();
To stop your media player call this method :
private void stopPlaying() {
if (player != null) {
player.stop();
player.release();
player = null;
}
}
Upvotes: 1