06 octubre 2015
Posted by, Barak Turovsky, Product Lead, Google Translate
Google Translate is used by more than 500 million people every month, translating more than 100 billion words every single day.
Beginning this week, Android mobile users who have the Translate app installed will be able to translate in 90 languages right within some of their favorite apps on any device running the newest version of Android’s operating system (Android 6.0, Marshmallow).
Android apps that use Android text selection behavior will already have this feature enabled, so no extra steps need to be taken. Developers who created custom text selection behavior for their apps can easily implement this feature by following the below steps:
Scan via the PackageManager through all packages that have the PROCESS_TEXT intent filter (for example: com.google.android.apps.translate - if it installed) and add them as MenuItems into TextView selections for your app
private Intent createProcessTextIntent() { return new Intent() .setAction(Intent.ACTION_PROCESS_TEXT) .setType("text/plain"); }
private ListgetSupportedActivities() { PackageManager packageManager = mTextView.getContext().getPackageManager(); return packageManager.queryIntentActivities(createProcessTextIntent(), 0); }
public void onInitializeMenu(Menu menu) { // Start with a menu Item order value that is high enough // so that your "PROCESS_TEXT" menu items appear after the // standard selection menu items like Cut, Copy, Paste. int menuItemOrder = 100; for (ResolveInfo resolveInfo : getSupportedActivities()) { menu.add(Menu.NONE, Menu.NONE, menuItemOrder++, getLabel(resolveInfo)) .setIntent(createProcessTextIntentForResolveInfo(resolveInfo)) .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } }
resolveInfo.loadLabel(mPackageManager);
The intent for each item can be created reusing the filter intent that you defined before and adding the missing data:
private Intent createProcessTextIntentForResolveInfo(ResolveInfo info) { return createProcessTextIntent() .putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, ! mTextView.isTextEditable()) .setClassName(info.activityInfo.packageName, info.activityInfo.name); }
Adding the translation option to your apps text selection menu (if you don’t use default Android text selection behavior) is easy and takes just a few extra lines of code. And remember, when a user is composing a text to translate, your app you should keep the selection when the Translate app is triggered.
With this new feature, Android Translate app users users will be able to easily translate right from within participating apps. We will be adding more documentation and sample code on this feature in the upcoming weeks.