非常感谢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 package com.TANK.temperature; 2 3 import java.util.ArrayList; 4 import java.util.Date; 5 import java.util.List; 6 7 import android.app.Activity; 8 import android.content.Context; 9 import android.os.Bundle; 10 import android.os.Handler; 11 import android.os.Message; 12 import android.text.TextUtils; 13 import android.view.View; 14 import android.view.Window; 15 import android.view.inputmethod.InputMethodManager; 16 import android.widget.EditText; 17 import android.widget.ListView; 18 import android.widget.Toast; 19 20 import com.TANK.temperature.Utils.HttpUtils; 21 import com.TANK.temperature.bean.ChatMessage; 22 import com.TANK.temperature.bean.ChatMessage.Type; 23 import com.TANK.temperature.Utils.HttpUtils; 24 25 public class PikaqiuActivity extends Activity { 26 /** 27 * 展示消息的listview 28 * */ 29 private ListView mChatView; 30 /** 文本域 */ 31 private EditText mMsg; 32 33 private List<ChatMessage> mDatas = new ArrayList<ChatMessage>(); 34 35 private ChatMessageAdapter mAdapter; 36 37 private Handler mHandler = new Handler() { 38 public void handleMessage(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 @Override 49 protected void onCreate(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 void initView() { 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 void sendMessage(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 = new ChatMessage(Type.OUTPUT, msg); 75 to.setDate(new Date()); 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 new Thread() { 91 public void run() { 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
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