Search code examples
androidinitializationandroid-mediaplayer

Check if Android MediaPlayer has been initialized


How does one check if a MediaPlayer object has been initialized? Is there something like a:

MediaPlayer mp;
if(mp.isInitialized())
    Log.v("Test", "mp has been initialized. :D ");
else
    Log.v("Test", "mp is NOT yet initialized. :( ");

Of course, I checked the API Documentation and there isn't a method like that, but is there a similar approach?

I'm considering just going through my code and just catching the thrown Exception if it ever triggers, but I find that unelegant. :P

EDIT:

My code was intended to go through like this:

MediaPlayer mp;

// Lorem ipsum dolor sit amet consectetur adipisicing...

if(mp.isInitialized)
{
    mp.stop();
}

Solution

  • When a method declares that it throws an Exception, when you are using that method, you have two options. Either declare your method to also throw the Exception (passing the buck off so to speak) using the throws keyword, or catch the exception. You must do one of those things.

    Even if the documentation,contained an isInitialized() method, if the methods were still throwing IllegalStateExceptions, you must still handle them by one of those two methods.

    Also, catching is elegant, it allows your app not to crash (crashing isn't elegant) and lets you know something is wrong. If you have a lot of media player calls (such as right after another in the same method), you can put them all under one try/catch block.