非常感谢CSDN博客上的鸿洋哥,他贴出的源码是我所做的工作的基础,鸿洋哥博客链接http://blog.csdn.net/lmj623565791/article/details/38498353
下面入正题:
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:
1 packagecom.TANK.temperature;2
3 importjava.util.ArrayList;4 importjava.util.Date;5 importjava.util.List;6
7 importandroid.app.Activity;8 importandroid.content.Context;9 importandroid.os.Bundle;10 importandroid.os.Handler;11 importandroid.os.Message;12 importandroid.text.TextUtils;13 importandroid.view.View;14 importandroid.view.Window;15 importandroid.view.inputmethod.InputMethodManager;16 importandroid.widget.EditText;17 importandroid.widget.ListView;18 importandroid.widget.Toast;19
20 importcom.TANK.temperature.Utils.HttpUtils;21 importcom.TANK.temperature.bean.ChatMessage;22 importcom.TANK.temperature.bean.ChatMessage.Type;23 importcom.TANK.temperature.Utils.HttpUtils;24
25 public class PikaqiuActivity extendsActivity {26 /**
27 * 展示消息的listview28 **/
29 privateListView mChatView;30 /**文本域*/
31 privateEditText mMsg;32
33 private List mDatas = new ArrayList();34
35 privateChatMessageAdapter mAdapter;36
37 private Handler mHandler = newHandler() {38 public voidhandleMessage(android.os.Message msg) {39 ChatMessage from =(ChatMessage) msg.obj;40 mDatas.add(from);41 mAdapter.notifyDataSetChanged();42 mChatView.setSelection(mDatas.size() - 1);43
44 }45
46 };47
48 @Override49 protected voidonCreate(Bundle savedInstanceState) {50 super.onCreate(savedInstanceState);51 requestWindowFeature(Window.FEATURE_NO_TITLE);52 setContentView(R.layout.chat_main);53 initView();54 mAdapter = new ChatMessageAdapter(this, mDatas);55 mChatView.setAdapter(mAdapter);56
57 }58
59 private voidinitView() {60 //TODO Auto-generated method stub
61 mChatView =(ListView) findViewById(R.id.id_chat_listView);62 mMsg =(EditText) findViewById(R.id.id_chat_msg);63 mDatas.add(new ChatMessage(Type.INPUT, "皮卡皮卡"));64 }65
66 public voidsendMessage(View view) {67
68 final String msg =mMsg.getText().toString();69 if(TextUtils.isEmpty(msg)) {70 Toast.makeText(this, "还没有填写信息o...", Toast.LENGTH_SHORT).show();71 return;72 }73
74 ChatMessage to = newChatMessage(Type.OUTPUT, msg);75 to.setDate(newDate());76 mDatas.add(to);77 mAdapter.notifyDataSetChanged();78 mChatView.setSelection(mDatas.size() - 1);79
80 mMsg.setText("");81
82 /**软键盘控制*/
83 InputMethodManager imm =(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);84 if(imm.isActive()) {85 imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,86 InputMethodManager.HIDE_NOT_ALWAYS);87
88 }89
90 newThread() {91 public voidrun() {92 ChatMessage from = null;93 try{94 from =HttpUtils.sendMsg(msg);95
96 } catch(Exception e) {97 //TODO: handle exception
98 from = new ChatMessage(Type.INPUT, "服务器已挂...");99 }100 Message message =Message.obtain();101 message.obj =from;102 mHandler.sendMessage(message);103
104 }105
106 }.start();107 }108 }
访问图灵机器人API
packagecom.TANK.temperature.Utils;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.UnsupportedEncodingException;importjava.net.HttpURLConnection;importjava.net.URL;importjava.net.URLEncoder;importjava.util.Date;importcom.google.gson.Gson;importcom.TANK.temperature.bean.ChatMessage;importcom.TANK.temperature.bean.ChatMessage.Type;importcom.TANK.temperature.bean.CommonException;importcom.TANK.temperature.bean.Result;public classHttpUtils {private static String API_KEY = "bb090f183940018147decf8f1858d3f9";private static String URL = "http://www.tuling123.com/openapi/api";/*** 发送一个消息,并得到返回的消息
*
*@parammsg
*@return
*/
public staticChatMessage sendMsg(String msg) {
ChatMessage message= newChatMessage();
String url=setParams(msg);
String res=doGet(url);
Gson gson= newGson();
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(newDate());returnmessage;
}/*** 拼接Url
*
*@parammsg
*@return
*/
private staticString 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请求,获得返回数据
*
*@paramurlStr
*@return
*/
private staticString doGet(String urlStr) {
URL url= null;
HttpURLConnection conn= null;
InputStream is= null;
ByteArrayOutputStream baos= null;try{
url= newURL(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= newByteArrayOutputStream();int len = -1;byte[] buf = new byte[128];while ((len = is.read(buf)) != -1) { //从输入流中读取一定数量的字节,如果流位于文件末尾而没有可用的字节将会返回-1;
baos.write(buf, 0, len);
}
baos.flush();//刷新,将缓冲区内容全部输出
returnbaos.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
原文:http://www.cnblogs.com/ALLENGF/p/4863444.html