I'm making a quiz app in which there is a sound game.But i find that sound keeps playing even when app is closed. Two time I'm using mediaplayer.
1.while clicking on image button.
2.on changing question.
Question is changed every 15 sec and after killing app sound is getting played every 15 seconds.
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
#Override
protected void onResume()
{
super.onResume();
questionPlay = db.getMorseQuestionMode(mode);
totalQuestion = questionPlay.size();
mCountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestion) {
thisQuestion++;
txtQuestion.setText(String.format("%d/%d", thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
int QusId = this.getResources().getIdentifier(questionPlay.get(index).getQus().toString(), "raw", getPackageName());
btnA.setText(questionPlay.get(index).getAnswerA());
btnB.setText(questionPlay.get(index).getAnswerB());
btnC.setText(questionPlay.get(index).getAnswerC());
btnD.setText(questionPlay.get(index).getAnswerD());
mCountDown.start();
mediaPlayer= MediaPlayer.create(this,QusId);
mediaPlayer.start();
} else {
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
mCountDown.cancel();
if (index < totalQuestion) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(questionPlay.get(index).getCorrectAnswer())) {
score += 10; // increase score
correctAnswer++; //increase correct answer
showQuestion(++index);
} else {
vibrator.vibrate(50);
showQuestion(++index); // If choose right , just go to next question
}
txtScore.setText(String.format("%d", score));
}
}
//CLicking back Button
public void onBackPressed() {
showExitAlertBox();
}
public void showExitAlertBox() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("You want to quit the play?");
//Yes Quit then go to category page
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int button) {
Intent intent = new Intent(getApplicationContext(), CategorySecond.class);
startActivity(intent);
}
});
//no Quit stay on same page
alertDialog.setNegativeButton("NO", null);
alertDialog.show();
mediaPlayer.stop();
}
}
Error Showing us below
W/MediaPlayer-JNI: MediaPlayer finalized without being released
Cancel your timer and stop mediaplayer if playing in onStop
#Override
public void onStop() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
if(mCountDown != null)
mCountDown.cancel();
super.onStop();
}
handle on destroy
#Override
public void onDestroy() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
if(mCountDown != null)
mCountDown.cancel();
}
You have not released the mediaplayer properly.
Use
protected void onStop(){
mediaPlayer.release();
mediaPlayer = null;
}
call this method where ever required.
Related
my code is given below in that for Each Question there is i.e. when count down ends its jump to next question and count down starts again, i want that when the countdown ends it should jump to the result page..and even after jumping to next question countdown should not stop.
#Override
protected void onResume()
{
super.onResume();
questionPlay = db.getRuleQuestionMode(mode);
totalQuestion = questionPlay.size();
mCountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
}
};
showQuestion(index);
db.close();
}
private void showQuestion(final int index) {
if (index < totalQuestion) {
thisQuestion++;
txtQuestion.setText(String.format("%d/%d", thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
txtView1.setText(questionPlay.get(index).getQus());
btnA.setText(questionPlay.get(index).getAnswerA());
btnB.setText(questionPlay.get(index).getAnswerB());
btnC.setText(questionPlay.get(index).getAnswerC());
btnD.setText(questionPlay.get(index).getAnswerD());
mCountDown.start();
Button btnca =(Button) findViewById(R.id.btnca);
btnca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StyleableToast st= new StyleableToast(getApplicationContext(),questionPlay.get(index).getCorrectAnswer(), Toast.LENGTH_SHORT);
st.setBackgroundColor(Color.RED);
st.setTextColor(Color.WHITE);
st.setCornerRadius(3);
st.show();
score-=10;
}
});
} else {
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
mCountDown.cancel();
if (index < totalQuestion) {
Button clickedButton = (Button) v;
if (clickedButton.getText().equals(questionPlay.get(index).getCorrectAnswer())) {
score += 10; // increase score
correctAnswer++; //increase correct answer
showQuestion(++index);
} else {
vibrator.vibrate(50);
showQuestion(++index); // If choose right , just go to next question
}
txtScore.setText(String.format("%d", score));
//clickedButton.setBackgroundColor(Color.YELLOW);;
}
}
#Override
public void onStop() {
if(mCountDown != null)
mCountDown.cancel();
super.onStop();
}
remove mCountDown.start(); in your showQuestion method.
in your onFinish method, call your results page from there
This is part of the code in my MainActivity.
stopwatch1 is an image button called in MainActivity:
stopwatch1 = (ImageButton)findViewById(R.id.stopwatch1);
I have tried searching for clues on how to use dialog.setOnDismissListener, however, there aren't proper answers to help me with the killing of the audio after deliberate or accidental exit of the dialog. Any help would be appreciated.
stopwatch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog mmDialog1 = new Dialog(context);
mmDialog1.setContentView(R.layout.countdowntimer);
mmDialog1.setTitle("Stop-watch");
Button ddButton1 = (Button) mmDialog1.findViewById(R.id.countdown_exit);
final Button ddButton2 = (Button) mmDialog1.findViewById(R.id.countdown_start);
final TextView timeview = (TextView) mmDialog1.findViewById(R.id.timeview);
ddButton2.setTag(1);
ddButton2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final int status = (Integer) v.getTag();
if (status == 1) {
ddButton2.setText("Stop");
countDownTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
int time = (int) (millisUntilFinished/1000);
timeview.setText(Integer.toString(time));
}
#Override
public void onFinish() {
timeview.setText("60");
ddButton2.setText("Start");
MediaPlayer stop = MediaPlayer.create(context, R.raw.stop);
stop.start();
}
}.start();
v.setTag(0);
} else {
ddButton2.setText("Start");
timeview.setText("60");
countDownTimer.cancel();
v.setTag(1);
}
}
});
ddButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mmDialog1.dismiss();
}
});
mmDialog1.show();
}
});
My suggestion would be to implement an interface. When the dialog closes, have the callback shut off the media player.
A quick example is this.
interface
public interface DialogClosed {
void shutDownMediaPlayer();
}
then implement the interface in the calling activity
activity
public class MainActivity extends Activity implements DialogClosed {
....
#Override
public void shutDownMediaPlayer() {
//shut down media player here
}
}
Also, you may add a boolean to check if the dialog is showing like this
boolean isShowing = mDialog.isShowing();
and then you can just shut off the media player at any point if this is false.
So I've used some pointers from Jawascript and also edited my code a little, now it works:
stopwatch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog mmDialog1 = new Dialog(context);
mmDialog1.setContentView(R.layout.countdowntimer);
mmDialog1.setTitle("Stop-watch");
Button ddButton1 = (Button) mmDialog1.findViewById(R.id.countdown_exit);
final Button ddButton2 = (Button) mmDialog1.findViewById(R.id.countdown_start);
final TextView timeview = (TextView) mmDialog1.findViewById(R.id.timeview);
final MediaPlayer stop = MediaPlayer.create(context, R.raw.stop);
ddButton2.setTag(1);
mmDialog1.setCancelable(false);
if (mmDialog1.isShowing() == false) {
stop.stop();
}
ddButton2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
final int status = (Integer) v.getTag();
if (status == 1) {
ddButton2.setText("Stop");
countDownTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
int time = (int) (millisUntilFinished/1000);
timeview.setText(Integer.toString(time));
}
#Override
public void onFinish() {
timeview.setText("60");
ddButton2.setText("Start");
try {
stop.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
stop.start();
}
}.start();
v.setTag(0);
} else {
ddButton2.setText("Start");
timeview.setText("60");
countDownTimer.cancel();
v.setTag(1);
stop.stop();
}
}
});
ddButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mmDialog1.dismiss();
}
});
mmDialog1.show();
}
});
I need a button that will start when pressed and stop when pressed again. Otherwise I have overlapping sounds. Can any of you assist me with the code please? Below is what I currently have and can't get the button to stop when clicked again so currently it is just playing and stops when the sound is done causing sounds to overlap. Getting one to stop when another is pressed would also be ideal but I don't have a clue how to easily incorporate this.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boardone);
Button one = (Button) findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(BoardoneActivity.this, R.raw.mouse_laughter);
mp.start();
}
});
Button two = (Button) findViewById(R.id.button2);
two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(BoardoneActivity.this, R.raw.evil_laugh);
mp.start();
}
});
Dont use two objects of Media Player. Bleow is the snippet of methods from my project. If any error let me know.
private MediaPlayerManager mRecordingPlayer = null;
private void initAudioPlayer(){
if(mRecordingPlayer == null){
mRecordingPlayer = new MediaPlayerManager();
}
}
private void playMusic(int position){
initAudioPlayer();
mRecordingPlayer.resetPlayer();
mRecordingPlayer.setupPlayback("your reasource");
mRecordingPlayer.startPlaying();
}
private void stopPlaying(){
initAudioPlayer();
if(mRecordingPlayer.isPlaying()){
mRecordingPlayer.pausePlaying();
}
}
#Override
public void onPause() {
clearAudioPlayer();
super.onPause();
}
private void clearAudioPlayer(){
if(mRecordingPlayer != null ){
mRecordingPlayer.resetPlayer();
}
}
#Override
public void onClick(View view) {
boolean on = ((ToggleButton) view).isChecked();
if(on){
playMusic("play music");
((ToggleButton) view).setChecked(true);
}else{
stopPlaying();
}
}
Try it with below code.
mPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
mPlayPause.setText("Play");
}
} else {
if (mp != null) {
mp.start();
mPlayPause.setText("Pause");
}
}
}
});
I have two buttons in my media player that streams a radio station, play and pause. I want to make it only one button that has two function. First click I want to play it and second click I want to pause it. And when I click it again I want to play it. I need help. Here is my code.
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
play.performClick();
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pause();
}
});
}
private void play() {
Uri myUri = Uri.parse("Shoutcast URL");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
Create just one Button and add something like a buttonstatus. Then you can check the status in your listener.
For example:
boolean isPlaying = false;
playPause = (Button) findViewById(R.id.play);
playPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (isPlaying) {
pause();
}else{
play();
}
isPlaying = !isPlaying;
}
});
Boolean b = false;
Button play = (Button) findViewById(R.id.play);
play..setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if(b == false)
{
//write play code here
b= true;
}
else
{
// enter pause code here
}
}
}
You can use Toggle button:
toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (toggleButton.isChecked()) {
play();
} else {
pause();
}
}
});
You can also remove the green bar from toggle button.
Toggle button Mkyong example
Android dev tutorial
You don't need to declare any boolean variable to check player state. There is a method already available in mediaplayer class named - isPlaying().
Try my code sequence for playpause using single button.
public void playpause(){
if(!mp.isPlaying()){ // here mp is object of MediaPlayer class
mp.start();
//showNotification("Player State Plying");
}
else if(mp.isPlaying()){
mp.pause();
//showNotification("Player State Pause");
}
}
I made an activity that has an audio as a background music. When i add a skip button to move to another activity the background music of my first activity was continuously playing. Here's my code, kindly check and post what should i add to my code. Thanks in advance!
public class pgone extends Activity {
protected boolean _active = true;
protected int _splashTime = 7000;
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
MediaPlayer audio;
MediaPlayer SLONE;
private long splashDelay = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pgone);
TimerTask task = new TimerTask()
{
public void run() {
Intent mainIntent = new Intent().setClass(pgone.this, pgtwo.class);
startActivity(mainIntent);
finish();
}
};
final Timer timer = new Timer();
timer.schedule(task, splashDelay);
audio = MediaPlayer.create(this,R.raw.storyaud);
audio.start();
SLONE = MediaPlayer.create(this,R.raw.sl1);
SLONE.start();
final MediaPlayer mp = MediaPlayer.create(this, R.raw.buttonbeep);
final Vibrator mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
Button skipButton = (Button)findViewById(R.id.skip);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent skipIntent = new Intent(pgone.this,choose.class);
startActivity(skipIntent);
mp.start();
mVibrator.vibrate(500);
finish();
timer.cancel();
timer.purge();
}
});
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to exit the game?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
}
You should stop the audio before moving to the next Activity. Try replacing mp.start() by mp.stop() here,
Button skipButton = (Button)findViewById(R.id.skip);
skipButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent skipIntent = new Intent(pgone.this,choose.class);
startActivity(skipIntent);
mp.stop();
mVibrator.vibrate(500);
finish();
timer.cancel();
timer.purge();
}
});
Please Write mp.stop() mp.reset() instead of mp.start() on click event of skip button, and see below link for more information.
Media Player example of Playing Sounds
Simple Android Mp3 Media Player
The easiest and most efficient way -
#Override
protected void onPause() {
super.onPause();
yoursMusicPlayerObject.release();
}
Exploit Activity life cycle's onPause phase when you jump to next activity .Just release the I/O resources under use which is yours MediaPlayer object here .