brain56
brain56

Reputation: 2711

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();
}

Upvotes: 2

Views: 4472

Answers (3)

Kels Louis
Kels Louis

Reputation: 21

use a try and catch around the mediaPlayer method invocation and if the IllegalStateException is thrown then it is not initialized

try {
   mediaPlayer.isPlaying();
} catch(IllegalStateException e) {
   // media player is not initialized
}

Upvotes: 2

A--C
A--C

Reputation: 36449

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.

Upvotes: 6

Ben Jakuben
Ben Jakuben

Reputation: 3237

Two possible ideas:

  1. According to your "intended" code, why can't you use the isPlaying() method in place of the desired isInitialized()? Don't you only want to call mp.stop() if it's actually playing something?

  2. How about putting mp.stop() or whatever inside an OnPreparedListener?

Upvotes: 0

Related Questions