Reputation: 137
Is it possible to turn the text to speech feature on inside the LocatioListener class??
I'm trying to make an android application detect how far you have moved. I am able to turn on the GPS, and monitor for location movement. I would like to make it say "You have moved 300meters". It would be very convenient to put it inside the OnLocation method, but it complains when i try to instantiate the texttospeech??
This is what I was trying:
public class Location implements LocationListener {
static TextToSpeech talk;
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
//This yells at me on next line, won't let me use 'this' as context?? (Also tried Location.this)
talk = new TextToSpeech(this, new extToSpeech.OnInitListener() {
public void onInit(int status) {
// TODO Auto-generated method stub
talk.setLanguage(Locale.UK);
Location aloc = new Location("aloc");
Location bloc = new Location("bloc");
aloc.setLatitude(alat);
aloc.setLongitude(alon);
bloc.setLatitude(blat);
bloc.setLongitude(blon);
float distance = aloc.distanceTo(bloc);
talk.speak("You Moved..", TextToSpeech.QUEUE_FLUSH, null);
}
});
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
Upvotes: 1
Views: 390
Reputation: 45493
You will need a reference to a Context
in order to initialise the TTS engine. Hence it will not work with this
or Location.this
, since both refer to the running instance of your Location
class, which obviously is not a Context
(or subclass of it).
That being said, there are multiple options.
Location
class as anonymous innerclass or non-static innerclass in e.g. an Activity
(or any other class where you can get a reference to a Context
object), you can use a reference to the outer class to initialise the TTS engine.Location
class, initialize it somewhere where you do have a Context
reference; e.g. the same place where you request the LocationManager
(for which you already need a Context
reference).Application
and keep it around there. After it has been initialized, you can get and use it more or less anywhere you like.Upvotes: 1