Android开发之智能聊天机器人

一:效果图二:注册图灵机器人,获取api1.进入图灵机器人官网注册,已有账号的可直接登录2.点击创建机器人3.创建好机器人之后会得到一个ApiKey(如图所示)4.下面就要拼接Api地址了(拼接方法如图所示)

三.下面就是具体实现的代码了1.首先是布局文件(activity_main)2.左布局文件(leftitem)3.右布局文件(rightitem)4.bg_edittext_selector.xml5.bg_button.xml6.HttpData7.HttpGetDataListener8.ListData9.TextAdapter10.主java文件(MainActivity)11.还需要注意申请网络权限,放在AndroidManifest.xml中

四、资源下载

Android实现智能聊天机器人

最近在做项目中,突然来了灵感,要做一个聊天机器人.聊天机器人在很多大型App上都有使用,比如QQ群里的QQ小冰,淘宝京东等App上在没有人工客服之前会有机器人跟你聊天,根据你发的问题关键词,向你推荐一些答案,可以省下很多人工的时间以及减小服务器的压力。

此功能主要原理: 1.接入图灵机器人api,拼接上你输入框的消息;

2.根据api完成网络请求消息的接收与发送

3.完成布局页面

4.实现你和小洛的对话 废话不多说,直接上图和代码

一:效果图

二:注册图灵机器人,获取api

1.进入图灵机器人官网注册,已有账号的可直接登录

2.点击创建机器人

3.创建好机器人之后会得到一个ApiKey(如图所示)

4.下面就要拼接Api地址了(拼接方法如图所示)

拼接方法:http://www.tuling123.com/openapi/api?key=你自己的apikey&info=你要发送的话&userid=你自己的唯一标示(在代码中会指出)

三.下面就是具体实现的代码了

1.首先是布局文件(activity_main)

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/LinearLayout1"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

android:id="@+id/lv"

android:layout_width="fill_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:divider="@null"

android:listSelector="@android:color/transparent"

android:transcriptMode="alwaysScroll" >

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:background="#229dec"

android:orientation="horizontal" >

android:id="@+id/et_sendText"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_gravity="center_vertical"

android:layout_marginLeft="7dp"

android:layout_weight="1"

android:background="@drawable/bg_edittext_selector"

android:paddingBottom="7dp"

android:paddingTop="7dp" />

android:id="@+id/btn_send"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_margin="7dp"

android:background="@drawable/bg_button"

android:text="发送" />

2.左布局文件(leftitem)

android:layout_width="match_parent"

android:layout_height="wrap_content">

android:id="@+id/tv_time"

android:layout_width="fill_parent"

android:gravity="center_horizontal"

android:layout_height="wrap_content"/>

android:id="@+id/iv"

android:layout_width="70dp"

android:layout_height="70dp"

android:layout_alignParentLeft="true"

android:layout_below="@id/tv_time"

android:paddingLeft="10dp"

android:paddingRight="10dp"

android:src="@drawable/by2" />

android:layout_below="@id/tv_time"

android:layout_marginTop="10dp"

android:layout_marginRight="10dp"

android:layout_toRightOf="@id/iv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:padding="10dp"

android:id="@+id/tv"

android:gravity="center"

android:background="@drawable/left"/>

3.右布局文件(rightitem)

android:layout_width="match_parent"

android:layout_height="wrap_content">

android:id="@+id/tv_time"

android:layout_width="fill_parent"

android:gravity="center_horizontal"

android:layout_height="wrap_content" />

android:id="@+id/iv"

android:layout_width="70dp"

android:layout_height="70dp"

android:layout_alignParentRight="true"

android:layout_below="@id/tv_time"

android:paddingLeft="10dp"

android:paddingRight="10dp"

android:src="@drawable/by5" />

android:id="@+id/tv"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/tv_time"

android:layout_marginLeft="10dp"

android:layout_marginTop="14dp"

android:layout_toLeftOf="@id/iv"

android:background="@drawable/right"

android:gravity="center"

android:padding="12dp" />

4.bg_edittext_selector.xml

android:width="1dip"

android:color="#BDC7D8" />

5.bg_button.xml

android:width="0.01dp"

android:color="#80cccf" />

android:bottomLeftRadius="5dp"

android:bottomRightRadius="5dp"

android:topLeftRadius="5dp"

android:topRightRadius="5dp" />

6.HttpData

package robot.com.myapplication;

import android.os.AsyncTask;

import android.util.Log;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;

import java.io.InputStream;

import java.io.InputStreamReader;

/**

*

*/

public class HttpData extends AsyncTask {

private HttpClient httpClient;

private HttpGet httpGet;

private HttpResponse httpResponse; //��ȡ���絻ص�����

private HttpEntity httpEntity;//����httpʵ��

private InputStream in; //����ȡ��������ת��Ϊ���ļ�

private HttpGetDataListener listener;//ʵ���Զ����HttpGetDataListener�ӿ�,���ҹ��컯���ݲ���

private String url;

public HttpData(String url ,HttpGetDataListener listener) {

this.url = url;

this.listener = listener;

}

@Override

protected String doInBackground(String... params) {//ʵ�ֽӿں���д�˷���,�˷����������ǣ�����get����㬻�ȡ����

try {

httpClient = new DefaultHttpClient();//ʵ�����ͻ���

httpGet = new HttpGet(url);//ʹ��get��ʽ��ͨ������URL������

httpResponse = httpClient.execute(httpGet); //ͨ���ͻ��˷�������

httpEntity = httpResponse.getEntity();//ͨ��httpResponse�����ȡ����

Log.i("haha1", "----------"+httpEntity.toString());

in = httpEntity.getContent();//��ȡʵ��ľ�������

BufferedReader br = new BufferedReader(new InputStreamReader(in));//��ȡ���������ݺ�ͨ�����������ж�ȡ

Log.i("haha2", "----------"+br.toString());

String line = null; //��ȡ����

StringBuffer sb = new StringBuffer();//������������

while((line = br.readLine()) != null){ //��ȡ������������

sb.append(line); //�洢���ݵ�StringBuffer��

}

Log.i("haha3", "----------"+sb.toString());

return sb.toString();//ת��ΪString����

} catch (Exception e) {

// TODO: handle exception

}

return null;

}

/**����

* ��д�˷�����ͨ���ⷽ����ȡ����

*/

@Override

protected void onPostExecute(String result) {

listener.getDataUrl(result);//��������

Log.i("haha4", "----------"+result);

super.onPostExecute(result);

}

}

7.HttpGetDataListener

package robot.com.myapplication;

public interface HttpGetDataListener {

void getDataUrl(String data);

}

8.ListData

package robot.com.myapplication;

/**

*

*/

public class ListData {

public static final int SEND = 1;

public static final int RECEIVE = 2;

private String content;

private int flag;//��ʶ

private String time;

public ListData(String content, int flag, String time) {

setContent(content);

setFlag(flag);

setTime(time);

}

public String getContent() {

return content;

}

public void setContent(String content) {

this.content = content;

}

public int getFlag() {

return flag;

}

public void setFlag(int flag) {

this.flag = flag;

}

public String getTime() {

return time;

}

public void setTime(String time) {

this.time = time;

}

}

9.TextAdapter

package robot.com.myapplication;

import android.content.Context;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.BaseAdapter;

import android.widget.RelativeLayout;

import android.widget.TextView;

import java.util.List;

/**

*

*/

public class TextAdapter extends BaseAdapter{

private List lists;//���ϵ���������

private Context mContext;//�н������ĵ�Context

private RelativeLayout layout;

public TextAdapter(List lists, Context mContext) {

this.lists = lists;

this.mContext = mContext;

}

@Override

public int getCount() {//����lists�����ص�����

return lists.size();

}

@Override

public Object getItem(int position) {

return lists.get(position);

}

@Override

public long getItemId(int position) {

return position;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

LayoutInflater inflater = LayoutInflater.from(mContext);

if(lists.get(position).getFlag() == ListData.RECEIVE){

layout = (RelativeLayout) inflater.inflate(R.layout.leftitem, null);

}

if(lists.get(position).getFlag() == ListData.SEND){

layout = (RelativeLayout) inflater.inflate(R.layout.rightitem, null);

}

TextView tv = (TextView) layout.findViewById(R.id.tv);//�Ի�textView

TextView tv_time = (TextView) layout.findViewById(R.id.tv_time);//ʱ��textView

tv.setText(lists.get(position).getContent()); //���������ݷ��MTextView��

tv_time.setText(lists.get(position).getTime());//���¼�д��TextView

return layout;

}

}

10.主java文件(MainActivity)

package robot.com.myapplication;

import android.view.View;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import org.json.JSONException;

import org.json.JSONObject;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ListView;

public class MainActivity extends AppCompatActivity implements

HttpGetDataListener,View.OnClickListener {

private HttpData httpData;// �첽�������

private List lists;

private ListView lv;

private EditText et_sendText;

private Button btn_send;

private String content_str; // �惦��EditText�@ȡ���Ĕ���

private TextAdapter adapter;

private String[] welcome_arry;//��ӭ��

private double currentTime,oldTime = 0;//�Ի�ʱ��

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Log.i("haha7", "----------7");

initView();

Log.i("haha8", "----------8");

}

/**

* ʵ��������

*/

private void initView(){

lists = new ArrayList();

lv = (ListView) findViewById(R.id.lv);

et_sendText = (EditText) findViewById(R.id.et_sendText);

btn_send = (Button) findViewById(R.id.btn_send);

btn_send.setOnClickListener(this);

adapter = new TextAdapter(lists, this);

lv.setAdapter(adapter);//��adapter

ListData listData;

listData = new ListData(getRandomWelcomeTips(),ListData.RECEIVE, getTime());

lists.add(listData);//��ӻ�ӭ��

}

/**

* ���û�ӭ��

*/

public String getRandomWelcomeTips(){

// String welcome_tip = null;

// welcome_arry = this.getResources().getStringArray(getResources().getString(R.string.welcome_tips));//��string.xml�л�ȡ��Ϊwelcome_tips���ַ�������

// int index = (int)(Math.random()*(welcome_arry.length - 1));//��ȡһ�������

// welcome_tip = welcome_arry[index];

return getResources().getString(R.string.welcome_tips);

}

/**

* ����ʱ��

* @return

*/

private String getTime(){

currentTime = System.currentTimeMillis();

SimpleDateFormat format = new SimpleDateFormat("yyyy��MM��dd�� HH:mm:ss");

Date curDate = new Date();

String str = format.format(curDate);

if(currentTime - oldTime >= 5*60*1000){//�������5���ӣ���ʾʱ��

oldTime = currentTime;

return str;

}else{

return "";

}

}

@Override

public void getDataUrl(String data) {

Log.i("haha---data=","------" + data);

parseText(data);

}

public void parseText(String str){//����json

try {

JSONObject jb = new JSONObject(str);

ListData listData;

listData = new ListData(jb.getString("text"),ListData.RECEIVE, getTime());

lists.add(listData);

adapter.notifyDataSetChanged();//�����m�䣿��

} catch (JSONException e) {

e.printStackTrace();

}

}

@Override

public void onClick(View v) {

getTime();//����ʱ��

content_str = et_sendText.getText().toString();//�@ȡEditText����

et_sendText.setText("");

String dropk = content_str.replace(" ", "");//ȥ���ո�

String droph = dropk.replace("\n", "");//ȥ���س�

ListData listData;

listData = new ListData(content_str, ListData.SEND, getTime());

lists.add(listData);

Log.i("haha9", "----------content_str="+content_str);

adapter.notifyDataSetChanged();//ˢ��

Log.i("haha6", "----------content_str="+content_str);

httpData = (HttpData) new HttpData(

"http://www.tuling123.com/openapi/api?key=02dfb86de93f8a3e81dabd214a50c8fa&info=" + droph + "&userid=15602229049",

this).execute();// �����Ѿ�ȥ���ո�ͻس�content_str������droph ; execute()�����첽ͨ��

Log.i("haha5", "----------"+httpData);

if(lists.size() > 30){//�����Ļ�ϵĶԻ����ݶ���30�����Ƴ�ǰ�������

for (int i = 0; i < lists.size(); i++) {

lists.remove(i);

}

}

}

}

11.还需要注意申请网络权限,放在AndroidManifest.xml中

四、资源下载

下载地址:Android开发之智能聊天机器人 至此,一个智能聊天机器人就实现了,你可以尽情的和它玩耍了,记住别玩坏了哦 不懂的地方可以问我哦

文章链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: