1. 程式人生 > >Android簡單應用之--與圖靈機器人聊天Demo

Android簡單應用之--與圖靈機器人聊天Demo

圖靈機器人聊天Demo

本著探討和分享技術的理念,也藉此記錄自己的成長,應運而生了這個小的Android Demo,這是我第一次寫部落格,更何況是技術型部落格,如有什麼不對的地方,歡迎大家指出,謝謝~。

下面簡單介紹一下這個小專案

  • 基於圖靈機器人
  • 網路請求使用了開源庫RxVolley

其實實現與機器人聊天功能不一定使用圖靈機器人,也可以是聚合資料的“問答機器人”免費介面(這裡附上地址:https://www.juhe.cn/docs/api/id/112),兩者在應用中的使用方法大同小異,但是由於聚合資料的“問答機器人”的每日呼叫次數上限為100次,而圖靈機器人為1000次,所以選擇圖靈機器人。

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.分包
這裡寫圖片描述

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 = 1;//收
    public static final int chat_right = 2;//發

    //構造器
    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 3;
    }

}

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中的網路許可權。

注意:原創文章,如有不妥,請指出,若要轉載請標明出處。