Android 在 BroadcastReceiver 中调用 TTS [英] Android call TTS in BroadcastReceiver

查看:39
本文介绍了Android 在 BroadcastReceiver 中调用 TTS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 BroadcastReceiver 的子类中调用 TTS 服务.当我从 OnInitListener 实现该类时,它给出了运行时错误.

I need to call TTS service within subclass of BroadcastReceiver. When I am implement that class from OnInitListener, it gave run-time error.

有没有其他方法可以在 BroadcastReceiver 中实现 TTS?

Is there any other-way to implement TTS within BroadcastReceiver?

谢谢,

抱歉代码:

public class TextApp extends BroadcastReceiver implements OnInitListener {
private TextToSpeech tts;
private String message = "Hello";


@Override
public void onReceive(Context context, Intent intent) {
    tts = new TextToSpeech(context, this);
    message = "Hello TTS";
}

@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS)
    {
        tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
    }


}
}

推荐答案

您的代码无法正常工作:

Your code didn't work on :

tts = new TextToSpeech(context, this);

BroadcastReceiver 上的上下文是受限上下文".这意味着您无法在 BroadcastReceiver 的上下文中启动服务.因为 TTS 是一种服务,所以它不会调用任何东西.

Context on BroadcastReceiver is a "restricted context". It means you cannot start service on context in BroadcastReceiver. Because TTS is a service, so it doesn't call anyting.

最好的解决方案是您在 BroadcastReceiver 上通过调用服务的活动开始另一个意图.

The Best Solutions is you start another intent on BroadcastReceiver with activity that call the service.

public void onReceive(Context context, Intent intent) {
....

    Intent speechIntent = new Intent();
    speechIntent.setClass(context, ReadTheMessage.class);
    speechIntent.putExtra("MESSAGE", message.getMessageBody().toString());
    speechIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |  Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
    context.startActivity(speechIntent);
....
}

然后在活动中使用来自 extras 的参数调用 TTS 服务

And then on the activity you call the TTS service with parameter from extras

public class ReadTheMessage extends Activity implements OnInitListener,OnUtteranceCompletedListener {

private TextToSpeech tts = null;
private String msg = "";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent startingIntent = this.getIntent();
    msg = startingIntent.getStringExtra("MESSAGE");
    tts = new TextToSpeech(this,this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (tts!=null) {
        tts.shutdown();
    }
}

// OnInitListener impl
public void onInit(int status) {
    tts.speak(msg, TextToSpeech.QUEUE_FLUSH, null);
}

// OnUtteranceCompletedListener impl
public void onUtteranceCompleted(String utteranceId) {
    tts.shutdown();
    tts = null;
    finish();
}
}

这篇关于Android 在 BroadcastReceiver 中调用 TTS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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