How to use google translator app - android

I coded program about dictionary sentence and I want to have function to go to "google translator" application in my app
How can I use it , Should I import anything?

From what I can tell, the Google Translate Android app does not expose any standard Intents that you could use (it's a pitty, but it's weird at the same time. You'd think Google would encourage this type of interaction between apps.. anyway).
However, it seems Google have opened up the translate API via a web service. This way, you can do the translation yourself and show it within your app. It's a bit more work, but it should do the job.
You could look at google-api-translate-java if you want to spare yourself from writing an API wrapper.

I have the same problem. Initially, I tried to use Google Translate Ajax API, but since Google have deprecated API version 1 and make version 2 as paid service, my code stops working. Then, I decompiled Google Translate App, looked into the Smali code and got some hint about the logic inside it. Use this code, it works for me:
private void callGoogleTranslateApps(String word, String fromLang, String toLang) {
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.putExtra("key_text_input", word);
i.putExtra("key_text_output", "");
i.putExtra("key_language_from", fromLang);
i.putExtra("key_language_to", toLang);
i.putExtra("key_suggest_translation", "");
i.putExtra("key_from_floating_window", false);
i.setComponent(new ComponentName("com.google.android.apps.translate", "com.google.android.apps.translate.TranslateActivity"));
startActivity(i);
}

Phi Van Ngoc's answer was fantastic, thanks for that.
However it didn't work initially for me and after investigating the Translate apk, it looks like they've modified their file structure slightly, so the intent ComponentName should now be:
i.setComponent(
new ComponentName(
"com.google.android.apps.translate",
"com.google.android.apps.translate.translation.TranslateActivity"));
The difference is that "translation" has been added before "TranslateActivity"
So my final version, including hard-coded translation from Spanish to English, is:
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.putExtra("key_text_input", "Me gusta la cerveza");
i.putExtra("key_text_output", "");
i.putExtra("key_language_from", "es");
i.putExtra("key_language_to", "en");
i.putExtra("key_suggest_translation", "");
i.putExtra("key_from_floating_window", false);
i.setComponent(
new ComponentName(
"com.google.android.apps.translate",
"com.google.android.apps.translate.translation.TranslateActivity"));
startActivity(i);

OMG! They have changed it once again! They have made it look more reasonable, but not compatible with the previous version.
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, "What is going on?");
i.putExtra("key_text_input", "Oh my God!");
i.putExtra("from", "en");
i.putExtra("to", "zh-CN");
i.setComponent(new ComponentName("com.google.android.apps.translate",
"com.google.android.apps.translate.HomeActivity"));
Looks like this is a SEND intent with two additional (BTW, optional) parameters, "to" and "from".
There's a gotcha: "key_text_input" takes preference over Intent.EXTRA_TEXT, and "to" and "from" work only with "key_text_input".
For people that change the API with each new version it may look only reasonable to rename "key_text_input" to, say, just "text_input", so we will look forward to the next release...
To be on the safe side, I'd propose to set both Intent.EXTRA_TEXT and "key_text_input" to the same value.

The Google Translate activity names tend to change over time which makes the code fragile if you hardcode them.
Here is an approach that works with the current version of google translate and will likely keep working with future updates (as long as the package name stays the same):
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (ResolveInfo resolveInfo : getPackageManager().queryIntentActivities(new Intent().setAction(Intent.ACTION_PROCESS_TEXT).setType("text/plain"), 0)) {
if (resolveInfo.activityInfo.packageName.equals("com.google.android.apps.translate")) {
String activityName = resolveInfo.activityInfo.name;
String packageName = resolveInfo.activityInfo.packageName;
Intent intent = new Intent().setPackage(packageName)
.setClassName(packageName, activityName)
.setAction(Intent.ACTION_PROCESS_TEXT)
.setType("text/plain")
.putExtra(Intent.EXTRA_PROCESS_TEXT, "Nobody expects the Spanish Inquisition!")
.putExtra(Intent.EXTRA_PROCESS_TEXT_READONLY, true);
startActivity(intent);
}
}
} else {
// >>> deprecated code from other answers goes here <<<
}

To add the above answers:
it is important that you pass two-letter language codes. With 3-letter codes, it may look like the google translate app does not receive any data.
In addition, if Intent.ACTION_VIEW does not work, you can use Intent.ACTION_SEND.
intent = new Intent();
//intent.setAction(Intent.ACTION_VIEW); // this did not work for me initially
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, m_text);
intent.putExtra("key_text_input", m_text);
intent.putExtra("key_text_output", "");
intent.putExtra("key_language_from", m_language);
intent.putExtra("key_language_to", lang_to);
intent.putExtra("key_suggest_translation", "");
intent.putExtra("key_from_floating_window", false);
intent.setComponent(
new ComponentName(
"com.google.android.apps.translate",
"com.google.android.apps.translate.HomeActivity"
));
//try {
startActivityForResult(intent, REQUEST_CODE_TRANSLATE);
//...

Related

Suggest several apps in playstore to user (Similar to Share dialog)

My app forwards users to a different app to perform a specific action (e.g. ACTION_SHARE, except that the apps that I forward users to do not implement an intent filter) Since they don't implement intent filters, I have a list of package names that support the action.
This part is working fine, like this:
for (String knownApp : knownApps) {
Intent intent = pm.getLaunchIntentForPackage(knownApp);
if (intent != null) {
ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
intentList.add(new LabeledIntent(intent, knownApp, resolveInfo.loadLabel(pm), resolveInfo.icon));
}
}
LabeledIntent[] extraIntents = intentList.toArray(new LabeledIntent[intentList.size()]);
Intent openInChooser = Intent.createChooser(actionIntent, getString(R.string.perform_action_with));
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
startActivity(openInChooser);
If the user has none of the apps installed, I want to give the user a choice of apps to download to fulfill the action.
Currently that looks like this.
As you can see it's lacking both icon and name. For regular apps I use an intent chooser which needs LabledIntent, but on one hand, I can't get the name and icon from the playstore unless I scrape them (which is not allowed by google, besides LabledIntent requires a resourceId as the Icon, which I can't get for downloaded files.), on the other the intent chooser won't seem to display the intent unless the package name of the intent and LabeledIntent match. This does not work for URIs which I'm using to access the Play Store in the first place.
Now I'm looking for ideas on how to get the following code to display both the correct name and app icon, as well as forward to the correct page on the play store.
protected void showPlayStoreOptions(List<String> knownApps) {
Intent chooserIntent = new Intent();
Intent showIntent = Intent.createChooser(chooserIntent, "You need one of these Apps on Google Play..."); //googles brand guidelines state that "on Google Play" has to be used
List<Intent> list = new ArrayList<>();
for (String knownApp : knownApps) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + knownApp)); //normally you would try an uri with market:// first, catch the exception if no playstore is installed and then use this, but the intent chooser seems to automatically forward correctly.
list.add(intent);
//list.add(new LabeledIntent(intent, "https://play.google.com/store/apps/details?id=" + knownApp, "test name", R.drawable.icon_info));
//list.add(new LabeledIntent(intent, ""+Uri.parse("https://play.google.com/store/apps/details?id=" + knownApp), "test name", R.drawable.icon_info));
}
showIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, list.toArray(new Intent[list.size()]));
startActivity(showIntent);
}
So to sum up my questions.
How can I get a resource Id from a downloaded image file, or how can I use the downloaded image file with a LabledIntent.
(Extending LabledIntent does not work due to issues with parceling (and those methods are package private))
How can I display a LabledIntent in a choose intent with an URI?
I realize it's probably easier to write my own chooser, but I want to wrangle this into the default android system.

Android Google Translate QuickTranslateActiviy - Intent extra issue

I want to use the QuickTranslateActiviy
and I have tried this
Intent i = new Intent();
i.setAction(Intent.ACTION_PROCESS_TEXT);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.putExtra(Intent.EXTRA_TEXT,"String");
i.setType(ClipDescription.MIMETYPE_TEXT_PLAIN);
i.setComponent(new ComponentName("com.google.android.apps.translate","com.google.android.apps.translate.QuickTranslateActivity"));
startActivity(i);
and It just keep showing the toast that could not find text.
But the manifest of the Google translate here show that it accept plain text
had anyone try that before?Or am I doing it in a wrong way?
Tactically, you are using the wrong extra name. It should be EXTRA_PROCESS_TEXT or EXTRA_PROCESS_TEXT_READONLY, not EXTRA_TEXT.
Strategically, your implementation will break any time that the Google Translate app refactors their code or otherwise changes the fully-qualified class name of the activity.

Why doesn't my App Chooser dialogue show?

I am using this tutorial to learn about the basics of Intents in Android. The code sample I am using is adopted from the section named "Force an App Chooser" on the page linked.
The following is the method which should be invoked on the click of the button.
public void startSecondActivity(View view) {
Intent intent = new Intent(Intent.ACTION_SEND);
String fileChooserLabel = getResources().getString(R.string.fileChooserLabel);
Intent fileChooserIntent = Intent.createChooser(intent, fileChooserLabel);
if (intent.resolveActivity(getPackageManager())!=null) {
startActivity(intent);
} else {
textView = (TextView) findViewById(R.id.text_view);
textView.setText("False");
}
}
But it just enters the else block of the if-else conditional. I tried this app on both a real device and the emulator. So can anybody point out what might be wrong here, and what I can do about it.
Note: I did not add anything to the Manifest file, since I am using Eclipse IDE and I suppose whatever is required at this point is automatically added to the manifest file.
It is returning null because there are no activities on the device that support your Intent. In this case, your ACTION_SEND Intent is not properly set up.
Note that the code sample you used as a reference is not a tutorial. It is not designed to be a complete code sample. In fact, what they list there will not even compile, as their ... is meant to be replaced by your own code to complete setting up the Intent.
You will need to fully configure your ACTION_SEND Intent, most notably setting the MIME type, as is covered elsewhere in the documentation. Replacing:
Intent intent = new Intent(Intent.ACTION_SEND);
with something like:
Intent intent = new Intent(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_TEXT, "IM IN UR STAK OVERFLO ANZWR");
should suffice.

Search Intent in Android (for Evernote)

I was trying to create an intent in Android that would search in the Evernote app for a specific keyword, but the documentation that the Evernote site mentions doesn't seem to be available, so I tried writing it on my own, but it doesn't seem to work. This is what I have now:
final String ACTION_EVERNOTE = "com.evernote.action.SEARCH_NOTES";
String KEYWORD = "hoi";
Intent i = new Intent();
i.setAction(ACTION_EVERNOTE);
i.putExtra(Intent.ACTION_SEARCH, KEYWORD);
startActivity(i);
Does anyone have an idea what is going wrong here? Right now it just performs a search with an asterisk, which is the default, so it probably just ignores the ACTION_SEARCH part. Is there an error in that part of my intent?
Thanks in advance!
Try it like this, with the String called QUERY, as it's called in the SearchManager documentation:
final String ACTION_EVERNOTE = "com.evernote.action.SEARCH_NOTES";
String QUERY = "hoi";
Intent i = new Intent();
i.setAction(ACTION_EVERNOTE);
i.putExtra(Intent.ACTION_SEARCH, QUERY);
startActivity(i);
An addition to the answer above. There is a new tiny library to send these Intents to the Evernote core app.
https://github.com/evernote/android-intent

Android Intent for Twitter application

Is it possible to show a list of applications (with intent.createChooser) that only show me my twitter apps on my phone (so htc peep (htc hero) or twitdroid). I have tried it with intent.settype("application/twitter") but it doesnt find any apps for twitter and only shows my mail apps.
Thank you,
Wouter
I'm posting this because I haven't seen a solution yet that does exactly what I want.
This primarily launches the official Twitter app, or if that is not installed, either brings up a "Complete action using..." dialog (like this) or directly launches a web browser.
For list of different parameters in the twitter.com URL, see the Tweet Button docs.
Remember to URL encode the parameter values. (This code is specifically for tweeting a URL; if you don't want that, just leave out the url param.)
// Create intent using ACTION_VIEW and a normal Twitter url:
String tweetUrl = String.format("https://twitter.com/intent/tweet?text=%s&url=%s",
urlEncode("Tweet text"),
urlEncode("https://www.google.fi/"));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(tweetUrl));
// Narrow down to official Twitter app, if available:
List<ResolveInfo> matches = getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
if (info.activityInfo.packageName.toLowerCase().startsWith("com.twitter")) {
intent.setPackage(info.activityInfo.packageName);
}
}
startActivity(intent);
(URL encoding is cleaner if you have a little utility like this somewhere, e.g. "StringUtils".)
public static String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
}
catch (UnsupportedEncodingException e) {
Log.wtf(TAG, "UTF-8 should always be supported", e);
throw new RuntimeException("URLEncoder.encode() failed for " + s);
}
}
For example, on my Nexus 7 device, this directly opens the official Twitter app:
If official Twitter app is not installed and user either selects Chrome or it opens automatically (as the only app which can handle the intent):
The solutions posted before, allow you to post directly on your first twitter app. To show a list of twitters app (if there are more then one), you can custom your Intent.createChooser to show only the Itents you want.
The trick is add EXTRA_INITIAL_INTENTS to the default list, generated from the createChoose, and remove the others Intents from the list.
Look at this sample where I create a chooser that shows only my e-mails apps. In my case appears three mails: Gmail, YahooMail and the default Mail.
private void share(String nameApp, String imagePath) {
List<Intent> targetedShareIntents = new ArrayList<Intent>();
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/jpeg");
List<ResolveInfo> resInfo = getPackageManager().queryIntentActivities(share, 0);
if (!resInfo.isEmpty()){
for (ResolveInfo info : resInfo) {
Intent targetedShare = new Intent(android.content.Intent.ACTION_SEND);
targetedShare.setType("image/jpeg"); // put here your mime type
if (info.activityInfo.packageName.toLowerCase().contains(nameApp) ||
info.activityInfo.name.toLowerCase().contains(nameApp)) {
targetedShare.putExtra(Intent.EXTRA_TEXT, "My body of post/email");
targetedShare.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(imagePath)) );
targetedShare.setPackage(info.activityInfo.packageName);
targetedShareIntents.add(targetedShare);
}
}
Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Select app to share");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
startActivity(chooserIntent);
}
}
You can run like that: share("twi", "/sdcard/dcim/Camera/photo.jpg");
This was based on post: Custom filtering of intent chooser based on installed Android package name
This question is a bit older, but since I have just come across a similar problem, it may also still be of interest to others. First, as mentioned by Peter, create your intent:
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.putExtra(Intent.EXTRA_TEXT, "Test; please ignore");
tweetIntent.setType("application/twitter");
"application/twitter" is in fact a known content type, see here. Now, when you try to start an activity with this intent, it will show all sorts of apps that are not really Twitter clients, but want a piece of the action. As already mentioned in a couple of the "why do you even want to do that?" sort of answers, some users may find that useful. On the other hand, if I have a button in my app that says "Tweet this!", the user would very much expect this to bring up a Twitter client.
Which means that instead of just launching an activity, we need to filter out the ones that are appropriate:
PackageManager pm = getPackageManager();
List<ResolveInfo> lract
= pm.queryIntentActivities(tweetIntent,
PackageManager.MATCH_DEFAULT_ONLY);
boolean resolved = false;
for(ResolveInfo ri: lract)
{
if(ri.activityInfo.name.endsWith(".SendTweet"))
{
tweetIntent.setClassName(ri.activityInfo.packageName,
ri.activityInfo.name);
resolved = true;
break;
}
}
You would need to experiment a bit with the different providers, but if the name ends in ".SendTweet" you are pretty safe (this is the activity name in Twidroyd). You can also check your debugger for package names you want to use and adjust the string comparison accordingly (i.e. Twidroyd uses "com.twidroid.*").
In this simple example we just pick the first matching activity that we find. This brings up the Twitter client directly, without the user having to make any choices. If there are no proper Twitter clients, we revert to the standard activity chooser:
startActivity(resolved ? tweetIntent :
Intent.createChooser(tweetIntent, "Choose one"));
You could expand the code and take into account the case that there is more than one Twitter client, when you may want to create your own chooser dialog from all the activity names you find.
It is entirely possible your users will only ever, now and forever, only want to post to Twitter.
I would think that it is more likely that your users want to send information to people, and Twitter is one possibility. But, they might also want to send a text message, or an email, etc.
In that case, use ACTION_SEND, as described here. Twidroid, notably, supports ACTION_SEND, so it will appear in the list of available delivery mechanisms.
These answers are all overly complex.
If you just do a normal url Intent that does to Twitter.com, you'll get this screen:
which gives you the option of going to the website if you have no Twitter apps installed.
String url = "https://twitter.com/intent/tweet?source=webclient&text=TWEET+THIS!";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
Either
You start an activity with an Intent with action Intent.ACTION_SEND and the text/plain MIME type. You'll have all applications that support sending text. That should be any twitter client, as well as Gmail, dropbox, etc.
Or, you try to look up for the specific action of every client you are aware of, like "com.twitter.android.PostActivity" for the official client. That will point to this client, and that is unlikely to be a complete list.
Or, you start with the second point, and fall back on the first...
Nope. The intent type is something like image/png or application/pdf, i.e. a file type, and with createChooser you're basically asking which apps can open this file type.
Now, there's no such thing as an application/twitter file that can be opened, so that won't work. I'm not aware of any other way you can achieve what you want either.
From http://twidroid.com/plugins/
Twidroid’s ACTION_SEND intent
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is a sample message via Public Intent");
sendIntent.setType("application/twitter");
startActivity(Intent.createChooser(sendIntent, null));
I used "billynomates" answer and was able to use hashtags by using the "URLEncoder.encode(, "UTF-8")" function. The hash tags showed up just fine.
String originalMessage = "some message #MESSAGE";
String originalMessageEscaped = null;
try {
originalMessageEscaped = String.format(
"https://twitter.com/intent/tweet?source=webclient&text=%s",
URLEncoder.encode(originalMessage, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(originalMessageEscaped != null) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(originalMessageEscaped));
startActivity(i);
}
else {
// Some Error
}

Categories

Resources