我使用JobService实现的TTS(文本到语音)如下:
package services;
import android.annotation.TargetApi;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import utilities.PhoneUtils;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class TTSJobScheduledService extends JobService {
private static TextToSpeech voice =null;
public static TextToSpeech getVoice() {
return voice;
}
@Override
public boolean onStartJob(JobParameters params) {
startTTSEngine();
PhoneUtils.scheduleTTSJob(getApplicationContext()); // reschedule the job
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
clearTtsEngine();
return true;
}
private void startTTSEngine()
{
try{
voice = new TextToSpeech(TTSJobScheduledService.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(final int status) {
}
});
}
catch(Exception e){
e.printStackTrace();
}
}
private static void clearTtsEngine()
{
if(voice!=null)
{
voice.stop();
voice.shutdown();
voice = null;
}
}
}
在某些HUAWEI设备上,它导致崩溃,如下所示:
Caused by java.lang.IllegalArgumentException: Service not registered: android.speech.tts.TextToSpeech$Connection@2b329ed
at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:1659)
at android.app.ContextImpl.unbindService(ContextImpl.java:1854)
at android.content.ContextWrapper.unbindService(ContextWrapper.java:703)
at android.speech.tts.TextToSpeech$Connection.disconnect(TextToSpeech.java:2287)
at android.speech.tts.TextToSpeech$1.run(TextToSpeech.java:855)
at android.speech.tts.TextToSpeech$1.run(TextToSpeech.java:851)
at android.speech.tts.TextToSpeech$Connection.runAction(TextToSpeech.java:2307)
at android.speech.tts.TextToSpeech.runAction(TextToSpeech.java:752)
at android.speech.tts.TextToSpeech.runActionNoReconnect(TextToSpeech.java:738)
at android.speech.tts.TextToSpeech.shutdown(TextToSpeech.java:850)
at services.TTSJobScheduledService.clearTtsEngine(Unknown Source:11)
at services.TTSJobScheduledService.onStopJob(Unknown Source)
at android.app.job.JobService$1.onStopJob(JobService.java:76)
at android.app.job.JobServiceEngine$JobHandler.handleMessage(JobServiceEngine.java:117)
at android.os.Handler.dispatchMessage(Handler.java:109)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7377)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
我了解它正在尝试清除可能已经清除的服务。但是,在这种情况下,我不确定如何正确实现 clearTTSEngine 方法。有人可以让我知道可能出什么问题以及如何解决吗?