2012-12-14 37 views
1

所以我有點問題。我試圖讓我的應用程序根據它通過GCM收到的消息來做事。在這種情況下,它應該使用TextToSpeech類發出聲音。這是有用的,但不是我第一次發送信息。我意識到這可能是因爲TextToSpeech沒有被實例化,但我不確定如何去做和做到這一點?我嘗試了onInit(),但那根本不起作用。在GCMIntentService中實例化TextToSpeech

另外,在我的例子中關閉TTS的最好方法是什麼?

聲明:我來自PHP背景,並且知道Java很少。我試着通過這樣做來學習,所以請原諒我,如果這是一個愚蠢的問題。提前致謝!

public class GCMIntentService extends GCMBaseIntentService { 

private static final String TAG = "GCMIntentService"; 
public static TextToSpeech mtts; 

public GCMIntentService() { 
    super(SENDER_ID); 
} 

@Override 
protected void onMessage(Context context, Intent intent) { 
    Log.i(TAG, "Received message"); 
    String message = intent.getExtras().getString("message"); 
    mtts = new TextToSpeech(context, null); 

    if (message.startsWith("makeSound")) { 
     mtts = new TextToSpeech(context, null); 
     mtts.setLanguage(Locale.US); 
     mtts.speak(message, TextToSpeech.QUEUE_FLUSH, null); 
    } 
} 
} 

回答

0

因爲TextToSpeech的初始化是異步的,所以它第一次不工作。你不能簡單地實例化它,並像你一樣使用它。如果你想馬上使用TextToSpeech,你應該提供一個回調函數來調用它。

mTextToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() 
    { 
     @Override 
     public void onInit(int status) 
     { 
      // Check for status might not be initialized due to errors 
      // Configure language/speed 
     } 
    }); 

因爲mtts是靜態的,所以它在其他時間都有效。這意味着它是一個類變量,在創建服務的新實例時不會被銷燬/初始化。第二次使用此服務時,此變量已在第一次服務執行中初始化。

+0

謝謝你!這就像一個魅力:) – user1904218

+0

任何想法如何正常關機? – user1904218