Android上的TextToSpeech初始化-如果失败,该怎么办? [英] TextToSpeech initialization on Android -- what if it fails?

查看:268
本文介绍了Android上的TextToSpeech初始化-如果失败,该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android中,如果TextToSpeech实例未能初始化(调用的回调指示TextToSpeech引擎初始化完成,则返回TextToSpeech.ERROR),这是否意味着对该实例的后续尝试方法调用将导致空指针异常?/p>

示例...

我们初始化对象:

  t1 = new TextToSpeech(getApplicationContext(),new TextToSpeech.OnInitListener(){@Overridepublic void onInit(int status){如果(状态== TextToSpeech.ERROR){Log.i("XXX",初始化TTS时出错");}}}); 

...假设初始化失败,但是接下来我们要做类似的事情:

  t1.speak("hello"); 

会崩溃吗?还是什么都不说?我问的原因是,如果它确实崩溃了,那么显然我将不得不在所有地方放置空检查.

此外,我不能自己找出原因的原因是我不知道如何模拟错误.

感谢您有任何先验知识.

解决方案

对于您的主要问题,请阅读 speak()方法的文档(

... let's say the init fails, but we then go on to do something like:

t1.speak("hello");

Will this crash... or just say nothing? The reason I ask is that if it does crash, then obviously I would have to put null checks everywhere.

Also, the reason I can't just find out for myself is that I don't know how to simulate the error.

Thanks for any prior knowledge.

解决方案

For your main question read the docs of the speak() method (here):

This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns.

So unless your tts instance is null, it shouldn't throw any exception or crash the app, but just return the error code.

Also, the reason I can't just find out for myself is that I don't know how to simulate the error.

Try to use constructor (see docs) that expects as third parameter String engine and put invalid package name there. It should probably result in error then. (or disable/uninstall all TTS engines on your device/emulator)

Important thing to note regarding constructor is:

In a case of a failure the listener may be called immediately, before TextToSpeech instance is fully constructed.

So unless the status is SUCCESS, you shouldn't touch your tts in the listener (of course you can use the tts afterwards as in your example) because it might not even be assigned / initialized yet.

这篇关于Android上的TextToSpeech初始化-如果失败,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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