调用图灵机器人API实现Android智能机器人

非常感谢CSDN博客上的鸿洋哥,他贴出的源码是我所做的工作的基础,鸿洋哥博客链接http://blog.csdn.net/lmj623565791/article/details/38498353

下面入正题:

Android智能机器人的实现

调用图灵机器人API实现Android智能机器人

效果图

一、概述

所谓实现了Android智能服务机器人,只是实现了一个可以调用图灵机器人API的工具,并为其加上聊天背景的壳子。

二、知识点补充(小白必看)

1.LayoutInflater:

它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等),具体作用:a、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;b、对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。

2.Adapter相关内容

相关内容参见 http://blog.chinaunix.net/uid-11898547-id-3303153.html

3.URLEncoder和URLDecoder

具体参见:http://www.java3z.com/cwbwebhome/article/article2/2414.html

4.HttpURLConnection

具体参见:http://www.blogjava.net/supercrsky/articles/247449.html

5.InputStream中的read()与read()

具体参见:http://www.cnblogs.com/pengyingh/articles/2507207.html

6.Button点击事件的三种方式

具体参见:http://www.2cto.com/kf/201501/369003.html

7.handler和thread的使用

具体参见:http://blog.csdn.net/lanpy88/article/details/6659630

在此贴个主要代码:
主Activity和访问API两个Java源码

主activity:

 package com.TANK.temperature;

 import java.util.ArrayList;
import java.util.Date;
import java.util.List; import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast; import com.TANK.temperature.Utils.HttpUtils;
import com.TANK.temperature.bean.ChatMessage;
import com.TANK.temperature.bean.ChatMessage.Type;
import com.TANK.temperature.Utils.HttpUtils; public class PikaqiuActivity extends Activity {
/**
* 展示消息的listview
* */
private ListView mChatView;
/** 文本域 */
private EditText mMsg; private List<ChatMessage> mDatas = new ArrayList<ChatMessage>(); private ChatMessageAdapter mAdapter; private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
ChatMessage from = (ChatMessage) msg.obj;
mDatas.add(from);
mAdapter.notifyDataSetChanged();
mChatView.setSelection(mDatas.size() - 1); } }; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.chat_main);
initView();
mAdapter = new ChatMessageAdapter(this, mDatas);
mChatView.setAdapter(mAdapter); } private void initView() {
// TODO Auto-generated method stub
mChatView = (ListView) findViewById(R.id.id_chat_listView);
mMsg = (EditText) findViewById(R.id.id_chat_msg);
mDatas.add(new ChatMessage(Type.INPUT, "皮卡皮卡"));
} public void sendMessage(View view) { final String msg = mMsg.getText().toString();
if (TextUtils.isEmpty(msg)) {
Toast.makeText(this, "还没有填写信息o...", Toast.LENGTH_SHORT).show();
return;
} ChatMessage to = new ChatMessage(Type.OUTPUT, msg);
to.setDate(new Date());
mDatas.add(to);
mAdapter.notifyDataSetChanged();
mChatView.setSelection(mDatas.size() - 1); mMsg.setText(""); /** 软键盘控制 */
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
InputMethodManager.HIDE_NOT_ALWAYS); } new Thread() {
public void run() {
ChatMessage from = null;
try {
from = HttpUtils.sendMsg(msg); } catch (Exception e) {
// TODO: handle exception
from = new ChatMessage(Type.INPUT, "服务器已挂...");
}
Message message = Message.obtain();
message.obj = from;
mHandler.sendMessage(message); } }.start();
}
}

访问图灵机器人API

package com.TANK.temperature.Utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date; import com.google.gson.Gson;
import com.TANK.temperature.bean.ChatMessage;
import com.TANK.temperature.bean.ChatMessage.Type;
import com.TANK.temperature.bean.CommonException;
import com.TANK.temperature.bean.Result; public class HttpUtils {
private static String API_KEY = "bb090f183940018147decf8f1858d3f9";
private static String URL = "http://www.tuling123.com/openapi/api"; /**
* 发送一个消息,并得到返回的消息
*
* @param msg
* @return
*/
public static ChatMessage sendMsg(String msg) {
ChatMessage message = new ChatMessage();
String url = setParams(msg);
String res = doGet(url);
Gson gson = new Gson();
Result result = gson.fromJson(res, Result.class); if (result.getCode() > 400000 || result.getText() == null
|| result.getText().trim().equals("")) {
message.setMsg("该功能等待开发...");
} else {
message.setMsg(result.getText());
}
message.setType(Type.INPUT);
message.setDate(new Date()); return message;
} /**
* 拼接Url
*
* @param msg
* @return
*/
private static String setParams(String msg) {
/** 利用Java中URLEncoder对其进行编码,如果不能实现,抛出异常 */
try {
msg = URLEncoder.encode(msg, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return URL + "?key=" + API_KEY + "&info=" + msg;
} /**
* Get请求,获得返回数据
*
* @param urlStr
* @return
*/
private static String doGet(String urlStr) {
URL url = null;
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5 * 1000);
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode() == 200) { //判断服务器是否成功处理了请求
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) { //从输入流中读取一定数量的字节,如果流位于文件末尾而没有可用的字节将会返回-1;
baos.write(buf, 0, len);
}
baos.flush(); //刷新,将缓冲区内容全部输出
return baos.toString();
} else {
throw new CommonException("服务器连接错误!");
} } catch (Exception e) {
e.printStackTrace();
throw new CommonException("服务器连接错误!");
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
} try {
if (baos != null)
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
} } }

提供两个源码下载:鸿洋哥源码(机器人): http://yunpan.cn/cHTDFM8jpR3dX  访问密码 00f5

我的源码(机器人+百度全景地图):http://yunpan.cn/cHTDdsyG52wSK  访问密码 ce29

上一篇:redhat6.9安装oracle11.2.0.4 PRCF-2010


下一篇:CString-int-string-char-BSTR之间的转换