Music keeps running - android

I have a sound on my app and when I play it and then press the home button, the app keeps running at the background ( I know it because the song keeps going.. ) How can I stop the app and the music?
here's my music code:
SoundPool sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
int iTmp = sp.load(getBaseContext(), R.raw.windows_8_notify, 1);
sp.play(iTmp, 1, 1, 0, 0, 1);
MediaPlayer mPlayer = MediaPlayer.create(getBaseContext(), R.raw.windows_8_notify);
mPlayer.start();
mPlayer.setLooping(true);
Button btn_show = (Button) findViewById(R.id.show_popup);
btn_show.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (p != null)
showPopup(FirstActivity.this, p);
} }); }

In your Main Activity just override the onPause method, if you want to restart the music when you re-enter the app, the logic should go into your onResume method.
http://developer.android.com/reference/android/app/Activity.html for more info on the activity class that you must extend to create your android app.
class myActivity extends Activity {
#Override
public onCreate(Bundle savedInstanceState) {
// setup your app here
}
#Override
protected void onPause() {
// stop or pause your music here
// other "clean up"
}
#Override
protected void onResume() {
// app is now to the forground set things back up that might have been removed in onPause
}
}

stop the player inside the onStop activity callback method
#Override
protected void onStop() {
super.onStop();
if(mPlayer!=null && mPlayer.isPlaying())
mPlayer.stop();
}

Related

Cant find a spot to properly release MediaPlayer

i know there are tons of questions about MediaPlayer releasing, but i searched for hours and hours and everything contradicts each other.
Simple sitation: I create a MediaPlayer instance in onCreate. I have a play and a pause button. Where to release the MediaPlayer?
onPause/onStop causes a crash on resume, because onCreate wont always be called.
onDestroy seems not reliable because it wont always be called.
So where is the place to release a MediaPlayer that was create in onCreate?
public class MainActivity extends AppCompatActivity {
private MediaPlayer sound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sound = MediaPlayer.create(this, R.raw.song);
Log.d("Media", "onCreate: MediaPlayer created");
Button buttonPlay = findViewById(R.id.button_play);
buttonPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sound.start();
}
});
Button buttonPause = findViewById(R.id.button_pause);
buttonPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sound.pause();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
sound.release();
sound = null;
Log.d("Media", "onDestroy: MediaPlayer released");
}
}
onDestroy seems not reliable because it wont always be called
Either:
onDestroy() will be called, or
Your process was terminated, in which case the MediaPlayer goes away when your process does
You had an unhandled exception, in which case you have bigger problems, or
So where is the place to release a MediaPlayer that was create in onCreate?
onDestroy().

How to set Android background music playing only one time

I am creating a game, I want to play a background music for one activity only(For main menu of game), my code shown below, The problem is that the music plays more than one time, I want to play the same music also when activity Resumes.
public class Menu extends Activity {
MediaPlayer mp
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
mp = MediaPlayer.create(Menu.this, R.raw.adalante);
if(!mp.isPlaying()) {
mp.start();
}
public void play(View ButtonClicked) {
mp.stop();
mp.release();
//mp = MediaPlayer.create(Menu.this, R.raw.l);
//mp.start();
goToActivity(Game.class);
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
//coins
coin.setText(data.getString("coin"));
mp = MediaPlayer.create(Menu.this, R.raw.adalante);
if(!mp.isPlaying()) {
mp.start();
}
//mps.release();
}
In your onResume don't initialise MediaPlayer again and again. It creates new instance every time when you come to onResume. So add a check in onResume like this :
#Override
protected void onResume() {
super.onResume();
if (mp==null)
mp=MediaPlayer.create(MainActivity.this,R.raw.adalante);
if (!mp.isPlaying())
mp.start();
}
and additionally add this for prevention to play when activity goes to onPause
#Override
protected void onPause() {
super.onPause();
mp.pause();
}

How to play music again when returing to main activity

What I would like to achieve is to stop the music when I go to my 2nd activity from my main activity (this works and the music does stop) But when I press the back button to go back to the main activity the music doesn't seem to start again. How can I make it to start again or if possible pause to music when going to the 2nd activity and resume when going back to the main activity.
Here is my code where the music stops when going to the next activity but doesn't play when going back to the main activity:
public class MainActivity extends Activity implements OnClickListener{
public static MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.music_a);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setLooping(true);
player.start();
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
player.stop();
}
});
}
protected void onPause() {
if (this.isFinishing()){
player.stop();
Toast.makeText(MainActivity.this, "BYE", Toast.LENGTH_LONG).show();
}
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
player.stop();
}
else {
}
}
super.onPause();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And here is my 2nd activity (do I need to put something here as well?)
public class SecondActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
}
}
Thanks
You have to call onResume on your First Activity to continue playing music
#Override
protected void onPause() {
super.onPause();
// stop the music
}
#Override
protected void onResume() {
super.onResume();
// play the music here
}
just remove your code to play from oncreate and start playing song in onResume
try {
if (player != null) {
player.start();
} else {
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.meintenu);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setLooping(true);
player.start();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
edit:
write this in your button click
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
player.stop();
player.release();
player=null;
pause Your music when you go to next activity and get the current position of the music
homeMusic.pause();
position=homeMusic.getCurrentPosition();
then add onRestart method,
#Override
protected void onRestart() {
super.onRestart();
homeMusic.seekTo(position);
homeMusic.start();
homeMusic.setLooping(true);
}

How to stop audio from playing when back button is pressed?

Hi all here is my code:
final ImageView imageView = (ImageView) findViewById(R.id.Image7);
imageView.setImageResource(mFullSizeIds[position]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(Audio.this,mAudio[position]);
mp.start();
}
});
Now this code works fine to play the audio when the user taps the image, however when I want to exit this activity and go to a different activity, the audio track is still playing, even when I press the home key the audio is still playing. How can I prevent this from happening?
Is there a way to stop the track from playing when the user taps the image again or presses the back/home button?
Add
#Override
public void onBackPressed ()
{
if (mp != null)
mp.stop();
super.onBackPressed();
}
and
#Override
public void onPause ()
{
if (mp != null)
{
mp.pause();
mp.stop();
}
super.onPause();
}
Create an onStop in the activity and make mp a class variable although I always create/prefer media player helper class for this sort of stuff. Then call mp.stop()/pause on onStop.
private MediaPlayer mp = null;
#Override
public void onStop() {
super.onStop();
if (mp != null) {
mp.stop();
}
}
then you just create it with removing the MediaPlayer before mp:
mp = MediaPlayer.create(Audio.this,mAudio[position]);
Override the onBackPressed method, and stop your MediaPlayer object, which is mp.

Access control of Activity in Service Android

I am new to android. i know that we can not access control of activity from service. But i want to change the ImageSource of the button whenever i call the method of the service.
here is the method that i created in service :
public void play()
{
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play); // not allowed
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause); // not allowed
}
}
}
in activity i am calling this method on play button click. How to implement this functionality in service. how can i change the image source of the button. Please clear my doubt. Thanx.
Create custom event object for those events and register your activity as listener.
Note: Don't forget to unregister it because it might cause a memory leak.
Try this code
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
public static MainActivity mThis;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mThis = this;
}
}
public void play()
{
Button btnPlay=((Button)MainActivity.mThis.findViewById(R.id.btnPlay));
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
}
}

Categories

Resources