0

I am creating an android application where I'm playing a music file from my phone. I am implementing this using services. So there is a problem in my service. When I start the service the music from my app starts playing. When I press Home Key and Went to YouTube application and played any video, The service is still running in the background paying the music file. How can I stop my service from playing the music file, when some other music file is started. Thanks in advance.

Vaibs
  • 1,128
  • 3
  • 16
  • 36

4 Answers4

0

Poll the list of running services on start of a new activity and, if it requires use of the speaker, pause yours and let it finish?

Community
  • 1
  • 1
hd1
  • 33,938
  • 5
  • 80
  • 91
0

Before starting a new service, stop the running service.
When stopping the running service, make sure you stop the player too.

Lazy Ninja
  • 22,342
  • 9
  • 83
  • 103
0

When the Activity or Service is starting, check whether the music is playing or not. If playing, stop it else return null as below:

I think u have the below lines in your onCreate Method of your Activity:

MediaPlayer mp= MediaPlayer.create(this, R.raw.<Your Music File>);
mp.setLooping(true);

Add the below lines of code in onPause, onStop methods in your Activity:

if(mp.isPlaying())
    mp.stop();
else
    return;
Avadhani Y
  • 7,566
  • 19
  • 63
  • 90
  • How will i come to know that some other application is going to start playing music file. So that i can stop mine. – Vaibs Dec 20 '12 at 12:35
  • onStop() works when another other task/onPause() is called when same app's activity comes to foreground. So, when ur application goes to the background onStop() and onPause() are called. So, place the two overriden methods in your activity where Music is playing, then debug the application u can understand clearly.... – Avadhani Y Dec 20 '12 at 12:43
0

Create two method like this. For audio play.

private void playAudioFile() 
    {
        try
        {
             mp=new MediaPlayer();
             mp.reset();
             mp.setDataSource(audiofileName));
             mp.prepare();
             mp.start();
        }
        catch (Exception ex) 
        {
            ex.printStackTrace();

        }
    }

and this for killMedia player.

private void killMediaPlayer() 
    {
        if(mp != null) 
        {
            try 
            {
                mp.release();
            }
            catch(Exception e) 
            {
                e.printStackTrace();
            }
        }
    }

use this done it's work for me.

and call like this 
killMediaPlayer();
playaudio();
Zala Janaksinh
  • 2,929
  • 5
  • 32
  • 58