【发布时间】:2019-04-08 10:20:33
【问题描述】:
在这里,我实现了使用 Text-To-Speech 读取传入推送通知消息的功能。我为它创建了一个单独的服务类,它工作正常,一段时间后通知来了,但它停止读取通知。
public class TTSService extends Service implements TextToSpeech.OnInitListener {
private static final String TAG = "TTSService";
private String mSpeechMessage;
private TextToSpeech mTts;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
mTts = new TextToSpeech(this,
this // OnInitListener
);
mTts.setSpeechRate(1f);
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
if (intent != null && intent.hasExtra(AppConstant.FEEDBACK_MSG)) {
mSpeechMessage = intent.getStringExtra(AppConstant.FEEDBACK_MSG);
}
speakMessage(mSpeechMessage);
super.onStart(intent, startId);
}
@Override
public void onInit(int status) {
Log.v(TAG, "oninit");
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.v(TAG, "Language is not available.");
} else {
if (mSpeechMessage != null) {
speakMessage(mSpeechMessage);
}
}
} else {
Log.v(TAG, "Could not initialize TextToSpeech.");
}
}
private void speakMessage(String str) {
if (str != null) {
mTts.speak(str,
TextToSpeech.QUEUE_FLUSH,
null);
}
//Stop Service
// stopSelf();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
}
我从FirebaseMessagingService 开始这项服务:
private void startTTSService(String message) {
Intent intent = new Intent(getApplicationContext(), TTSService.class);
intent.putExtra(AppConstant.FEEDBACK_MSG, message);
startService(intent);
}
如果有人可以提供帮助,那就太好了。提前致谢。
【问题讨论】:
-
从 API 级别 26 开始,android 限制后台服务访问。详情请查看developer.android.com/guide/components/services。您可以通过将服务作为前台启动来解决此问题。
-
@Ajay-Rlogical 我尝试使用
startForeground,但没有任何改变。
标签: android push-notification text-to-speech background-service