目录
1.进入有道智云主页,注册自己的账号(手机号验证码),完善信息随意填
2.登录进来后,创建应用。根据需要选择语言翻译服务。
3. 打开Android Studio,新建空的Activity项目
1. 新建项目,在build.gradle(app)添加retrofit依赖
2. 打开有道云文本翻译API接入文档,找到json文件示例
3.新建一个接口类,获取json文件
4. 新建一个接口实现类来获取Call<>
5.更改activity_main.xml布局文件
6. drawable文件夹中添加edit_border.xml
7.在values文件夹中添加arrays.xml文件
8.更改mainactivity文件
9.在Manifest.xml中添加网络权限
4.现在就可以运行了
1.进入有道智云主页,注册自己的账号(手机号验证码),完善信息随意填
记得领取赠送的50元体验金(能用好久)
2.登录进来后,创建应用。根据需要选择语言翻译服务。我这里接入方式是API接入,因为用的是retrofit。注意IP地址不要填写,直接为空,就不会有IP限制
创建完成后,记下应用ID和应用密钥,等会会用到
3. 打开Android Studio,新建空的Activity项目 1. 新建项目,在build.gradle(app)添加retrofit依赖implementation 'com.squareup.retrofit2:retrofit:2.4.0' implementation 'com.squareup.retrofit2:converter-gson:2.4.0'2. 打开有道云文本翻译API接入文档,找到json文件示例
( AndroidStudio下载一个GsonFormatPlus插件)
新建Java类来接收这个json文件,Alt+Insert或者右键选择Generate,选择GsonFormatPlus,会跳出这样一个对话框
将API接入文档中的json文件示例复制粘贴到左边空白栏,点击OK就会自动生成代码。
3.新建一个接口类,获取json文件import retrofit2.Call; import retrofit2.http.POST; import retrofit2.http.Query; public interface GetResult { @POST("api") CallgetTextRes(@Query("from") String from, @Query("to") String to, @Query("appKey") String ID, @Query("salt") String salt, @Query("sign") String sign, @Query("signType") String signType, @Query("curtime") String curtime, @Query("q") String q); }
Call
import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class TextTranslator { String q; public TextTranslator(String s) { this.q = s; } static String APP_KEY = "你的应用ID", signType = "v3"; static final String APP_SECRET = "你的应用密钥"; static String base_URL = "https://openapi.youdao.com/"; public Call5.更改activity_main.xml布局文件getCall(String from, String to) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(base_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); final GetResult getR = retrofit.create(GetResult.class); String salt = String.valueOf(System.currentTimeMillis()); String curtime = String.valueOf(System.currentTimeMillis() / 1000); String sign = getDigest(APP_KEY + truncate(q) + salt + curtime + APP_SECRET); return getR.getTextRes(from, to, APP_KEY, salt, sign, signType, curtime, q); } private static String truncate(String q) { if (q == null) { return null; } int len = q.length(); return len <= 20 ? q : (q.substring(0, 10) + len + q.substring(len - 10, len)); } private static String getDigest(String string) { if (string == null) { return null; } char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; byte[] btInput = string.getBytes(StandardCharsets.UTF_8); try { MessageDigest mdInst = MessageDigest.getInstance("SHA-256"); mdInst.update(btInput); byte[] md = mdInst.digest(); int j = md.length; char[] str = new char[j * 2]; int k = 0; for (byte byte0 : md) { str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (NoSuchAlgorithmException e) { return null; } } }
6. drawable文件夹中添加edit_border.xml
7.在values文件夹中添加arrays.xml文件
8.更改mainactivity文件- 自动检测
- 英文 → 中文
- 中文 → 英文
- 中文 → 日语
- 中文 → 韩语
- 中文 → 法语
- 中文 → 俄语
- 20sp
- 0dp
- 0dp
- @drawable/edit_border
import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { EditText trans; TextView transTv, expTv; Button search; LinearLayout transLi, expLi; String exp, tran, pho; String from = "auto", to = "auto", q; TextRes tr; Spinner spinner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); clickAndListener(); } private void init() { trans = findViewById(R.id.trans); transTv = findViewById(R.id.trans_tv); expTv = findViewById(R.id.exp_tv); search = findViewById(R.id.search); transLi = findViewById(R.id.trans_l); expLi = findViewById(R.id.exp_l); spinner = findViewById(R.id.lan_spinner); } private void clickAndListener() { search.setonClickListener(v -> textResult()); trans.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (s.length() == 0) { transLi.setVisibility(View.GONE); expLi.setVisibility(View.GONE); } search.setVisibility(View.VISIBLE); } @Override public void afterTextChanged(Editable s) { } }); spinnerListener(); } private void textResult() { q = trans.getText().toString().trim(); TextTranslator t = new TextTranslator(q); Call9.在Manifest.xml中添加网络权限call = t.getCall(from, to); call.enqueue(new Callback () { @Override public void onResponse(@NonNull Call call, @NonNull Response response) { tr = response.body(); if (tr != null) { int code = tr.getErrorCode(); if (0 == code) { exp = tr.getExplains(); tran = tr.getTrans(); pho = tr.getUkPho(); if (pho != null) { transTv.setText(tran + pho); } else { transTv.setText(tran); } transLi.setVisibility(View.VISIBLE); search.setVisibility(View.GONE); if (!tran.equals(exp) && exp != null) { expTv.setText(exp); expLi.setVisibility(View.VISIBLE); } } else if (113 == code) { toaPrint("请输入翻译内容"); } else toaPrint("请求错误,错误码为:" + tr.getErrorCode()); } } @Override public void onFailure(@NonNull Call call, @NonNull Throwable t) { Log.i("TAG", "onFailure"); toaPrint("请检查网络设置!"); } }); } private void toaPrint(String s) { Toast.makeText(this, s, Toast.LENGTH_SHORT).show(); } private void spinnerListener() { spinner.setOnItemSelectedListener(new AdapterView.onItemSelectedListener() { @Override public void onItemSelected(AdapterView> parent, View view, int position, long id) { switch (position) { case 1://英文 → 中文 from = "en"; to = "zh-CHS"; break; case 2://中文 → 英文 from = "zh-CHS"; to = "en"; break; case 3://中文 → 日语 from = "zh-CHS"; to = "ja"; break; case 4://中文 → 韩语 from = "zh-CHS"; to = "ko"; break; case 5://中文 → 法语 from = "zh-CHS"; to = "fr"; break; case 6://中文 → 俄语 from = "zh-CHS"; to = "ru"; break; default: break; } } @Override public void onNothingSelected(AdapterView> parent) { } }); } }
4.现在就可以运行了
源码下载:GitHub - Beacon0423/Androidhttps://github.com/Beacon0423/Android
欢迎批评点赞
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)