Saving music state - android

I am having an issue with the music playback of my app. I set up the media player within a Service class which plays music throughout the application fine. However, the issue I'm having is when changing screens from the Options page to the Home page again.
In the option class, I have a single ToggleButton which turns the music on and off when it's clicked, and I have used a boolean to determine whether the ToggleButton is auto on and off, depending on whether the music is playing.
However, when the user clicks the back button or the save button (which both send them back to the home page) the music starts playing again, even if it's checked as "off".
Does anyone have a suggestion for me?
Service Class:
public class MyMusicService extends Service {
MediaPlayer mp;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mp = MediaPlayer.create(this, R.raw.song);
mp.start();
mp.setLooping(true);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
if(mp!=null) {
mp.stop();
mp.release();
}
mp=null;
}
}
Options Class:
public class OptionsActivity extends Activity {
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK ) {
Intent i = new Intent(OptionsActivity.this, MainActivity.class);
startActivity(i);
return true;
}
return super.onKeyDown(keyCode, event);
}
private boolean isMyServiceRunning(String serviceCanonicalClassName) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceCanonicalClassName.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
Intent i; // Handles MyMusicService.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
final TextView tSound = (TextView) findViewById(R.id.textView2);
final Button saveBtn = (Button) findViewById(R.id.optSaveBtn);
final Button tblBtn = (Button) findViewById(R.id.tableBtn);
i=new Intent(this, MyMusicService.class);
final ToggleButton soundOption = (ToggleButton) findViewById(R.id.soundPref);
boolean musicPlays = isMyServiceRunning(MyMusicService.class.getCanonicalName());
soundOption.setChecked(musicPlays);
if(musicPlays==true){
tSound.setText("On");
}
if(musicPlays==false) {
tSound.setText("Off");
}
soundOption.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on clicks to control sound being on and off.
if(soundOption.isChecked()) {
Toast.makeText(OptionsActivity.this, "Music on.", Toast.LENGTH_SHORT).show();
startService(i);
Intent i = new Intent(OptionsActivity.this, OptionsActivity.class);
startActivity(i);
}
else {
if(stopService(i)==true){
soundOption.setChecked(false);
stopService(i);
Toast.makeText(OptionsActivity.this, "Music off.", Toast.LENGTH_SHORT).show();
Intent i = new Intent(OptionsActivity.this, OptionsActivity.class);
startActivity(i);
}
}
}
});
tblBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent tblView = new Intent(OptionsActivity.this, SQLView.class);
startActivity(tblView);
}
});
saveBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent homePage = new Intent(OptionsActivity.this, MainActivity.class);
switch (v.getId()){
case R.id.optSaveBtn: //Determine what will happen when the user presses the "Submit button".
boolean optionsWork = true;
try{
String sound = tSound.getText().toString();
optionsDB entry = new optionsDB(OptionsActivity.this); //Creating a new instance of MasterMind game
entry.open();
entry.createOptionEntry(sound); //Passing both strings
entry.close();
}catch (Exception e){ //Creating an error message if for some reason the app cannot transfer data to the Database.
Toast.makeText(OptionsActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
finally { //Creating an AlertDialog box when the user presses the Submit button.
if (optionsWork){
Toast.makeText(OptionsActivity.this, "Settings Saved", Toast.LENGTH_SHORT).show();
}
}
break;
}
startActivity(homePage);
}
});
}
}
And finally, the home class:
public class MainActivity extends Activity {
Intent i;
private boolean isMyServiceRunning(String serviceCanonicalClassName) {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceCanonicalClassName.equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public void checkSound(){
boolean musicPlays = isMyServiceRunning(MyMusicService.class.getCanonicalName());
if(musicPlays==true){
//Do nothing
}
else {
stopService(i);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setting the layout
//Start Networking
//Intent net = new Intent(this, Networking.class);
//startService(net);
//Auto starts playing music on app launch.
i = new Intent(this,MyMusicService.class);
startService(i);
checkSound();
final ImageView findGame = (ImageView) findViewById(R.id.btnFindGame);
final ImageView profile = (ImageView) findViewById(R.id.btnProfile);
final ImageView instructions = (ImageView) findViewById(R.id.btnInstructions);
final ImageView options = (ImageView) findViewById(R.id.btnOptions);
findGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, DrawActivity.class);
startActivity(intent);
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, WaitingActivity.class);
startActivity(intent);
}
});
instructions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, InstructionsActivity.class);
startActivity(intent);
}
});
options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, OptionsActivity.class);
startActivity(intent);
}
});
}
//On app close, music stops playing.
#Override
protected void onDestroy() {
if (this.isFinishing()){
super.onDestroy();
stopService(i);
//finish();
}
}
}

When you're creating the home screen, you are also starting the service again. In your 'onStartCommand' of the service you are starting the media player. That means that every time you go to the homepage, the media player will start playing again.
I would recommend not putting mp.start(); in the 'onStartCommand' but instead in its own function. Then after you call startService(i); you can bind to the the service using bindService() then call a function such as play() on the service handle you have.
Of course if you are pausing the song instead of stopping you will need to save the position of the songs and then use seekTo() to move the song to the proper position when you restart the service.
I'd recommend reading through the Android service page here and here

i think u have to place some check on start service in your home class on create method,
check if(your service is running)
{
if(mp is playing)
{
//do nothing
}
}
else
{
startservice();
}

Related

Sound keeps on playing even when app is killed

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.

When resuming music player then music resumes but not the play and pause button states

Below is the code which I use.By this code the background music plays on all activities.But when I come back to this activity using home button then music plays normally but the drawables will not resumed. That Mean if music is played and I went back to that activity via home button then play button is shown rather than the pause button but I want that if music played on resume then button is pause and if not then show play button.
Can you tell what to do with play and pause buttons on resuming activties?
public class RadioActivity extends ActionBarActivity implements RadioListener{
private final String[] RADIO_URL = {"url "};
private ActionMenuView amvMenu;
ImageButton mButtonControlStart;
TextView mTextViewControl;
RadioManager mRadioManager = RadioManager.with(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
mButtonControlStart = (ImageButton) findViewById(R.id.buttonControlStart);
mRadioManager.registerListener(this);
mRadioManager.setLogging(true);
initializeUI();
mButtonControlStart.setBackgroundResource(R.drawable.play);
Toolbar toolbarBottom = (Toolbar) findViewById(R.id.toolbar);
toolbarBottom.setTitle("Radio");
amvMenu = (ActionMenuView) toolbarBottom.findViewById(R.id.amvMenu);
amvMenu.setOnMenuItemClickListener(new ActionMenuView.OnMenuItemClickListener() {
// toolbarBottom.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
switch(item.getItemId()){
case R.id.activity_aboutus:
// TODO
Intent intent=new Intent(RadioActivity.this,Contact_us.class);
startActivity(intent);
break;
// TODO: Other cases
case R.id.menu_refresh:
// TODO
Intent intent1=new Intent(RadioActivity.this,Web.class);
startActivity(intent1);
break;
case R.id.menu_about:
Intent intent2=new Intent(RadioActivity.this,Song_rqst.class);
startActivity(intent2);
break;
case R.id.menu_item_share:
Intent intent3=new Intent(RadioActivity.this,Ratee.class);
startActivity(intent3);
break;
}
return true;
}
});
}
public void initializeUI() {
mButtonControlStart = (ImageButton) findViewById(R.id.buttonControlStart);
mTextViewControl = (TextView) findViewById(R.id.textviewControl);
mButtonControlStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mRadioManager.isPlaying()) {
mRadioManager.startRadio(RADIO_URL[0]);
mButtonControlStart.setBackgroundResource(R.drawable.end);
}
else {
mRadioManager.stopRadio();
mButtonControlStart.setBackgroundResource(R.drawable.play);
}
}
});
}
#Override
protected void onResume() {
super.onResume();
mRadioManager.connect();
}
#Override
protected void onDestroy() {
super.onDestroy();
mRadioManager.disconnect();
}
#Override
public void onRadioLoading() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//TODO Do UI works here.
mTextViewControl.setText("RADIO STATE : LOADING...");
}
});
}
#Override
public void onRadioConnected() {
}
#Override
public void onRadioStarted() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//TODO Do UI works here.
mTextViewControl.setText("RADIO STATE : PLAYING...");
}
});
}
#Override
public void onRadioStopped() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//TODO Do UI works here
mTextViewControl.setText("RADIO STATE : STOPPED.");
}
});
}
#Override
public void onMetaDataReceived(String s, String s1) {
//TODO Check metadata values. Singer name, song name or whatever you have.
}
#Override
public void onError() {
}
Whenever you come back to your Music Play Activity Oncreate() is not called so your drawable resource load on Onpause() or Onstart(), Everytime Oncreate() is not calling.

Service and background music codes -updated-

i am making a quiz game that has a background music.i saw a very helpful source code using service and background music here http://marakana.com/forums/android/examples/60.html but my problem is i want to add another sound on my EasyOne.class in my correct answer button. what will i add or edit to make it work. my point is. everytime i click the a button of my easyone.class it will play a sound and if i want to turn off all my music even the corrrect button and the background music it will turn off if ill go to my settings.class and click the OFF button. hope you can help me.really appriciate it.
here is my code for my service
public class MusicService extends Service {
private static final String TAG = "";
MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "ON", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.bsound);
player.setLooping(false);
}
#Override
public void onDestroy() {
Toast.makeText(this, "OFF", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "ON", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
and here is my for my settings
public class Settings extends Activity implements OnClickListener {
private static final String TAG = "";
Button on, off, back;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
back = (Button) findViewById(R.id.btn_backk);
on = (Button) findViewById(R.id.btn_on);
off = (Button) findViewById(R.id.btn_off);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Back",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainMenu.class);
startActivity(intent);
}
});
on.setOnClickListener(this);
off.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.btn_on:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MusicService.class));
break;
case R.id.btn_off:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MusicService.class));
break;
}
}
}
my EasyOne.class - (class of my level 1 easy mode)
public class EasyOne extends Activity {
ImageButton a, b, c;
Intent intent ;
CountDownTimer cdt;
TextView timer;
MediaPlayer clap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easyone);
a = (ImageButton) findViewById(R.id.ib_a);
b = (ImageButton) findViewById(R.id.ib_b);
c = (ImageButton) findViewById(R.id.ib_c);
timer = (TextView) findViewById(R.id.tv_timer);
cdt = new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
timer.setText("seconds remaining: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timer.setText("TIMES UP!");
intent = new Intent(getApplicationContext(),TimesUp.class);
startActivity(intent);
}
};
intent = new Intent(getApplicationContext(),ChoiceTwo.class);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
//i want to add a sound here that will play if they click this button and can turn it OFF on the setting.class OFF button
cdt.cancel();
Intent intent = new Intent(getApplicationContext(),ChoiceTwo.class);
startActivity(intent);
}
});
cdt.start();
}
}
In the main activity of your code (where the game actually starts), put:
startService(new Intent(MusicService.class))
This will start your music playing as soon as the game starts

how to add soundeffects when clicking a button

I'm having a bit of a trouble,, here's the gen. idea,, I have created an app a simple game-like application.. however the problem is when I try to click the button in the title screen it doesn't play the click sound.. can anyone please help me.. here's the code for my sound
public class Effects extends Activity implements MediaPlayer.OnCompletionListener {
Button mPlay;
MediaPlayer mPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPlay = (Button)findViewById(R.id.btnStart);
mPlay.setOnClickListener(playListener);
setContentView(R.layout.activity_main);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mPlayer != null) {
mPlayer.release();
}
}
private View.OnClickListener playListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mPlayer == null) {
try {
mPlayer = MediaPlayer.create(Effects.this, R.raw.button11);
mPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
} else {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
};
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
}
and here's my code for the main java that I want the sound to be played when I clicked this button
public class Main extends Activity implements OnClickListener
{
Button about;
Button Quit;
Button start;
protected void onCreate(Bundle onSavedInstanceState) {
super.onCreate(onSavedInstanceState);
setContentView(R.layout.activity_main);
about = (Button)findViewById(R.id.btnAbout);
about.setOnClickListener(this);
Quit = (Button)findViewById(R.id.btnQuit);
Quit.setOnClickListener(this);
start = (Button)findViewById(R.id.btnStart);
start.setOnClickListener(this);
}
public void onClick(View argo)
{
if(argo.getId()==R.id.btnAbout)
{
Intent i = new Intent(this,About.class);
this.startActivity(i);
}
if(argo.getId()==R.id.btnQuit)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
if(argo.getId()==R.id.btnStart)
{
Intent start = new Intent(this,Howto.class);
this.startActivity(start);
Intent svc=new Intent(this,Effects.class);
startService(svc);
}
}
}
Use SoundPool to play your sounds: http://developer.android.com/reference/android/media/SoundPool.html you should init sounds in your onCreate() and then play them back in onClick()
And instead of doing thousands of pointless if(argo.getId()==R.id.btnQuit) (you should at least use else) get familiar with switch/case syntax)

audio continuously playing even it moves to the next activity

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 .

Categories

Resources