天天看點

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/)
      • 代碼塊
      • 代碼塊
注意:原創文章,如有不妥,請指出,若要轉載請标明出處。