检查Android MediaPlayer是否已初始化 [英] Check if Android MediaPlayer has been initialized

查看:479
本文介绍了检查Android MediaPlayer是否已初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查MediaPlayer对象是否已初始化?是否有类似的东西:

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. :( ");

当然,我检查了API文档,没有类似的方法,但是有类似的方法吗?

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

我正在考虑只是遍历我的代码,并在引发时捕获抛出的Exception,但是我觉得那很没意思. :P

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

我的代码原本是要经过这样的过程:

My code was intended to go through like this:

MediaPlayer mp;

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

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

推荐答案

当方法声明其引发异常时,使用该方法时,有两个选择.声明您的方法也使用throws关键字或catch异常抛出异常(可以这样说).您必须执行其中一项操作.

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.

即使文档包含一个isInitialized()方法,如果该方法仍在抛出IllegalStateException,您仍必须使用这两种方法之一来处理它们.

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.

此外,捕获很优雅,它使您的应用程序不会崩溃(崩溃不是优雅的),并让您知道出了什么问题.如果您有很多媒体播放器调用(例如以相同的方法接连进行),则可以将它们全部放在一个try/catch块下.

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.

这篇关于检查Android MediaPlayer是否已初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆