Google 翻译/Android 错误

Google Translate / Android Error

我刚开始使用 Google 翻译 API 客户端库,在 AS 3.0.1 中使用 SDK 26/min 22,遵循 http://cloud.google.com/translate/docs/reference/libraries。在获得密钥并使用 gradle 应用程序文件安装库后,我正在使用他们建议的代码。

package com.example.xxx.simptrans;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class MainActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Context context = getApplicationContext();

        Translate translate = TranslateOptions.getDefaultInstance().getService();

        // The text to translate
        String text = "Hello, world!";

        // Translates some text into Russian
        Translation translation =
                translate.translate(
                        text,
                        TranslateOption.sourceLanguage("en"),
                        TranslateOption.targetLanguage("ru"));

        System.out.printf("Text: %s%n", text);
        System.out.printf("Translation: %s%n", translation.getTranslatedText());
    }
}

当我 运行 它时,我得到一个网络线程异常:

Caused by: android.os.NetworkOnMainThreadException 
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)......

我有,包括我的 AndroidManifest.xml-

<uses-permission android:name="android.permission.INTERNET" />

导致错误的原因是什么?谢谢。

尝试创建一个 AsyncTask class 然后用您要翻译的文本执行它。 因为问题可能是你试图通过主线程访问网络

class Translate extends AsyncTask<String, Void, String> {


    protected String doInBackground(String... params) {

         String text = params[0]; //text to translate
         Translate translate = TranslateOptions.getDefaultInstance().getService();
         Translation translation =
                translate.translate(
                    text,
                    TranslateOption.sourceLanguage("en"),
                    TranslateOption.targetLanguage("ru"));



         return translation.getTranslatedText();
    }

    //this method will run after doInBackground execution
    protected void onPostExecute(String result) {
     System.out.printf("Translation: %s%n", result);
    }


}

执行此 class :

Translate translate = new Translate();
String text = "Hello, world!";
System.out.printf("Text: %s%n", text);
translate.execute(text );