2

I want to develop Text-To-Speech (TTS) feature in my app. It must be implemented inside Service, because user may leave "details" Activity and get back to "main" Activity or even leave my app, and it should still speak out loud text. Since Oreo introduced some background limitations for services and I must support 4.0+ I have to use JobIntentService

Problem is that TTS have async implementation and JobIntentService gets killed just after onHandleWork finishes its job, even when I use startForeground (in my code showSpeakingNotification)

Funny part is that when I but a breakpoint inside onHandleWork after 'speakOut' method or just uncomment Thread.sleep service is working and reading my text (and foreground notification is present).

Question is how to prevent "auto-killing" my service when it is actually running, but using asynchronous feature inside?

@Override
protected void onHandleWork(@NonNull Intent intent) {
    if (ACTION_SPEAK.equals(intent.getAction()) && intent.hasExtra(EXTRA_TEXT_ARRAY)) {
        ArrayList<String> textArr = intent.getStringArrayListExtra(EXTRA_TEXT_ARRAY);
        showSpeakingNotification(textArr.get(0));
        if (ttsInitialized)
            speakOut(textArr);
        else if (ttsInitListener != null)
            ttsInitListener.setPendingText(textArr);
    } else if (ACTION_STOP_SPEAKING.equals(intent.getAction())) {
        if (ttsInitialized && tts.isSpeaking())
            tts.stop();
    }
    try {
        //Thread.sleep(10000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
snachmsm
  • 17,866
  • 3
  • 32
  • 74

1 Answers1

1

just uncomment Thread.sleep service is working and reading my text

When you add Thread.sleep(10000); it blocks the current thread as a result, it doesn't respond to your speech. When you comment it current thread is free to read your data

Question is how to prevent "auto-killing" my service when it is actually running, but using asynchronous feature inside?

Note possible. Your requirements can be fulfilled using Foreground Service. Refer to this SO for implementing the Foreground Service

Sagar
  • 23,903
  • 4
  • 62
  • 62
  • with `Thread.sleep` its actually reading text out loud (for sleep duration), but it was only test, no the solution. Hopefully Foreground Service will work, I will check your link and get back with feedback or answer mark :) thanks! – snachmsm Jun 07 '18 at 08:36
  • @snachmsm sure. – Sagar Jun 07 '18 at 08:39
  • @snachmsm great! enjoy coding – Sagar Jun 07 '18 at 09:17