Android之Android studio實現智慧聊天機器人
Android實現智慧聊天機器人
最近在做專案中,突然來了靈感,要做一個聊天機器人.聊天機器人在很多大型App上都有使用,比如QQ群裡的QQ小冰,淘寶京東等App上在沒有人工客服之前會有機器人跟你聊天,根據你發的問題關鍵詞,向你推薦一些答案,可以省下很多人工的時間以及減小伺服器的壓力
此功能主要原理
1.接入圖靈機器人api,拼接上你輸入框的訊息;
2.根據api完成網路請求訊息的接收與傳送
3.完成佈局頁面
4.實現和你小蜜的對話
廢話不多說,直接上圖和程式碼
一:老規矩,先上效果圖
二:註冊圖靈機器人,獲取api
1.進入圖靈機器人官網註冊,已有賬號的可直接登入
2.點選建立機器人
3.在建立機器人時,根據自己的需求,選擇即可
4.建立好機器人之後會得到一個Api地址和一個ApiKey(如圖所示)
5.下面就要拼接Api地址了(拼接方法如圖所示)
拼接方法:
http://www.tuling123.com/openapi/api?key=你自己的apikey&info=你要傳送的話&userid=你自己的唯一標示
三.下面就是具體實現的程式碼了
6.配置類,配置自己的圖靈機器人(Config)
/** * author:Created by ZhangPengFei. * data: 2017/12/28 * 配置類 */ public class Config { public static final String URL_KEY = "http://www.tuling123.com/openapi/api"; public static final String APP_KEY = "38026ee35d614607b29c4ef3a56474a7";//此處是你申請的Apikey }
7.格式化日期時間的工具類,用於顯示時間(DateUtils)
import android.annotation.SuppressLint; import java.text.SimpleDateFormat; import java.util.Date; /** * author:Created by ZhangPengFei. * data: 2017/12/28 * 時間格式化工具類 */ 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); } }
8.HttpUtils網路請求類(HttpUtils)
import com.google.gson.Gson;
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;
/**
* author:Created by ZhangPengFei.
* data: 2017/12/28
* http工具類
*/
public class HttpUtils {
/**
* 傳送訊息到伺服器
*
* @param message :傳送的訊息
* @return:訊息物件
*/
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("伺服器繁忙,請稍候再試...");
}
}
chatMessage.setData(new Date());
chatMessage.setType(ChatMessage.Type.INCOUNT);
return chatMessage;
}
/**
* get請求
*
* @param message :傳送的話
* @return:資料
*/
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[] buff = 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;
}
/**
* 設定引數
*
* @param message : 資訊
* @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;
}
}
9.請求api地址返回的資料(Result)
/**
* author:Created by ZhangPengFei.
* data: 2017/12/28
* 對映伺服器返回的結果
*/
public class Result {
private int code; // code碼
private String text; // 資訊
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;
}
}
10.聊天訊息的實體類(ChatMessage)
import java.util.Date;
/**
* author:Created by ZhangPengFei.
* data: 2017/12/28
* 聊天訊息的實體類
*/
public class ChatMessage {
private String name;// 姓名
private String message;// 訊息
private Type type;// 型別:0.傳送者 1.接受者
private Date data;// 時間
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
}
}
11.伺服器傳送與接收訊息,左邊佈局的實現(layout_left)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:background="#f5f5f5"
android:id="@+id/chat_left_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingTop="5dp"
android:textSize="14sp"
android:text="2015/5/6 12:10:13" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/chat_left_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/ser" />
<TextView
android:id="@+id/chat_left_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:text="小蜜"
android:textSize="16sp" />
</LinearLayout>
<TextView
android:layout_marginLeft="10dp"
android:background="@drawable/kefuborder"
android:gravity="center"
android:textSize="16sp"
android:layout_gravity="center_vertical"
android:id="@+id/chat_left_message"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:text="您好。" />
</LinearLayout>
</LinearLayout>
12.客戶端傳送與接收訊息,右邊佈局的實現(layout_right)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/chat_right_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#f5f5f5"
android:paddingTop="5dp"
android:text="2015/5/6 12:10:13"
android:textSize="14sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="horizontal" >
<TextView
android:id="@+id/chat_right_message"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginRight="10dp"
android:background="@drawable/myborder"
android:gravity="center"
android:text="can i help me ?"
android:textSize="16sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/chat_right_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/m" />
<TextView
android:id="@+id/chat_right_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:layout_marginTop="5dp"
android:text="zengtao"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
13.主介面聊天頁面佈局的實現(activity_chat)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bac"
android:orientation="vertical" >
<!-- 頭部 -->
<RelativeLayout
android:id="@+id/chat_top"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#3A4449" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="小蜜"
android:textColor="#ffffff"
android:textSize="18sp" />
</RelativeLayout>
<!-- 底部 -->
<RelativeLayout
android:id="@+id/chat_bottom"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true"
android:background="#3A4449" >
<EditText
android:id="@+id/chat_input_message"
android:layout_width="240dp"
android:background="@drawable/shuruborder"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:gravity="center" />
<Button
android:background="@drawable/btnborder"
android:id="@+id/chat_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/chat_input_message"
android:text="傳送"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</RelativeLayout>
<!-- 中間 -->
<ListView
android:id="@+id/chat_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/chat_bottom"
android:layout_below="@id/chat_top"
android:divider="@null"
android:dividerHeight="3dp" >
</ListView>
</RelativeLayout>
14.聊天訊息的介面卡(ChatMessageAdapter)
/**
* author:Created by ZhangPengFei.
* data: 2017/12/28
*/
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 java.util.List;
import weektest.project.R;
/**
* 聊天資訊介面卡
*
* @author zengtao 2015年5月6日 下午2:25:10
*/
public class ChatMessageAdapter extends BaseAdapter {
private List<ChatMessage> list;
public ChatMessageAdapter(List<ChatMessage> list) {
this.list = list;
}
@Override
public int getCount() {
return list.isEmpty() ? 0 : list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
ChatMessage chatMessage = list.get(position);
// 如果是接收訊息:0,傳送訊息:1
if (chatMessage.getType() == ChatMessage.Type.INCOUNT) {
return 0;
}
return 1;
}
@Override
public int getViewTypeCount() {
return 2;
}
@SuppressLint("InflateParams")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessage chatMessage = list.get(position);
if (convertView == null) {
ViewHolder viewHolder = null;
// 通過ItemType載入不同的佈局
if (getItemViewType(position) == 0) {
convertView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.layout_left, 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.layout_right, 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);
}
// 設定資料
ViewHolder vh = (ViewHolder) convertView.getTag();
vh.chat_time.setText(DateUtils.dateToString(chatMessage.getData()));
vh.chat_message.setText(chatMessage.getMessage());
return convertView;
}
/**
* 內部類:只尋找一次控制元件
*
* @author zengtao 2015年5月6日 下午2:27:57
*/
private class ViewHolder {
private TextView chat_time, chat_message;
}
}
15.主java的實現(ChatActivity)
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 java.util.ArrayList;
import java.util.Date;
import java.util.List;
import weektest.project.R;
public class ChatActivity extends Activity {
private List<ChatMessage> list;
private ListView chat_listview;
private EditText chat_input;
private Button chat_send;
private ChatMessageAdapter chatAdapter;
private ChatMessage chatMessage = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_chat);
initView();
initListener();
initData();
}
// 1.初始試圖
private void initView() {
// 1.初始化
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.設定監聽事件
private void initListener() {
chat_send.setOnClickListener(onClickListener);
}
// 3.初始化資料
private void initData() {
list = new ArrayList<ChatMessage>();
list.add(new ChatMessage("您好,小乖為您服務!", ChatMessage.Type.INCOUNT, new Date()));
chatAdapter = new ChatMessageAdapter(list);
chat_listview.setAdapter(chatAdapter);
chatAdapter.notifyDataSetChanged();
}
// 4.傳送訊息聊天
private void chat() {
// 1.判斷是否輸入內容
final String send_message = chat_input.getText().toString().trim();
if (TextUtils.isEmpty(send_message)) {
Toast.makeText(ChatActivity.this, "對不起,您還未傳送任何訊息",
Toast.LENGTH_SHORT).show();
return;
}
// 2.自己輸入的內容也是一條記錄,記錄重新整理
ChatMessage sendChatMessage = new ChatMessage();
sendChatMessage.setMessage(send_message);
sendChatMessage.setData(new Date());
sendChatMessage.setType(ChatMessage.Type.OUTCOUNT);
list.add(sendChatMessage);
chatAdapter.notifyDataSetChanged();
chat_input.setText("");
// 3.傳送你的訊息,去伺服器端,返回資料
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;
}
// 新增資料到list中,更新資料
list.add(chatMessage);
chatAdapter.notifyDataSetChanged();
}
};
};
// 點選事件監聽
OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.chat_send:
chat();
break;
}
}
};
}
17.當然別忘記了許可權與依賴問題
<uses-permission android:name="android.permission.INTERNET" /> <!-- 網路許可權 -->
compile 'com.google.code.gson:gson:2.2.4'//Gson解析依賴
18.寫了這麼多,就把圖片和繪製的形狀一塊給你們吧,
①.輸入框的樣式(shuruborder)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="#FFF" />
<solid android:color="#FFF" />
<corners android:radius="5dip" />
</shape>
②.小蜜聊天框的樣式(kefuborder)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="#5188DE" />
<solid android:color="#A5D932" />
<corners android:radius="8dip" />
</shape>
③.自己聊天框的樣式(myborder)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="1dp"
android:color="#787878" />
<solid android:color="#FFFFFF" />
<corners android:radius="8dip" />
</shape>
④.傳送按鈕的樣式(btnborder)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#CCCCCC"/>
<corners android:radius="5dip"/>
</shape>
⑤.用到的圖片
背景圖(bac.png)小蜜頭像(ser.png)
自己的頭像(m.png)
19.現在的話我們的造人計劃已經基本完成了,現在就可以跟你造好的聊天玩耍,
自己造的,玩的時候小心一點,玩壞就不好了.
相關推薦
Android之Android studio實現智慧聊天機器人
Android實現智慧聊天機器人 最近在做專案中,突然來了靈感,要做一個聊天機器人.聊天機器人在很多大型App上都有使用,比如QQ群裡的QQ小冰,淘寶京東等App上在沒有人工客服之前會有機器人跟你聊天,根據你發的問題關鍵詞,向你推薦一些答案,可以省下很多人工的時間以及減小伺
安卓實現智慧聊天機器人(結合百度語音和圖靈機器人)
package com.ysk.tldemo; //提問/回答 public class TalkBean { public TalkBean(String content, int image
android智慧聊天機器人
本人是某211高校計算機研究生研一的學生,自學android已經接近一年,做過幾個android的小專案,平時都是學習大牛的部落格,學習別人的程式碼,學習別人方法,得到了許多經驗和提高,我覺得現在也是我回報大家的時候啦,這是我第一次寫部落格,一方面記錄重要的程式
Android之Android studio基本除錯和快捷鍵
第一種除錯方法: 如果APP是單程序,直接debug執行,如下圖 第二種除錯方法: 第二種就是除錯當前已經處於執行狀態下的App,這也是我們用的更多的一種除錯手段,即Attach debugger
android之ViewPager簡單實現區域性頁面滑動效果
-Viewpager能實現什麼效果? -實現左右滑動,切換view的效果。 -既可以實現整個頁面左右滑動,也可以實現同一個頁面中區域性左右滑動。 搞清楚viewpager的作用後,開始寫一個簡單例子,實現同一個頁面中區域性滑動的效果。 在coding前要做的準備工作 2
Android之Android studio如何解決Multiple dex files define Landroid/support/a(檔案重複引用錯誤)
先爆錯誤的圖片照,如下 define 可以理解檔案重複的意思,所以這個錯誤是我匯入了v4.jar包的原因,因為我專案裡面本來就有v7.jar,如下圖 解決辦法一:
android之用scrollview實現控制元件滑動固定效果
專案中最近用到需要佈局滑動到某一個地方的時候某個控制元件固定在螢幕頂部不動,就去研究了下,思路其實挺簡單的。我置頂的懸浮控制元件上邊還需要留個控制元件,比如搜尋框之類的,專案需求不一樣就留的不一樣,所以就研究了一下,網上也有很多,其實方法思路都一樣的,很簡單,自定義一下Sc
如何讓聊天機器人能夠實現自我學習功能呢?(智慧聊天機器人序言)
傳統的aiml是通過配置aiml語料檔案來匹配聊天對話。這種模式需要大量的aiml語料檔案,而且都是初始時就固定好這些預料檔案。那麼我們能否設計一種能夠擁有自我學習完善功能的聊天機器人呢?在aiml語言的基礎上再進一步延伸,使聊天機器人能夠自我完善學習,豐富自己語料庫。1:初
Android之XML方式實現漸變動畫
Android漸變動畫(AlphaAnimation) 漸變動畫的就是一個檢視在透明度上的漸變效果,其中他的主要屬性有 1、fromAlpha動畫的其實時的透明度,值取在0.0-1.0之間 2、toAlpha 動畫結束時透明度,取值在0.0-1.0之間 3、duratio
Arcgis For Android之離線地圖實現的幾種方式
ArcGIS for Android離線資料編輯實現原理 實現ArcGIS for Android上的離線資料編輯,具體實現環境及其步驟如下: 一、 環境準備 1. 軟體環境 1) ArcGIS Server10用於釋出地圖服務 2) ArcGIS Des
Android 仿微信實現語音聊天功能
在此感謝鴻洋大神,因為我這是在慕課上看大神的視訊做出來的。程式碼中我已經添加了很多很多註釋,不光是為了大家,也是為了自己能夠更加透徹的理解該功能支援原創,也不算原創了哈哈~注意注意:Android 6.0動態獲取錄音許可權,我並沒有加上,所以你們需要在寫完程式碼後,執行時在許
android之videoplayer視訊實現示例收集
1,效果圖 地址:專案地址 2, 3, 4, 5 6 8 9 收集: 自定義floatview,無需申明懸浮框許可權,利用WindowManager T
Android之用Handler實現主執行緒和子執行緒互相通訊以及子執行緒和子執行緒之間的通訊
1、上程式碼 activity_main.xml檔案 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.
Android之Handler:實現計時器例項
通常情況下,當應用程式啟動時,Android首先會開啟一個主執行緒 (也就是UI執行緒) , 主執行緒為管理介面中的UI控制元件,進行事件分發。如果此時需要一個耗時的操作,例如:聯網讀取資料,或者讀取本地較大的一個檔案的時候,你不能把這些操作放在主執行緒中,如果
【打死不做程式設計師】python3+qqBot+圖靈機器人實現qq聊天機器人
原理: 通過Python3的qqBot開源庫,基於騰訊的smartQQ協議登入個人QQ,實現監控、收集QQ訊息,進而通過圖靈機器人API接入方式實現自動聊天。 零、前期準備: 1、Python3 2、qqBot & requests & re 3、
微信小程式連線圖靈API實現智慧聊天(超級簡單)
小程式的demo.wxml <view class='top'>{{tittle}}</view> <view class='que' > <block wx:for="{{syas}}" wx:for-item="it
Android之Android WebView常見問題及解決方案彙總
就目前而言,如何應對版本的頻繁更新呢,又如何靈活多變地展示我們的介面呢,這又涉及到了web app與native app之間孰優孰劣的爭論. 於是乎,一種混合型的app誕生了,靈活多變的部分,如淘寶商城首頁的活動頁面,一集凡客誠品中我們都可以見到web 頁面與native頁面
簡易DIY智慧聊天機器人
前言 大二忙裡偷閒,花了一個月左右自己利用了Python+ESP8266 DIY 了一個智慧聊天機器人,呼叫的是圖靈機器人的體驗API,現在把DIY過程記錄下來,希望能分享給別的對這方面有興趣的人。 DIY前的準備 1.STM32F429IG作為主控晶片 2.ESP8
android之android.intent.category.DEFAULT的用途和使用
原文:http://blog.csdn.net/jason0539/article/details/100498991. 要弄清楚這個問題,首先需要弄明白什麼是implicit(隱藏) intent什麼是explicit(明確) intent。 Explicit Int
Android之android:theme設定在Application 和 Activity的區別
在Android Manifest中,theme可以定義<application>或<activity>,主要區別是: 前者將主題新增到整個程式,後者指定到某個 Activity。 <application android:theme=