android - 我需要 TextToSpeech 在后台工作,我该怎么做?
问题描述
我在我的 Android 应用程序中实现了一个非常基本的 TextToSpeech,当应用程序在前台运行时它似乎运行良好,但在后台运行时它不会播放。它一直等到应用程序返回前台并播放队列中的内容。如何为我的 GPS 跟踪应用程序实现这一点,该应用程序需要在显示屏关闭时提供跟踪反馈?提前致谢。
public class MainActivity extends AppCompatActivity implements LocationListener, GpsStatus.Listener {
LocationManager locationManager;
TextToSpeech textToVoice;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Locale spanish = new Locale("es", "ES");
textToVoice = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToVoice.setLanguage(spanish);
}
}
});
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
locationManager.addGpsStatusListener(this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, this);
}
this.onLocationChanged(null);
}else{
this.finish();
}
}
@Override
public void onLocationChanged(Location location) {
TextView view = this.findViewById(R.id.dashView);
TextView actual = this.findViewById(R.id.actualView);
if(location == null) {
view.setText("0.0 Km/h");
} else {
//location.setAccuracy(1);
float speedInMs = location.getSpeed();
double currentSpeed = ( speedInMs * 3.6 );
DecimalFormat df = new DecimalFormat("#.##");
df.format(currentSpeed);
String speed = df.format(currentSpeed) + "Km/h";
view.setText(speed);
actual.setText(speedInMs + "m/s");
textToVoice(speed);
Log.d("GPS", "Location Change:" + location.getLongitude() + "," + location.getLatitude());
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onGpsStatusChanged(int i) {
}
public void textToVoice( String message){
textToVoice.speak(message,
TextToSpeech.QUEUE_FLUSH, null,null);
}
@Override
protected void onDestroy() {
if (textToVoice != null) {
textToVoice.stop();
textToVoice.shutdown();
}
if(locationManager !=null){
locationManager.removeUpdates(this);
}
super.onDestroy();
}
}
解决方案
推荐阅读
- javascript - 无法发送异步发布请求
- java - 当我单击 Imagebutton 而不是将我带到另一个 Activity 时,我的应用程序崩溃了
- android - 动态 RecyclerView 上的空视图
- c++ - 计算字符串网格中的字符串短语
- javascript - 数据未获取到在 textarea 上按 Enter 键
- api - LinkedIn API 更改
- sphinx - 将邻近搜索强制转换为多个单词形式?
- mysql - 为什么使用偏移量时 where 子句不起作用?
- git - 如何从分支的一部分创建拉取请求?
- pandas - 使用 np.where 将循环转换为矢量化格式时出现 ValueError