最近學習android寫了一個算的上是應用的app,功能很簡單,利用google 提供的translate服務將輸入的字符翻譯成想要的語言(比如英漢翻譯)和http://translate.google.cn/差不多(這裡我直接應用了google-api-translate-Java-0.92.jar這個jar包,操作很簡單,方便,嘿嘿),還有利用android的TextToSpeech進行speech翻譯的結果,由於android的TextToSpeech只支持English,French,German,Italian,Spanish,所以只有翻譯的目標語言是上面的語種時才進行speech;還有功能就是將翻譯的結果能以email/msg的形式發送消息給別人。寫這個程序的重點在於學習利用AIDL進行process間的信息傳遞(關於aidl的知識google下可以找到很多,呵呵)
定義activity訪問translate service的代碼段:
- private ServiceConnection mTranslateConn = new ServiceConnection() {
- public void onServiceConnected(ComponentName name, IBinder service) {
- mTranslateService = ITranslate.Stub.asInterface(service);
- if (mTranslateService != null) {
- mTranslateButton.setEnabled(true);
- } else {
- mTranslateButton.setEnabled(false);
- mStatusVIEw.setText(getString(R.string.error));
- log("Unable to acquire TranslateService");
- }
- }
- public void onServiceDisconnected(ComponentName name) {
- mTranslateButton.setEnabled(false);
- mTranslateService = null;
- }
- };
google translate service的應用:
- GoogleAPI
- .setHttpReferrer("http://code.google.com/p/google-api-translate-Java/");
- String translatedText = Translate.execute(text, Language
- .fromString(from), Language.fromString(to));
TextToSpeech的應用:
- @Override
- public void onInit(int status) {
- // TODO Auto-generated method stub
- if (status == TextToSpeech.SUCCESS) {
- Language to = (Language) mToButton.getTag();
- String toShortName = to.getShortName();
-
- int result = tts.setLanguage(new Locale(toShortName));
-
- if (result == TextToSpeech.LANG_MISSING_DATA ||
- result == TextToSpeech.LANG_NOT_SUPPORTED) {
-
- Log.e(TAG, "Language is not available.");
- } else {
- // sayText();
- }
- } else {
- // Initialization failed.
- Log.e(TAG, "Could not initialize TextToSpeech.");
- }
- }
-
- private void sayText() {
-
- String sayInfo = mToEditText.getText().toString();
- Language to = (Language) mToButton.getTag();
- String toShortName = to.getShortName();
- tts.setLanguage(new Locale(toShortName));
- tts.speak(sayInfo, TextToSpeech.QUEUE_FLUSH,null);
- }
最後send msg的應用:
- private void sendEmail() {
- Intent intent = new Intent(Intent.ACTION_SEND);
- intent.setType("text/plain");
- intent.putExtra(Intent.EXTRA_TEXT, mToEditText.getText());
- startActivity(Intent.createChooser(intent, null));
- }
恩,很簡單吧,呵呵,不過還是很有成就感的說,嘿嘿。