最近学习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)); }
恩,很简单吧,呵呵,不过还是很有成就感的说,嘿嘿。
贴些图片吧,呵呵: