Check if Android MediaPlayer has been initialized

人盡茶涼 提交于 2019-12-11 03:56:52

问题


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

回答1:


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.




回答2:


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
}



回答3:


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?



来源:https://stackoverflow.com/questions/14371180/check-if-android-mediaplayer-has-been-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!