【Android】图灵聊天机器人

打包好的apk:http://url.cn/SQ2wBy
1.登陆图灵机器人官网,打开接入文档,查看API接入的使用方法
2.通过get方式访问,格式是:url?key=Key&info=请输入你想知道的内容
3.返回一个Json数据,格式是{"code":xxx,"text":xxx}
4.解释Json的数据,截取text的内容,用ListView显示到屏幕上
【Android】图灵聊天机器人_第1张图片
Httpdata.java(AsyncTask异步线程类,以GET方式访问api,并将返回的数据通过接口传给Activity)
public class Httpdata extends AsyncTask<String, Void, String>{

	private HttpClient mHttpClient;
	private HttpGet mHttpGet;
	private HttpResponse mHttpResponse;
	private HttpEntity mHttpEntity;
	private InputStream in;
	private HttpDatalistener listener;
	
	private String url;
	public Httpdata(String url,HttpDatalistener listener) {
		this.url = url;
		this.listener = listener;
	}
	
	protected String doInBackground(String... params) {
		try {
			mHttpClient = new DefaultHttpClient();
			mHttpGet = new HttpGet(url);
			mHttpResponse = mHttpClient.execute(mHttpGet);
			mHttpEntity = mHttpResponse.getEntity();
			in = mHttpEntity.getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			return sb.toString();
		} catch (Exception e) {
		}
		
		return null;
	}
	@Override
	protected void onPostExecute(String result) {
		listener.getDataUrl(result);
		super.onPostExecute(result);
	}
}

HttpDatalistener.java(接口类,将返回的Json数据传给Activity)
//用于将返回的Json数据传给Activity
public interface HttpDatalistener {
	void getDataUrl(String data);
}

ListData.java(用于存放获得的每一条数据对象)
//存放每一条内容的对象 
public class ListData {
	//判断是发送者还是接收者,用于显示头像
	public static final int SEND = 1;
	public static final int RECEIVER = 2;
	//与SEND或RECEIVER作判断
	private int flag;
	//存放系统时间
	private String time;
	//存放最终输出的内容
	private String content;
	
	public ListData(String content,int flag,String time) {
		setFlag(flag);
		setContent(content);	
		setTime(time);
	}
	
	public String getContent(){
		return content;
	}
	
	public void setContent(String content){
		this.content = content;
	}
	
	public void setFlag(int flag){
		this.flag = flag;
	}
	
	public int getFlag(){
		return this.flag;
	}

	public String getTime() {
		return time;
	}

	public void setTime(String time) {
		this.time = time;
	}
}

TextAdapter.java(BaseAdapter子类,用与控制ListView的显示样式)
//用于控制ListView的显示样式
public class TextAdapter extends BaseAdapter {

	private List<ListData> lists;
	private Context mContext;
	private RelativeLayout layout;
	
	public TextAdapter(List<ListData> lists,Context mContext) {
		this.lists = lists;
		this.mContext = mContext;
	}
	
	public int getCount() {
		return lists.size();
	}

	public Object getItem(int arg0) {
		return lists.get(arg0);
	}

	public long getItemId(int arg0) {
		return arg0;
	}

	//根据flag来判断发言者,并设置对应listview的布局界面
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		LayoutInflater inflater = LayoutInflater.from(mContext);
		if(lists.get(arg0).getFlag() == ListData.RECEIVER){
			layout = (RelativeLayout) inflater.inflate(R.layout.leftitem, null);
		}
		if (lists.get(arg0).getFlag() == ListData.SEND) {
			layout = (RelativeLayout) inflater.inflate(R.layout.rightitem, null);
		} 
		TextView tv = (TextView) layout.findViewById(R.id.tv);
		TextView time = (TextView) layout.findViewById(R.id.time);
		tv.setText(lists.get(arg0).getContent());
		time.setText(lists.get(arg0).getTime());
		return layout;
	}

}

MainActivity.java
public class MainActivity extends Activity implements HttpDatalistener,OnClickListener{

	private Httpdata htmldata;
	private List<ListData> lists;
	private ListView lv;
	private EditText getText;
	private Button send_btn;
	private String content_str;
	private TextAdapter adapter;
	private String [] welcome_array;
	private double currentTime,oldTime = 0;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		initView();	
	}
	
	//初始化界面
	private void initView(){
		lv = (ListView) findViewById(R.id.lv);
		getText = (EditText) findViewById(R.id.sendText);
		send_btn = (Button) findViewById(R.id.send_btn);
		
		lists = new ArrayList<ListData>();
		send_btn.setOnClickListener(this);
		adapter = new TextAdapter(lists, this);
		lv.setAdapter(adapter);
		ListData l;
		l = new ListData(getRandomWelcomeTips(), ListData.RECEIVER,getTime());
		lists.add(l);
	}
	
	//设置随机欢迎标题
	private String getRandomWelcomeTips(){
		String welcome_tips = null;
		welcome_array = this.getResources().getStringArray(R.array.welcome_tips);
		int index = (int) (Math.random()*(welcome_array.length - 1));
		welcome_tips = welcome_array[index];
		return welcome_tips;
	}

	//将返回的Json数据中的text数据截取出来
	public void getDataUrl(String data) {
		getContent(data);
	}
	public void getContent(String str){
		try {
			JSONObject jb = new JSONObject(str);
			ListData listData;
			listData = new ListData(jb.getString("text"),ListData.RECEIVER,getTime());
			lists.add(listData);
			adapter.notifyDataSetChanged();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	//点击时触发,html的Get方法线程
	public void onClick(View arg0) {
		getTime();
		content_str = getText.getText().toString();
		getText.setText("");
		//自动忽略输入的空格和回车
		String dropk = content_str.replace(" ", "");
		String droph = dropk.replace("\n", "");
		ListData listData;
		listData = new ListData(content_str, ListData.SEND,getTime());
		//如果超过30条对话,则删除
		if(lists.size()>30){
			for (int i = 0; i < lists.size(); i++) {
				lists.remove(i);
			}
		}
		lists.add(listData);
		adapter.notifyDataSetChanged();
		htmldata = (Httpdata) new Httpdata("http://www.tuling123.com/openapi/api?key=3f919fb92a6002468bab30da6bfaa71c&info="+content_str, this).execute();		
	}
	
	//获取系统当前时间,每隔5分钟显示一次
	private String getTime(){
		currentTime = System.currentTimeMillis();
		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		Date curDate = new Date();
		String str = format.format(curDate);
		if (currentTime - oldTime >= 500) {
			oldTime = currentTime;
			return str;
		} else {
			return "";
		}
	}
}

leftitem.xml(左边时的ListView显示样式)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <TextView 
        android:id="@+id/time"
        android:layout_width="fill_parent"
        android:gravity="center_horizontal"
        android:layout_height="wrap_content"
     />
    
	<ImageView
	    android:layout_below="@id/time"
	    android:id="@+id/iv"
	    android:layout_width="70dp"
	    android:layout_height="70dp"
	    android:padding="10dp"
	    android:src="@drawable/robot"
	/>
	
	<TextView 
	    android:layout_below="@id/time"
	    android:layout_marginRight="50dp"
	    android:id="@+id/tv"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:layout_toRightOf="@id/iv"
	    android:background="@drawable/aio_friend_bg_nor_11"
	    android:gravity="center"/>
	
</RelativeLayout>



你可能感兴趣的:(【Android】图灵聊天机器人)