Android在BroadcastReceiver中调用TTS

Cha*_*ana 7 android text-to-speech

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

在BroadcastReceiver中是否有其他方式来实现TTS?

谢谢,

对不起代码:

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


}
}
Run Code Online (Sandbox Code Playgroud)

far*_*ruk 6

您的代码无效:

tts = new TextToSpeech(context, this);
Run Code Online (Sandbox Code Playgroud)

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

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

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);
....
}
Run Code Online (Sandbox Code Playgroud)

然后在活动中使用附加参数调用TTS服务

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();
}
}
Run Code Online (Sandbox Code Playgroud)