Search code examples
javaandroidservicemedia-player

Media Player Bound Service Locks Up UI When Pausing Thread


I know that pausing a thread can easily lockup the UI, and it is generally a bad idea. However it was my understanding that if something is running as a service that will not cause any issues, because the service will pause and the main app will continue running.

With that in mind, I am either doing something wrong, or just misunderstood the use of a service for a MediaPlayer.

I create the object

public AudioService AudioService;
public boolean AudioServiceBound = false;

and then in my SurfaceView's onStart event I bind it:

public void onStart() {
    Intent intent = new Intent(gameContext, AudioService.class);
    gameContext.bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}

throughout the rest of the class I run methods that pause and resume the AudioService based on the onResume and onPause events.

I have tried to introduce a new ability to my service. Within my main update loop I run the function HalfOverSwitch() seen below:

public void HalfOverSwitch()
{
    if (( ((float)player.getCurrentPosition()) / ((float)player.getDuration()) > 0.5) && !transitioning)
    {
        transitioning = true;

        MediaPlayer temp = MediaPlayer.create(this, R.raw.dumped);
        temp.setVolume(0, 0);
        temp.setLooping(true);
        temp.start();

        for (int i = 0; i < 100; i++)
        {
            player.setVolume(100-i, 100-i);
            temp.setVolume(i, i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        player = temp;
        player.setVolume(100,100);

        transitioning = false;
    }
}

Because that function doesn't return anything and is running in a different thread, it was my understanding that the main activity would not pause. It does however. That brings up the question, what is the best way to do something like that, and what is the point of making my AudioService a service at all (and not just a class)?


Solution

  • Service runs in the same thread in which service is created.

    http://developer.android.com/reference/android/app/Service.html

    "Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work. "