首页 > 代码库 > Android智能聊天机器人

Android智能聊天机器人

http://www.tuling123.com/       注册一个账号,申请一个KEY值。此网站也有文档,可以查看。

  1 package com.tulingdemo;  2   3 import java.text.SimpleDateFormat;  4 import java.util.ArrayList;  5 import java.util.Date;  6 import java.util.List;  7 import org.json.JSONException;  8 import org.json.JSONObject;  9 import com.tulingdemo.R; 10 import android.app.Activity; 11 import android.os.Bundle; 12 import android.view.View; 13 import android.view.View.OnClickListener; 14 import android.widget.Button; 15 import android.widget.EditText; 16 import android.widget.ListView; 17  18 public class MainActivity extends Activity implements HttpGetDataListener, 19         OnClickListener { 20  21     private HttpData httpData; 22     private List<ListData> lists; 23     private ListView lv; 24     private EditText sendtext; 25     private Button send_btn; 26     private String content_str; 27     private TextAdapter adapter; 28     private String[] welcome_array; 29     // 做比对时间;老时间 30     private double currentTime = 0, oldTime = 0; 31  32     @Override 33     protected void onCreate(Bundle savedInstanceState) { 34         super.onCreate(savedInstanceState); 35         setContentView(R.layout.activity_main); 36         initView(); 37     } 38  39     private void initView() { 40         lv = (ListView) findViewById(R.id.lv); 41         sendtext = (EditText) findViewById(R.id.sendText); 42         send_btn = (Button) findViewById(R.id.send_btn); 43         lists = new ArrayList<ListData>(); 44         send_btn.setOnClickListener(this); 45         adapter = new TextAdapter(lists, this); 46         lv.setAdapter(adapter); 47         ListData listData; 48         listData = http://www.mamicode.com/new ListData(getRandomWelcomeTips(), ListData.RECEIVER, 49                 getTime()); 50         lists.add(listData); 51     } 52  53     /** 用户第一次进入,随机获取欢迎语 */ 54     private String getRandomWelcomeTips() { 55         String welcome_tip = null; 56         welcome_array = this.getResources() 57                 .getStringArray(R.array.welcome_tips); 58         int index = (int) (Math.random() * (welcome_array.length - 1)); 59         welcome_tip = welcome_array[index]; 60         return welcome_tip; 61     } 62  63     @Override 64     public void getDataUrl(String data) { 65         parseText(data); 66     } 67  68     public void parseText(String str) { 69         try { 70             JSONObject jb = new JSONObject(str); 71             // System.out.println(jb.getString("code")); 72             // System.out.println(jb.getString("text")); 73             ListData listData; 74             listData = http://www.mamicode.com/new ListData(jb.getString("text"), ListData.RECEIVER, 75                     getTime()); 76             lists.add(listData); 77             adapter.notifyDataSetChanged(); 78         } catch (JSONException e) { 79             e.printStackTrace(); 80         } 81     } 82  83     @Override 84     public void onClick(View v) { 85         getTime(); 86         content_str = sendtext.getText().toString(); 87         sendtext.setText(""); 88         // 去掉空格 89         String dropk = content_str.replace(" ", ""); 90         // 去掉回车 91         String droph = dropk.replace("\n", ""); 92         ListData listData; 93         listData = http://www.mamicode.com/new ListData(content_str, ListData.SEND, getTime()); 94         lists.add(listData); 95         if (lists.size() > 30) { 96             for (int i = 0; i < lists.size(); i++) { 97                 // 移除数据 98                 lists.remove(i); 99             }100         }101         adapter.notifyDataSetChanged();102         httpData = http://www.mamicode.com/(HttpData) new HttpData(103                 "http://www.tuling123.com/openapi/api?key=6af9822f5491fadfc142b53818bbd63a&info="104                         + droph, this).execute();105     }106 107     /** 获取时间 */108     private String getTime() {109         currentTime = System.currentTimeMillis();110         SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");111         Date curDate = new Date();112         String str = format.format(curDate);113         // 如果超过5分钟.114         if (currentTime - oldTime >= 5 * 60 * 1000) {115             oldTime = currentTime;116             return str;117         } else {118             return "";119         }120 121     }122 }

 

activity_main.xml

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2     xmlns:tools="http://schemas.android.com/tools" 3     android:layout_width="match_parent" 4     android:layout_height="match_parent" 5     android:orientation="vertical" > 6  7     <!--  8          android:transcriptMode="alwaysScroll" 自动向下一直滚动。 9      -->10     <ListView11         android:id="@+id/lv"12         android:layout_width="fill_parent"13         android:layout_height="0dp"14         android:layout_weight="1"15         android:divider="@null"16         android:listSelector="@android:color/transparent"17         android:transcriptMode="alwaysScroll" />18 19     <LinearLayout20         android:layout_width="fill_parent"21         android:layout_height="wrap_content"22         android:orientation="horizontal" >23 24         <EditText25             android:id="@+id/sendText"26             android:layout_width="0dp"27             android:layout_height="wrap_content"28             android:layout_weight="1" />29         30         <Button 31             android:id="@+id/send_btn"32             android:layout_width="wrap_content"33             android:layout_height="wrap_content"34             android:text="@string/send" />35     </LinearLayout>36 37 </LinearLayout>

 

 1 package com.tulingdemo; 2  3 import java.util.List; 4 import com.tulingdemo.R; 5 import android.content.Context; 6 import android.view.LayoutInflater; 7 import android.view.View; 8 import android.view.ViewGroup; 9 import android.widget.BaseAdapter;10 import android.widget.RelativeLayout;11 import android.widget.TextView;12 13 public class TextAdapter extends BaseAdapter {14 15     private List<ListData> lists;16     private Context mContext;17     private RelativeLayout layout;18 19     public TextAdapter(List<ListData> lists, Context mContext) {20         this.lists = lists;21         this.mContext = mContext;22     }23 24     @Override25     public int getCount() {26         return lists.size();27     }28 29     @Override30     public Object getItem(int position) {31         return lists.get(position);32     }33 34     @Override35     public long getItemId(int position) {36         return position;37     }38 39     @Override40     public View getView(int position, View convertView, ViewGroup parent) {41         42         LayoutInflater inflater = LayoutInflater.from(mContext);43         44         if (lists.get(position).getFlag() == ListData.RECEIVER) {45             layout = (RelativeLayout) inflater.inflate(R.layout.leftitem, null);46         }47         if (lists.get(position).getFlag() == ListData.SEND) {48             layout = (RelativeLayout) inflater49                     .inflate(R.layout.rightitem, null);50         }51         TextView tv = (TextView) layout.findViewById(R.id.tv);52         TextView time = (TextView) layout.findViewById(R.id.time);53         tv.setText(lists.get(position).getContent());54         time.setText(lists.get(position).getTime());55         return layout;56     }57 58 }

 

leftitem.xml     接受信息

 1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout  3     xmlns:android="http://schemas.android.com/apk/res/android" 4     android:layout_width="match_parent" 5     android:layout_height="match_parent" > 6  7     <TextView 8         android:id="@+id/time" 9         android:layout_width="fill_parent"10         android:layout_height="wrap_content"11         android:gravity="center_horizontal" />12 13     <ImageView14         android:id="@+id/iv"15         android:layout_width="70dp"16         android:layout_height="70dp"17         android:layout_below="@id/time"18         android:padding="10dp"19         android:src="@drawable/robot" />20 21     <TextView22         android:id="@+id/tv"23         android:layout_width="wrap_content"24         android:layout_height="wrap_content"25         android:layout_below="@id/time"26         android:layout_marginRight="50dp"27         android:layout_toRightOf="@id/iv"28         android:background="@drawable/aio_friend_bg_nor_11"29         android:gravity="center" />30 31 </RelativeLayout>

 

rightitem.xml      发送信息

 1 <?xml version="1.0" encoding="utf-8"?> 2 <RelativeLayout  3     xmlns:android="http://schemas.android.com/apk/res/android" 4     android:layout_width="match_parent" 5     android:layout_height="match_parent" > 6  7     <TextView 8         android:id="@+id/time" 9         android:layout_width="fill_parent"10         android:layout_height="wrap_content"11         android:gravity="center_horizontal" />12 13     <ImageView14         android:id="@+id/iv"15         android:layout_width="70dp"16         android:layout_height="70dp"17         android:layout_alignParentRight="true"18         android:layout_below="@id/time"19         android:padding="10dp"20         android:src="@drawable/visitor" />21 22     <TextView23         android:id="@+id/tv"24         android:layout_width="wrap_content"25         android:layout_height="wrap_content"26         android:layout_below="@id/time"27         android:layout_marginLeft="50dp"28         android:layout_toLeftOf="@id/iv"29         android:background="@drawable/aio_user_bg_nor_11"30         android:gravity="center" />31 32 </RelativeLayout>

 

 1 package com.tulingdemo; 2  3 import java.io.BufferedReader; 4 import java.io.InputStream; 5 import java.io.InputStreamReader; 6 import org.apache.http.HttpEntity; 7 import org.apache.http.HttpResponse; 8 import org.apache.http.client.HttpClient; 9 import org.apache.http.client.methods.HttpGet;10 import org.apache.http.impl.client.DefaultHttpClient;11 import android.os.AsyncTask;12 13 public class HttpData extends AsyncTask<String, Void, String>{14 15     private HttpClient mHttpClient;16     private HttpGet mHttpGet;17     private HttpResponse mHttpResponse;18     private HttpEntity mHttpEntity;19     private InputStream in;20     private HttpGetDataListener listener;21     22     private String url;23     public HttpData(String url,HttpGetDataListener listener) {24         this.url = url;25         this.listener = listener;26     }27     28     @Override29     protected String doInBackground(String... params) {30         try {31             mHttpClient = new DefaultHttpClient();32             mHttpGet = new HttpGet(url);33             mHttpResponse = mHttpClient.execute(mHttpGet);34             mHttpEntity = mHttpResponse.getEntity();35             in = mHttpEntity.getContent();36             BufferedReader br = new BufferedReader(new InputStreamReader(in));37             String line = null;38             StringBuffer sb = new StringBuffer();39             while ((line = br.readLine()) != null) {40                 sb.append(line);41             }42             return sb.toString();43         } catch (Exception e) {44         }45         return null;46     }47     @Override48     protected void onPostExecute(String result) {49         listener.getDataUrl(result);50         super.onPostExecute(result);51     }52 }

 

1 package com.tulingdemo;2 3 public interface HttpGetDataListener {4     void getDataUrl(String data);5 }

 

 1 package com.tulingdemo; 2  3 public class ListData { 4      5     public static final int SEND = 1;      // 发送 6     public static final int RECEIVER = 2;  // 接收 7     private String content; 8     // 标识,判断是左边,还是右边。 9     private int flag;    10     private String time;11     12     public ListData(String content,int flag,String time) {13         setContent(content);14         setFlag(flag);15         setTime(time);16     }17     18     public String getContent() {19         return content;20     }21     public void setContent(String content) {22         this.content = content;23     }24     public int getFlag() {25         return flag;26     }27     public void setFlag(int flag) {28         this.flag = flag;29     }30     public String getTime() {31         return time;32     }33     public void setTime(String time) {34         this.time = time;35     }36 }

 

strings.xml

 1 <?xml version="1.0" encoding="utf-8"?> 2 <resources> 3  4     <string name="app_name">小灵机器人</string> 5     <string name="hello_world">Hello world!</string> 6     <string name="action_settings">Settings</string> 7     <string name="send">发送</string> 8      9     <!-- 欢迎语 -->10     <string-array name="welcome_tips">11         <item>主人,奴婢在此等候多时了</item>12         <item>主人,近来一切可好</item>13         <item>亲爱的,我想死你了</item>14         <item>欢迎归来,我亲爱的主人</item>15         <item>我是小灵机器人,很高兴为您服务</item>16     </string-array>17 18 </resources>

 

完整代码下载:http://pan.baidu.com/s/1pJJR8JD

 

Android智能聊天机器人