Reputation: 87
I would like to make sparing use of TTS from several Activities (one MAIN Activity can start multiple other Activities).
I realize that there is no concept of a "global" class (or any other global anything), other than via Application and Activity.getApplication()
. It is all but useless since it returns null
in an Activity's onCreate()
methods, or constructors. This appears to be because the Activity is not "attached" to the Application context until the object is completely constructed.
There MUST to be a way to do this that isn't full-on silly, like re-implementing TTS in each and every Activity.
Alternative: I use Intent and startActivity()
to start each new Activity, so is there a way to pass a reference to the toplevel Activity via Intent.putExtras()
?
Upvotes: 3
Views: 1746
Reputation: 52936
TextToSpeech
is tied to a Context
(Activity), so you can't really make a 'global' object you can just use anywhere. If you don't want to duplicate code, create an base TtsActivity
and put common code there. Or, create a TtsManager
or similar class that takes care of initializing, etc. TTS and put it in all activities that need it.
Upvotes: 1
Reputation: 2737
You can create a regular Java class that inherits from Object, and put the methods you want in there.
Edit: I've never used android TTS, but it should look something like this, I'd gather
public class SpeechHelper {
public static void speak(String text, Context con)
{
TextToSpeech tts = new TextToSpeech(con, TextToSpeech.onInitListener {
private void onInit(int status){
tts.speak(text, TextToSpeech.QUEUE_ADD, new HashMap<String, String>());
}
});
}
}
Upvotes: 0
Reputation: 95578
getApplication()
always returns a valid reference if called from within your activity's onCreate()
method. It will return null
if called within the activity's constructor, but you shouldn't define a constructor for an activity anyway. Are you trying to call onCreate()
yourself?
If you want to store data in the Application
instance then you will need to subclass Application
and you will need to provide the name of your subclass in the manifest as
<application android:name="fully.qualified.name.of.my.application.subclass">
Upvotes: 0