1. 程式人生 > >Android使用百度翻譯api

Android使用百度翻譯api

一直想試用一下百度翻譯的介面,前些天從網上看了一篇關於json的部落格,突然想試一下百度翻譯api,於是我做了一個使用百度翻譯api的Android小程式。

首先要使用百度翻譯(也可以使用有道翻譯)必須要有一個userkey,至於如何去申請userkey,還有請求的規則什麼的,這裡不再介紹,網站上寫的都非常清楚。廢話不多說下面直接說開發過程:

1、首先做一個介面出來(至於介面如何做,自己隨意就好):edittext用於接收要翻譯的內容,button用於傳送請求,textview用於顯示翻譯好的內容。


2、由於是連線百度翻譯介面,所以聯網是必須的,這裡最好寫一個檢查網路的類,我這裡簡單寫一個出來:

public class NetworkStatus {

         publicstatic boolean isNetworkAvailable(Activity activity) {

                   Contextcontext = activity.getApplicationContext();

                   ConnectivityManagerconnectivityManager = (ConnectivityManager) context

                                     .getSystemService(Context.CONNECTIVITY_SERVICE);

                   if(connectivityManager == null) {

                            returnfalse;

                   }else {

                            NetworkInfo[]networkInfo = connectivityManager.getAllNetworkInfo();

                            if(networkInfo != null && networkInfo.length > 0) {

                                     for(int i = 0; i < networkInfo.length; i++) {

                                               if(networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {

                                                        returntrue;

                                               }

                                     }

                            }

                   }

                   returnfalse;

         }

}

3、onclick方法,拼接請求字串,(對字串的處理,我建議還是自己寫一下比較好點,我這裡只是為了試驗一下,所以寫的很簡單。。。)


4、從網站上讀取資料並顯示:

private void fanYi(final Stringstr) {

                   newAsyncTask<String, Void, String>() {

                            @Override

                            protectedString doInBackground(String... params) {

                                     try{

                                               URLurl = new URL(params[0]);

                                               HttpURLConnectionconnection = (HttpURLConnection) url

                                                                 .openConnection();

                                               InputStreamis = connection.getInputStream();

                                               InputStreamReaderisr = new InputStreamReader(is, "utf-8");

                                               BufferedReaderbf = new BufferedReader(isr);

                                               Stringline;

                                               StringBuffersb = new StringBuffer();

                                               while((line = bf.readLine()) != null) {

                                                        System.out.println(line);

                                                        sb.append(line);

                                               }

                                               bf.close();

                                               isr.close();

                                               is.close();

                                               JSONObjectjsonObject = new JSONObject(sb.toString());

                                               JSONArraytrans_result = jsonObject

                                                                 .getJSONArray("trans_result");

                                               StringBufferafterText = new StringBuffer();

                                               for(int i = 0; i < trans_result.length(); i++) {

                                                        JSONObjectjo = trans_result.optJSONObject(i);

                                                        afterText.append(jo.getString("dst"));

                                               }

                                               textAfter= afterText.toString();

                                     }catch (Exception e) {

                                               e.printStackTrace();

                                     }

                                     returnparams[0];

                            }

                            @Override

                            protectedvoid onPostExecute(String result) {

                                     //TODO Auto-generated method stub

                                     tvTextAfter.setText(textAfter);

//                                  super.onPostExecute(result);

                            }

                   }.execute(str);

         }

5、注意:

這個程式需要聯網並讀取網路連線情況所以就要新增兩個許可權:

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

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

一定要注意轉換編碼格式,不然會出現亂碼。

                          ps:這個寫的好的話,完全可以寫一個翻譯APP自己來使用啊。我是小白,寫的不好的地方,大家指正啊。