騰訊公益賽個人衝刺部落格15(2024.6.3)

记得关月亮發表於2024-06-12
今天開始寫後端的主類介面,去圖靈機器人買了金鑰和介面,今天只寫了一部分,還看不出效果
package com.java.ffshixun;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private ListView listView;
    private ChatAdapter adapter;
    private List<ChatBean> chatBeanList;//存放所有聊天資料的集合
    private EditText et_send_msg;
    private Button btn_send;
    //介面地址
    private static final String WEB_SITE="http://www.tuling123.com/openapi/api";
    //唯一key,該key的值是從官網註冊賬號獲取的,註冊地址為:http://www.tuling123.com/
    private static final String KEY="b7f13cd027d5469fbd586940c0adbe83";
    private String sendMsg;//傳送的資訊
    private String welcome[];//儲存歡迎資訊
    private MHandler mHandler;
    public static final int MSG_OK=1;//獲取資料

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        chatBeanList=new ArrayList<ChatBean>();
        mHandler=new MHandler();
        //獲取內建的歡迎資訊
        welcome=getResources().getStringArray(R.array.welcome);
        initView();//初始化介面控制元件

    }
    public void initView(){
        listView=(ListView)findViewById(R.id.list);
        et_send_msg=(EditText)findViewById(R.id.et_send_msg);
        btn_send=(Button)findViewById(R.id.btn_send);
        adapter=new ChatAdapter(chatBeanList,this);
        listView.setAdapter(adapter);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendData();//點選傳送按鈕,傳送資訊
            }
        });
        et_send_msg.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent keyEvent) {
                if (keyCode==KeyEvent.KEYCODE_ENTER && keyEvent.getAction()==
                KeyEvent.ACTION_DOWN){
                    sendData();//點選Enter鍵也可以傳送資訊
                }
                return false;
            }
        });
        int position=(int)(Math.random()*welcome.length-1);//獲取一個隨機數
        showData(welcome[position]);//用隨機數獲取機器人的首次聊天資訊
    }
    private void sendData(){
        sendMsg=et_send_msg.getText().toString();//獲取你輸入的資訊
        if(TextUtils.isEmpty(sendMsg)){//判斷是否為空
            Toast.makeText(this,"您還未輸入任何資訊哦",Toast.LENGTH_LONG).show();
            return;
        }
        et_send_msg.setText("");
        //替換空格和換行
        sendMsg=sendMsg.replaceAll(" ","").replaceAll("\n","").trim();
        ChatBean chatBean=new ChatBean();
        chatBean.setMessage(sendMsg);
        chatBean.setState(chatBean.SEND);//SEND表示自己傳送的資訊
        chatBeanList.add(chatBean);//將傳送的資訊新增到chatBeanList集合中
        adapter.notifyDataSetChanged();//更新ListView列表
        getDataFromServer();//從伺服器獲取機器人傳送的資訊
    }

    private void getDataFromServer(){
        OkHttpClient okHttpClient=new OkHttpClient();
        Request request =new Request.Builder().url(WEB_SITE+"?key="+KEY+"&info="+sendMsg).build();
        Call call=okHttpClient.newCall(request);
        //開啟非同步執行緒訪問網路
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res=response.body().string();
                Message msg=new Message();
                msg.what=MSG_OK;
                msg.obj=res;
                mHandler.sendMessage(msg);
            }
        });
    }


    
}

相關文章