根据在2018年11月之前将目标SDK版本更新为26的要求,我在将目标sdk和编译sdk版本都更新为26(从23)后,尝试在几个月前更新gradle文件并发布了新版本的应用程序. .一天之内,我开始在Firebase控制台上观察我的应用程序中的崩溃.原因是我在我的应用程序中使用了TTS服务,并且当定位到版本26时,由于致命的运行时异常,它似乎需要TTS服务的新实现.因此,我将目标SDK版本还原为23,并将sdk版本编译为23.
Caused by java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.a.b.c/services.TTSService }: app is in background
仅在Android OS 8.0和8.1上的设备上看到此例外.
因此,一个月前,我购买了一个新设备,该设备在Android 8.0(Motorola G6 Plus)上运行,希望能够始终如一地重现此错误.但是,即使我的应用程序的目标版本为26,即使我通过我的应用程序强制触发了TTS服务,该设备也从未发生过.因此,我对如何进行感到困惑.
here说明了此异常的解决方案.
我当前用于实现和调用TTS服务的代码如下:
MainActivity oncreate方法:
if(!isMyServiceRunning(TTSService.class))//Start a service instance only if service is currently not running
startService(new Intent(MainActivity.this, TTSService.class));
TTSService.java:
package services;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Environment;
import android.os.IBinder;
import android.speech.tts.TextToSpeech;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.firebase.crash.FirebaseCrash;
import constants.ConstantParams;
public class TTSService extends Service {
private static TextToSpeech voice =null;
public static TextToSpeech getVoice() {
return voice;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
// not supporting binding
return null;
}
public TTSService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try{
voice = new TextToSpeech(TTSService.this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(final int status) {
}
});
}
catch(Exception e){
e.printStackTrace();
FirebaseCrash.report(new Exception("Error in initializing TTS object"));
FirebaseCrash.log("Error in initializing TTS object");
}
return Service.START_STICKY;
}
@Override
public void onDestroy() {
clearTtsEngine();
super.onDestroy();
}
public static void clearTtsEngine()
{
if(voice!=null)
{
voice.stop();
voice.shutdown();
voice = null;
}
}
}
是否必须根据上述解决方案重新实现此功能?还是我可以采用一种更简单的方法来定位版本26 SDK,但将编译SDK版本保留为23(这是我应用程序中的当前状态)?任何其他解决方案将不胜感激.