Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android call TTS in BroadcastReceiver

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

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

Thank You,

Sorry Code:

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


}
}
like image 787
Chandana Avatar asked Dec 21 '10 09:12

Chandana


1 Answers

Your code didn't work on :

tts = new TextToSpeech(context, this);

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.

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

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();
}
}
like image 164
faruk Avatar answered Oct 09 '22 22:10

faruk