Android 我需要文本来在后台工作,我该怎么做?
我已经在我的Android应用程序中实现了一个非常基本的TextToSpeech,当应用程序在前台运行时,它似乎工作得很好,但在后台时它不会播放。它等待应用程序返回前台并播放队列中的内容。对于需要在显示器关闭时提供轨迹反馈的GPS跟踪应用程序,如何实现这一点? 提前谢谢Android 我需要文本来在后台工作,我该怎么做?,android,text-to-speech,android-gps,Android,Text To Speech,Android Gps,我已经在我的Android应用程序中实现了一个非常基本的TextToSpeech,当应用程序在前台运行时,它似乎工作得很好,但在后台时它不会播放。它等待应用程序返回前台并播放队列中的内容。对于需要在显示器关闭时提供轨迹反馈的GPS跟踪应用程序,如何实现这一点? 提前谢谢 public class MainActivity extends AppCompatActivity implements LocationListener, GpsStatus.Listener { Location
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();
}
}
您的用例需要
服务
。现在,TTS和LocationManager
生命周期与您的活动
相关联,这是应用程序离开屏幕后最有可能被销毁的组件。我理解。你们知道怎么做吗?我先从。您可能需要前台服务。活动
应在活动时绑定,否则服务
只能独立存在。感谢您的帮助:)