Android enables intelligent robot chat
Background: In fact, it is accidental to implement chatbots. The company needs to build an ios version robot to automatically buy things, and then ios develops one, I think this kind of robot is very interesting. I want to know how to implement it, so I went to Baidu. This is an artifact and I need to make good use of it.
I. Old Rules: go first
Ii. Principle Analysis
1. Access the Turing robot api
2. send and receive network request messages based on APIs
3. Complete the layout page
4. Achieve conversations with the little guy
Iii. instance cutting (source code Display)
1. turing robot is a very powerful and easy-to-use platform. When we implement intelligent robot chat, we rely on its powerful api to implement our chat function and chat for us, soup, Doudou, haha.
Turing robot access api address: http://www.tuling123.com/openapi/cloud/access_api.jsp
From the website of the Turing machine, we can see that one of his request methods is a get, an assembly url, and then the data in gson format is returned, which is really simple and convenient, just do what it says.
2. receiving and sending api request messages (Tool class)
(1) configuration class
Package com. robot. tools;/*** configuration class ** @ author zengtao May 5, 2015 7:59:42 */public class Config {public static final String URL_KEY = http://www.tuling123.com/openapi/api;public static final String APP_KEY = 817259da4b7b4f105d1ca8d3072ed7ab ;}
(2) date tools
Package com. robot. tools; import android. annotation. suppressLint; import java. text. simpleDateFormat; import java. util. date;/*** time formatting tool ** @ author zengtao May 6, 2015 3:27:14 */public class DateUtils {@ SuppressLint (SimpleDateFormat) public static String dateToString (Date date) {SimpleDateFormat df = new SimpleDateFormat (yyyy-MM-dd HH: mm: ss); return df. format (date );}}
(3) http request Tool
Package com. robot. tools; 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. robot. bean. chatMessage; import com. robot. bean. chatMessage. type; import com. robot. bean. result;/*** htt P tool class ** @ author zengtao May 5, 2015 7:59:15 */public class HttpUtils {/*** send a message to the server ** @ param message *: sent message * @ return: message object */public static ChatMessage sendMessage (String message) {ChatMessage chatMessage = new ChatMessage (); String gsonResult = doGet (message); Gson gson = new Gson (); result result = null; if (gsonResult! = Null) {try {result = gson. fromJson (gsonResult, Result. class); chatMessage. setMessage (result. getText ();} catch (Exception e) {chatMessage. setMessage (the server is busy. Please try again later ...);}} chatMessage. setData (new Date (); chatMessage. setType (Type. INCOUNT); return chatMessage;}/*** get request ** @ param message *: Sent * @ return: Data */public static String doGet (String message) {String result =; String url = setParmat (message ); System. out. println (------------ url = + url); InputStream is = null; ByteArrayOutputStream baos = null; try {URL urls = new URL (url); HttpURLConnection connection = (HttpURLConnection) urls. openConnection (); connection. setReadTimeout (5*1000); connection. setConnectTimeout (5*1000); connection. setRequestMethod (GET); is = connection. getInputStream (); baos = new ByteArrayOutputStream (); int len =-1; byte [] bu Ff = new byte [1024]; while (len = is. read (buff ))! =-1) {baos. write (buff, 0, len);} baos. flush (); result = new String (baos. toByteArray ();} catch (Exception e) {e. printStackTrace ();} finally {if (is! = Null) {try {is. close () ;}catch (IOException e) {e. printStackTrace () ;}} if (baos! = Null) {try {baos. close ();} catch (IOException e) {e. printStackTrace () ;}} return result;}/*** set the parameter ** @ param message *: information * @ return: url */private static String setParmat (String message) {String url =; try {url = Config. URL_KEY +? + Key = + Config. APP_KEY + & info = + URLEncoder. encode (message, UTF-8);} catch (UnsupportedEncodingException e) {e. printStackTrace ();} return url ;}}
3. Compiling object classes
(1) results returned by the Turing Robot
Package com. robot. bean;/*** ing the results returned by the server ** @ author zengtao May 6, 2015 9:50:52 */public class Result {private int code; // code private String text; // information public int getCode () {return code;} public void setCode (int code) {this. code = code;} public String getText () {return text;} public void setText (String text) {this. text = text ;}}
(2) entity class of chat Information
Package com. robot. bean; import java. util. date;/*** entity class of chat information ** @ author zengtao May 6, 2015 9:47:01 */public class ChatMessage {private String name; // name private String message; // message private Type type; // Type: 0. sender 1. recipient private Date data; // time public ChatMessage () {} public ChatMessage (String message, Type type, Date data) {super (); this. message = message; this. type = type; this. data = data;} public String getName () {return name;} public void setName (String name) {this. name = name;} public String getMessage () {return message;} public void setMessage (String message) {this. message = message;} public Type getType () {return type;} public void setType (Type type) {this. type = type;} public Date getData () {return data;} public void setData (Date data) {this. data = data;} public enum Type {INCOUNT, OUTCOUNT }}
4. layout implementation
(1) Implementation of left Layout
(2) layout on the right of the chat
(3) Main Interface (chat interface) Layout
5. Chat information Adapter
Package com. robot. adapter; import java. util. list; import android. annotation. suppressLint; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widget. baseAdapter; import android. widget. textView; import com. robot. bean. chatMessage; import com. robot. bean. chatMessage. type; import com. robot. tools. dateUtils; import com. robot. ui. r;/*** chat information adapter ** @ author zengtao May 6, 2015 2:25:10 */public class ChatMessageAdapter extends BaseAdapter {private List
List; public ChatMessageAdapter (List
List) {this. list = list;} @ Overridepublic int getCount () {return list. isEmpty ()? 0: list. size () ;}@ Overridepublic Object getItem (int position) {return list. get (position) ;}@ Overridepublic long getItemId (int position) {return position ;}@ Overridepublic int getItemViewType (int position) {ChatMessage chatMessage = list. get (position); // if the message is received: 0, the message is sent: 1if (chatMessage. getType () = Type. INCOUNT) {return 0;} return 1 ;}@ Overridepublic int getViewTypeCount () {return 2 ;}@ SuppressLint (InflateParams) @ Overridepublic View getView (int position, View convertView, viewGroup parent) {ChatMessage chatMessage = list. get (position); if (convertView = null) {ViewHolder viewHolder = null; // load different la s using ItemType if (getItemViewType (position) = 0) {convertView = LayoutInflater. from (parent. getContext ()). inflate (R. layout. list_chat_left_item, null); viewHolder = new ViewHolder (); viewHolder. chat_time = (TextView) convertView. findViewById (R. id. chat_left_time); viewHolder. chat_message = (TextView) convertView. findViewById (R. id. chat_left_message);} else {convertView = LayoutInflater. from (parent. getContext ()). inflate (R. layout. list_chat_right_item, null); viewHolder = new ViewHolder (); viewHolder. chat_time = (TextView) convertView. findViewById (R. id. chat_right_time); viewHolder. chat_message = (TextView) convertView. findViewById (R. id. chat_right_message);} convertView. setTag (viewHolder);} // sets the data ViewHolder h_= (ViewHolder) convertView. getTag (); Vl. chat_time.setText (DateUtils. dateToString (chatMessage. getData (); FLAC. chat_message.setText (chatMessage. getMessage (); return convertView;}/*** internal class: Search for only one control ** @ author zengtao 2:27:57, January 1, May 6, 2015 */private class ViewHolder {private TextView chat_time, chat_message ;}}
6. Main Interface call
Package com. robot. ui; import java. util. arrayList; import java. util. date; import java. util. list; import android. annotation. suppressLint; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. text. textUtils; import android. view. view; import android. view. view. onClickListener; import android. view. window; import android. widget. button; import android. widget. editText; import android. widget. listView; import android. widget. toast; import com. robot. adapter. chatMessageAdapter; import com. robot. bean. chatMessage; import com. robot. bean. chatMessage. type; import com. robot. tools. httpUtils; public class MainActivity extends Activity {private List
List; private ListView chat_listview; private EditText chat_input; private Button chat_send; private ChatMessageAdapter chatAdapter; private ChatMessage chatMessage = null; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); requestWindowFeature (Window. FEATURE_NO_TITLE); setContentView (R. layout. main_activity); initView (); initListener (); initData ();} // 1. initial Attempt to private void initView () {// 1. initialize chat_listview = (ListView) findViewById (R. id. chat_listview); chat_input = (EditText) findViewById (R. id. chat_input_message); chat_send = (Button) findViewById (R. id. chat_send);} // 2. set the listening event private void initListener () {chat_send.setOnClickListener (onClickListener);} // 3. initialize data private void initData () {list = new ArrayList
(); List. add (new ChatMessage (hello, you can help me !, Type. INCOUNT, new Date (); chatAdapter = new ChatMessageAdapter (list); chat_listview.setAdapter (chatAdapter); chatAdapter. notifyDataSetChanged ();} // 4. send message chat private void chat () {// 1. final String send_message = chat_input.getText (). toString (). trim (); if (TextUtils. isEmpty (send_message) {Toast. makeText (MainActivity. this, sorry, you have not sent any message, Toast. LENGTH_SHORT ). show (); return;} // 2. the self-input content is also a record, refresh the record ChatMessage sendChatMessage = new ChatMessage (); sendChatMessage. setMessage (send_message); sendChatMessage. setData (new Date (); sendChatMessage. setType (Type. OUTCOUNT); list. add (sendChatMessage); chatAdapter. notifyDataSetChanged (); chat_input.setText (); // 3. send your message to the server and return the data new Thread () {public void run () {ChatMessage chat = HttpUtils. sendMessage (send_message); Message message = new Message (); message. what = 0x1; message. obj = chat; handler. sendMessage (message );};}. start () ;}@ SuppressLint (HandlerLeak) private Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {if (msg. what = 0x1) {if (msg. obj! = Null) {chatMessage = (ChatMessage) msg. obj;} // Add data to the list to update the data list. add (chatMessage); chatAdapter. notifyDataSetChanged () ;}};}; // click event listening OnClickListener onClickListener = new OnClickListener () {@ Overridepublic void onClick (View v) {switch (v. getId () {case R. id. chat_send: chat (); break ;}}};}
7. Of course, remember the permission issues in AndroidManifest. xml.
Iv. Summary
In the above cases, the so-called intelligent robot KO has been changed, and our little girl has finished it. Now you can start to tease her, but don't let it go. It's not good if you smoke. Of course, our little girl can also add many functions. You can choose to add the language function or something. If there is any implementation, I beg to share it, I also learn and learn. Every day I write code, every day I write code, and every day I write code into my mind.