欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  技术分享

Android调用百度翻译API实现中英智能翻译源代码Demo下载

程序员文章站 2022-03-01 12:55:02
...

本Demo是一个基于Android的简单在线翻译app应用项目源码、调用了百度翻译的接口、通过直接带入字符串的方式进行翻译、可以翻译单个文字也可以翻译一段话、同时支持英文翻译成中文、其实就是中英文互相翻译的、更多相关的Api可以参考百度的开发文档、下面是效果图

Android调用百度翻译API实现中英智能翻译源代码Demo下载


onCreate中检测网络

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_fanyi);

    if (NetworkStatus.isNetworkAvailable(this)) {
        Toast.makeText(getApplicationContext(), "当前网络可用", Toast.LENGTH_LONG)
                .show();
    } else {
        Toast.makeText(getApplicationContext(), "当前网络不可用!",
                Toast.LENGTH_LONG).show();
    }
    findViews();

}


翻译核心代码

private void fanYi(final String str) {

    new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                InputStream is = connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader bf = new BufferedReader(isr);
                String line;
                StringBuffer sb = new StringBuffer();
                while ((line = bf.readLine()) != null) {
                    System.out.println(line);
                    sb.append(line);
                }
                bf.close();
                isr.close();
                is.close();
                JSONObject jsonObject = new JSONObject(sb.toString());
                JSONArray trans_result = jsonObject
                        .getJSONArray("trans_result");
                StringBuffer afterText = new StringBuffer();
                for (int i = 0; i < trans_result.length(); i  ) {
                    JSONObject jo = trans_result.optJSONObject(i);
                    afterText.append(jo.getString("dst"));
                }
                textAfter = afterText.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return params[0];
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            tvTextAfter.setText(textAfter);
            //super.onPostExecute(result);
        }
    }.execute(str);
    
}


源代码下载链接: http://dwtedx.com/download.html?bdkey=s/1kUn5zj5 密码: 4d9f