天天看点

Android简单应用之--与图灵机器人聊天Demo图灵机器人聊天Demo

图灵机器人聊天Demo

本着探讨和分享技术的理念,也借此记录自己的成长,应运而生了这个小的Android Demo,这是我第一次写博客,更何况是技术型博客,如有什么不对的地方,欢迎大家指出,谢谢~。

下面简单介绍一下这个小项目

  • 基于图灵机器人
  • 网络请求使用了开源库RxVolley

其实实现与机器人聊天功能不一定使用图灵机器人,也可以是聚合数据的“问答机器人”免费接口(这里附上地址:https://www.juhe.cn/docs/api/id/112),两者在应用中的使用方法大同小异,但是由于聚合数据的“问答机器人”的每日调用次数上限为100次,而图灵机器人为1000次,所以选择图灵机器人。

RxVolley简介(摘自http://rxvolley.mydoc.io/)

RxVolley是RxVolley是一个基于Volley的网络请求库;

同时支持RxJava;

可以选择使用OKHttp替代默认的 HttpUrlConnection 做网络请求;

这里只需要使用

RxVolley.get(String url, new HttpCallback() {

@Override

public void onSuccess(String t) {

Loger.debug(“请求到的数据:” + t);

}

});

其中URL为以下三点拼接成:

1.图灵机器人Web api v1.0 接口地址:http://www.tuling123.com/openapi/api

2.图灵官网中注册的机器人获得的api_key:3e4f8d6a4a484a46b34330e8693f7f9b

3.info后接入信息

url=http://www.tuling123.com/openapi/api?key=3e4f8d6a4a484a46b34330e8693f7f9b&info=你好

实现步骤

1.分包

Android简单应用之--与图灵机器人聊天Demo图灵机器人聊天Demo

2.activity_main.xml

代码块

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <ListView
        android:id="@+id/lv_chat_list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical"
        >
        <EditText
            android:id="@+id/ed_send"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:hint="输入"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/btn_send"
            android:padding="5dp"
            android:text="send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>
           

3.left_item.xml

代码块

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:padding="10dp">

    <ImageView
        android:src="@mipmap/ic_launcher_round"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_left_text"
        android:background="@drawable/chat_bg_cloud"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:gravity="center"
       />


</LinearLayout>
           

4.right_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="right|center_vertical"
    android:padding="10dp">


    <TextView
        android:id="@+id/tv_right_text"
        android:background="@drawable/chat_bg_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:gravity="center"
       />

    <ImageView
        android:src="@drawable/user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
           

5.ChatData.java—消息实体类

public class ChatData {
    //信息类型(get/send)
    private int type;
    //文本
    private String text;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}
           

6.ChatListAdapter.java—–消息适配器

public class ChatListAdapter extends BaseAdapter {
    private List<ChatData> mList = new ArrayList<>();
    private ChatData data;
    private Context mContext;
    private LayoutInflater inflater;

    //定义常量,区分收发信息
    public static final int chat_left = ;//收
    public static final int chat_right = ;//发

    //构造器
    public ChatListAdapter(Context mContext,List<ChatData> mList) {
        this.mContext = mContext;
        this.mList = mList;
        inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolderleft viewHolderleft = null;
        ViewHolderright viewHolderright = null;
        int type = getItemViewType(i);
        if(view==null){
            //加载布局
            //判断左右信息,即是收到还是发出
            switch (type){
                case chat_left:
                    viewHolderleft = new ViewHolderleft();
                    view = inflater.inflate(R.layout.left_item,null);
                    viewHolderleft.textView_left = (TextView) view.findViewById(R.id.tv_left_text);
                    view.setTag(viewHolderleft);
                    break;
                case chat_right:
                    viewHolderright = new ViewHolderright();
                    view = inflater.inflate(R.layout.right_item,null);
                    viewHolderright.textView_right = (TextView) view.findViewById(R.id.tv_right_text);
                    view.setTag(viewHolderright);
                    break;
            }

        }else{
            //判断左右信息,即是收到还是发出
            switch (type){
                case chat_left:
                    viewHolderleft = (ViewHolderleft) view.getTag();
                    break;
                case chat_right:
                    viewHolderright = (ViewHolderright) view.getTag();
                    break;
            }

        }


        //赋值
        ChatData data = mList.get(i);
        //判断左右信息,即是收到还是发出
        switch (data.getType()){
            case chat_left:
                viewHolderleft.textView_left.setText(data.getText());
                break;
            case chat_right:
                viewHolderright.textView_right.setText(data.getText());
                break;
        }
        return view;
    }

    //获取当前Item的类型
    @Override
    public int getItemViewType(int position) {
        ChatData chatData= mList.get(position);
        int type = chatData.getType();
        return type;
    }

    //左边消息控件缓存
    class ViewHolderleft{
        private TextView textView_left;
    }

    //右边消息控件缓存
    class ViewHolderright{
        private TextView textView_right;
    }
    //返回所有Layout数据
    @Override
    public int getViewTypeCount() {
        return ;
    }

}
           

7.MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private ListView lv_chat_list;
    private EditText ed_send;
    private Button btn_send;
    private List<ChatData> mList = new ArrayList<>();
    private ChatListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化控件
        initView();

    }

    private void initView() {
        lv_chat_list = (ListView) findViewById(R.id.lv_chat_list);
        ed_send = (EditText) findViewById(R.id.ed_send);
        btn_send = (Button) findViewById(R.id.btn_send);
        lv_chat_list.setDivider(null);

        //设置适配器
        adapter = new ChatListAdapter(this,mList);
        lv_chat_list.setAdapter(adapter);

        //设置发送按钮监听
        btn_send.setOnClickListener(this);

        //设置欢迎语
        addlefttext("你好呀!");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_send:
                String message = ed_send.getText().toString().trim();
                if(!TextUtils.isEmpty(message)){
                    //点击发送后清空输入框
                    ed_send.setText("");
                    addrighttext(message);
                    //定义URL
                    //图灵机器人接口地址:http://www.tuling123.com/openapi/api
                    //key=后接在图灵官网申请到的apikey
                    //info后接输入的内容
                    String url ="http://www.tuling123.com/openapi/api?"+
                            "key="+"3e4f8d6a4a484a46b34330e8693f7f9b"+"&info="+message;
                    //RxVolley将信息发出(添加RxVolley依赖,
                    // 在app的build.gradle的ependencies中添加compile 'com.kymjs.rxvolley:rxvolley:1.1.4')
                    RxVolley.get(url, new HttpCallback() {
                        @Override
                        public void onSuccess(String t) {
                            //解析返回的JSON数据
                            pasingJson(t);
                        }
                    });

                }else{
                    return;
                }
                break;
        }
    }

    private void pasingJson(String message){
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(message);
            //通过key(text)获取value
            String text = jsonObject.getString("text");
            addlefttext(text);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //添加右侧消息
    private void addrighttext(String message) {
        ChatData data = new ChatData();
        data.setType(ChatListAdapter.chat_right);
        data.setText(message);
        mList.add(data);
        //通知adapter刷新页面
        adapter.notifyDataSetChanged();
        lv_chat_list.setSelection(lv_chat_list.getBottom());

    }

    //添加左侧消息
    private void addlefttext(String message) {
        ChatData data = new ChatData();
        data.setType(ChatListAdapter.chat_left);
        data.setText(message);
        mList.add(data);
        adapter.notifyDataSetChanged();
        lv_chat_list.setSelection(lv_chat_list.getBottom());

    }
}
           

到这里就差不多是全部的代码了,提醒:用到RxVolley库前别忘了在app.gradle中添加必要的依赖,代码中也有提示,请注意。

最后一步就是配置AndroidManifest.xml中的网络权限。

  • 图灵机器人聊天Demo
    • RxVolley简介(摘自http://rxvolley.mydoc.io/)
      • 代码块
      • 代码块
注意:原创文章,如有不妥,请指出,若要转载请标明出处。