本博客主要介绍了使用android studio接入图灵机器人,实现智能聊天机器人的功能。
<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/left_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingTop="5dp"
android:textSize="14sp" />
<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/left_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/shu" />
<TextView
android:id="@+id/left_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:text="小洛"
android:textSize="16sp" />
LinearLayout>
<TextView
android:layout_marginLeft="10dp"
android:background="@drawable/shuborder"
android:gravity="center"
android:textSize="16sp"
android:layout_gravity="center_vertical"
android:id="@+id/left_message"
android:layout_width="200dp"
android:layout_height="50dp">
LinearLayout>
LinearLayout>
<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/right_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#f5f5f5"
android:paddingTop="5dp"
android:textSize="14sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="horizontal" >
<TextView
android:id="@+id/right_message"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_gravity="center_vertical"
android:layout_marginRight="10dp"
android:background="@drawable/myborder"
android:gravity="center"
android:textSize="16sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="@+id/right_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="@drawable/my" />
<TextView
android:id="@+id/right_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginTop="5dp"
android:text="grape"
android:textSize="16sp" />
LinearLayout>
LinearLayout>
LinearLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
android:orientation="vertical" >
<RelativeLayout
android:id="@+id/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/downborder"
android:layout_height="50dp"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:gravity="center" />
<Button
android:background="@drawable/buttonborder"
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/input_message"
android:text="发送"
android:textColor="#FFFFFF"
android:textSize="18sp" />
RelativeLayout>
<ListView
android:id="@+id/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>
public class MyRobot {
public static final String URL_KEY = "http://www.tuling123.com/openapi/api";//获取图灵机器人官网地址
public static final String API_KEY = "044a24e728164414ba63c3efb1b3b9e9";//此处是你申请的图灵机器人apikey
}
import java.util.Date;
public class ChatMessage {
private String name;// 名字
private String message;//聊天信息
private Type type;// 类型
private Date date;// 时间
public ChatMessage() {
}
public ChatMessage(String message, Type type, Date date) {
super();
this.message = message;
this.type = type;
this.date = date;
}
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 getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public enum Type {
INCOUNT, OUTCOUNT
}
}
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;
}
}
import com.google.gson.Gson;//Google 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;
public class HttpRequest {
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);//从json数据(json格式字符串)转为java对象(解析数据)
chatMessage.setMessage(result.getText());//http连接获取的内容解析之后的结果给聊天信息赋值
}
catch (Exception e) {
chatMessage.setMessage("请求错误...");
}
}
chatMessage.setDate(new Date());
chatMessage.setType(ChatMessage.Type.INCOUNT);
return chatMessage;
}
public static String doGet(String message) {
String result = "";
String url = setParmat(message);
System.out.println("------------url = " + url);
InputStream input = null;
ByteArrayOutputStream output = null;
try {
//创建URL实例,打开URLConnection 创建连接
URL urls = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urls.openConnection();
//设置Connection参数
connection.setReadTimeout(5 * 1000);//读取超时
connection.setConnectTimeout(5 * 1000);//连接超时
connection.setRequestMethod("GET"); //使用GET提交模式
input = connection.getInputStream();
output = new ByteArrayOutputStream();//初始化字节数组输出流对象
int len = -1;
byte[] buff = new byte[1024];
while ((len = input.read(buff)) != -1) {//读取长度
output.write(buff, 0, len);// 将buff字节数组中从偏移量0开始的 len 个字节写入此字节数组输出流
}
output.flush();
result = new String(output.toByteArray());
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (input != null) {
try {
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (output != null) {
try {
output .close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
//拼接api地址
private static String setParmat(String message) {
String url = "";//api地址
try {
url =MyRobot.URL_KEY + "?" + "key=" + MyRobot.APi_KEY + "&info="
+ URLEncoder.encode(message, "UTF-8");
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url;
}
}
package com.example.chat;
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;
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;
// 加载布局
if (getItemViewType(position) == 0) {
convertView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.left, null);
viewHolder = new ViewHolder();
viewHolder.time = (TextView) convertView
.findViewById(R.id.left_time);
viewHolder.message = (TextView) convertView
.findViewById(R.id.message);
} else {
convertView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.right, null);
viewHolder = new ViewHolder();
viewHolder.time = (TextView) convertView
.findViewById(R.id.right_time);
viewHolder.message = (TextView) convertView
.findViewById(R.id.right_message);
}
convertView.setTag(viewHolder);
}
// 设置数据
ViewHolder vh = (ViewHolder) convertView.getTag();
vh.time.setText(DateUtils.dateToString(chatMessage.getDate()));
vh.message.setText(chatMessage.getMessage());
return convertView;
}
private class ViewHolder {
private TextView time, message;
}
}
package com.example.chat;
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;
public class ChatActivity extends Activity {
private List<ChatMessage> list;
private ListView listview;
private EditText input;
private Button 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.chat);
initView();
initListener();
initData();
}
// 初始视图
private void initView() {
listview = (ListView) findViewById(R.id.listview);
input = (EditText) findViewById(R.id.input_message);
send = (Button) findViewById(R.id.send);
}
// 设置监听事件
private void initListener() {
send.setOnClickListener(onClickListener);
}
// 初始化数据
private void initData() {
list = new ArrayList<ChatMessage>();
list.add(new ChatMessage("您好,小洛为您服务!", ChatMessage.Type.INCOUNT, new Date()));
chatAdapter = new ChatMessageAdapter(list);
listview.setAdapter(chatAdapter);
chatAdapter.notifyDataSetChanged();
}
// 发送消息聊天
private void chat() {
//判断是否输入内容
final String send_message = chat_input.getText().toString().trim();
if (TextUtils.isEmpty(send_message)) {
Toast.makeText(ChatActivity.this, "对不起,您还未发送任何消息",
Toast.LENGTH_SHORT).show();
return;
}
// 记录刷新
ChatMessage sendChatMessage = new ChatMessage();
sendChatMessage.setMessage(send_message);
sendChatMessage.setData(new Date());
sendChatMessage.setType(ChatMessage.Type.OUTCOUNT);
list.add(sendChatMessage);
chatAdapter.notifyDataSetChanged();
input.setText("");
// 发送消息去服务器端,返回数据
new Thread() {
public void run() {
ChatMessage chat = HttpRequest.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.add(chatMessage);
chatAdapter.notifyDataSetChanged();
}
};
};
// 点击事件监听
OnClickListener onClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.send:
chat();
break;
}
}
};
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.chat">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".ChatActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
application>
<uses-permission android:name="android.permission.INTERNET" />
manifest>
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.chat"
minSdkVersion 22
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
compile 'com.google.code.gson:gson:2.2.4'//添加依赖
}
作者:于静
原文链接:https://blog.csdn.net/qq_40660339/article/details/90715810