Android开发之使用AsyncTask实现实时翻译

Posted 骨灵冷

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android开发之使用AsyncTask实现实时翻译相关的知识,希望对你有一定的参考价值。

最近在做自己的安卓软件,于是乎就自己做了个翻译功能,主要方式是使用AsyncTask实现异步处理,翻译调用的互联网接口是有道提供的API。

方法很简单,通过HttpGET和HttpResponse获得String,再将json数据解析即可。

在AsynTask实现类中,输入是String,在doInBackground方法里主要实现目标String的获取。而在onPostExecute方法里主要实现获取后对结果result的处理与解析。

其他过程就没啥好说的了:具体代码如下:

package com.example.myallfunprojects;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.Manifest.permission;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class YouDaoTranslation extends Activity
	//控件
	private Button btn_translate;
	private EditText edit;
	private TextView tv_result;
	//判断是否有网络
	private ConnectivityManager connManager;
	private boolean hasNetwork = false;
	//进行有道翻译时用到的常量
	private String YouDaoBaseUrl = "http://fanyi.youdao.com/openapi.do";
	private String YouDaoDocType = "json";
	private String YouDaoVersion = "1.1";
	private String YouDaoType = "data";
	private String YouDaoKeyFrom = "MyAllFunction2";
	private String APIKey = "297337179";
	private String search_Content;
	
	//数据保存使用
	private String source_text = null;
	private String resultmessage = null;
	private SharedPreferences preference;
	private Editor editor;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.youdao_layout);
		init();
	
		preference = getPreferences(Context.MODE_PRIVATE);
		editor = preference.edit();
		
		edit.setText(preference.getString("source_text", ""));
		tv_result.setText(preference.getString("message", ""));
		//判断网络状态
		connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		btn_translate.setOnClickListener(new View.OnClickListener() 	
			@Override
			public void onClick(View v) 
				NetworkInfo netinfo = connManager.getActiveNetworkInfo();
				// TODO Auto-generated method stub
				//先检查网络状态
				if (netinfo == null)
				
					hasNetwork = false;
					Toast.makeText(getApplicationContext(), "当前不存在网络,请检查设置", 
							Toast.LENGTH_SHORT).show();
				
				else
				
					hasNetwork = true;
					search_Content = edit.getText().toString().trim();
					source_text = search_Content;
					new Translate_Asynctask().execute(search_Content);
				
			
		);
	
	
	public void init()
	
		btn_translate = (Button) findViewById(R.id.btn_translate);
		edit = (EditText) findViewById(R.id.et_text);
		tv_result = (TextView) findViewById(R.id.result_text);
	
	/**
	 * 通过Async实现异步操作
	 * @author sjm
	 *
	 */
	private class Translate_Asynctask extends AsyncTask<String, Void, String>
	
		//在执行时查询
		@Override
		protected String doInBackground(String... params) 
			// TODO Auto-generated method stub
			if (hasNetwork == false) 
				return null;
			
			String Url = YouDaoBaseUrl+"?keyfrom="+YouDaoKeyFrom+"&key="+APIKey+
					"&type="+YouDaoType+"&doctype="+YouDaoDocType+"&version="+YouDaoVersion+
					"&q="+params[0];
			String result = null;
			//HttpGet
			HttpGet httpGet = new HttpGet(Url);
			//使用execute方法发送HTTPGET请求,并获得HTTPResponse响应
			try 
				HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
				if (httpResponse.getStatusLine().getStatusCode() == 200) 
					 result = EntityUtils.toString(httpResponse.getEntity());				
				
			 catch (ClientProtocolException e) 
				// TODO Auto-generated catch block
				e.printStackTrace();
			 catch (IOException e) 
				// TODO Auto-generated catch block
				e.printStackTrace();
			
			return result;
		
		
		@Override
		protected void onCancelled() 
			// TODO Auto-generated method stub
			super.onCancelled();
		

		@Override
		protected void onCancelled(String result) 
			// TODO Auto-generated method stub
			super.onCancelled(result);
		

		@Override
		protected void onPostExecute(String result) 
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) 
				try 
					JSONArray jsonarray = new JSONArray("["+result+"]");
					String message = null;
					for (int i = 0; i < jsonarray.length(); i++) 
						JSONObject object = jsonarray.getJSONObject(i);
						if (object != null) 
							String errorCode = object.getString("errorCode");
							if (errorCode.equals("20")) 
								Toast.makeText(getApplicationContext(), "要翻译的文本过长", Toast.LENGTH_SHORT);
							
							else if (errorCode.equals("30")) 
								Toast.makeText(getApplicationContext(), "无法进行有效的翻译", Toast.LENGTH_SHORT);
							
							else if (errorCode.equals("40")) 
								Toast.makeText(getApplicationContext(), "不支持的语言类型", Toast.LENGTH_SHORT);
							
							else if (errorCode.equals("50")) 
								Toast.makeText(getApplicationContext(), "无效的key", Toast.LENGTH_SHORT);
							
							else
							
								//取得要翻译的内容
								String query = object.getString("query");
								message = query;
								String translation = object.getString("translation");
								message += "\\t"+translation;
								if (object.has("basic")) 
									JSONObject basic_object = object.getJSONObject("basic");
									if (basic_object.has("phonetic")) 
										String phonetic = basic_object.getString("phonetic");
										message += "\\n\\t"+ phonetic;
									
									if (basic_object.has("explains")) 
										String explains = basic_object.getString("explains");
										message += "\\n\\t" + explains;
									
								
								if (object.has("web")) 
									String web = object.getString("web");
									JSONArray webarray = new JSONArray("["+web+"]");
									message += "\\n网络释义:";
									JSONArray webArray = webarray.getJSONArray(0);
									int count = 0;
									while(!webArray.isNull(count))
										
										if (webArray.getJSONObject(count).has("key"))
										
											String key = webArray.getJSONObject(count).getString("key");
											message += "\\n\\t<"+(count+1)+">" + key;
										
										if (webArray.getJSONObject(count).has("value"))
										
											String value = webArray.getJSONObject(count).getString("value");
											message += "\\n\\t   " + value;
										
										count++;
									
								
							
						
					
					resultmessage = message;
					tv_result.setText(message);
					editor.putString("source_text", source_text);
					editor.putString("message", resultmessage);
					editor.commit();
				 catch (JSONException e) 
					// TODO Auto-generated catch block
					e.printStackTrace();
				
			
			else
				tv_result.setText("无网络,无法执行");
		

		@Override
		protected void onPreExecute() 
			// TODO Auto-generated method stub
			super.onPreExecute();
		

		@Override
		protected void onProgressUpdate(Void... values) 
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		
	
	



以上是关于Android开发之使用AsyncTask实现实时翻译的主要内容,如果未能解决你的问题,请参考以下文章

android 开发之AsyncTask

android源码解析之-->异步任务AsyncTask

Android之——AsyncTask和Handler对照

Android多线程分析之五:使用AsyncTask异步下载图像

Android开发学习之路-使用AsyncTask进行异步操作

Android开发之AsynTask的使用