1. 程式人生 > 程式設計 >Android studio開發小型對話機器人app(例項程式碼)

Android studio開發小型對話機器人app(例項程式碼)

前言

偶然在網上看到一個免費機器人介面,所以生此想法,介面地址:http://api.qingyunke.com/,Android開發比爬蟲要繁瑣得多,所以本文我將細說介面的呼叫方法,讀者可根據思路去網上找一些免費介面拿來玩,其他程式碼一帶而過,詳細原始碼見文末。

成品展示:

在這裡插入圖片描述

開發步驟

1)新建專案empty,必要可github託管。

2)先寫頁面在res->layout目錄下新建兩個layout xml file

在這裡插入圖片描述

activity_main作為主頁面,msg_item為附在其上的訊息頁面。(具體程式碼見文末)

這裡再acitvity_main採用的不是ListView而是RecyclerView。

(3)寫介面呼叫首先封裝一個RobotManager類,用於接收使用者輸入之後對Url進行封裝。

public class RobotManager {
 private static String url = "http://api.qingyunke.com/api.php?key=free&appid=0&msg=!!";

 public static String getUrl(String question){
 String real_url = url.replace("!!",question);//將url中的!!替換為使用者輸入的內容
 return real_url;
 }
}

其次在java->第一個包下建立一個介面GetConnection,用來接收介面返回的返回。

public interface GetConnection {
 void onFinish(String response);	//返回正常
 void onError(Exception e);	//返回錯誤
}

然後開始寫MyConnection類,呼叫介面,給參,並通過GetConnection介面將網上介面返回的資料傳遞出去。

public class MyConnection {

 public static void getResponse(final String url,final GetConnection getConnection){
 new Thread(new Runnable() {
  @Override
  public void run() {
  HttpURLConnection connection;
  try{
   URL Url = new URL(url);
   connection = (HttpURLConnection) Url.openConnection();
   connection.setRequestMethod("GET");//Get方法
   connection.setConnectTimeout(2000);//延時時間
   connection.setReadTimeout(3000);
   connection.setDoInput(true);
   InputStream in = connection.getInputStream();
   BufferedReader reader = new BufferedReader(new InputStreamReader(in));
   StringBuilder response = new StringBuilder();
   String line;
   while ((line = reader.readLine()) != null) {
   response.append(line);
   }
   Log.e("result",response.toString());
   if (getConnection != null) {
   getConnection.onFinish(response.toString());
   }else {
   Log.e("WeiNull","WeiNull");//測試時用的,無須關心。
   }
  }catch(IOException io) {
   if (getConnection != null) {
   getConnection.onError(io);
   }
  }
  }
 }).start();

 }
}

(4)寫頁面邏輯頁面邏輯主要是將從介面得到的內容渲染到頁面上。首先進行一系列初始化,繫結佈局,然後監聽按鈕點選接收使用者輸入,呼叫MyConnection類傳入url,輸入內容接收介面返回內容,同時用handler動態更新頁面。

public class MainActivity extends AppCompatActivity {

 private List<Msg> msgList = new ArrayList<Msg>();

 private EditText inputText;

 private Button send;

 private RecyclerView msgRecyclerView;

 private MsgAdapter adapter;

 private Handler handler = new Handler(){
 @Override
 public void handleMessage(@NonNull Message msg) {
  switch (msg.what){
  case 1:{
   Bundle data = msg.getData();
   String result = data.getString("result");
   Msg robotMsg = new Msg(result,Msg.TYPE_RECEIVED);
   msgList.add(robotMsg);
   adapter.notifyItemInserted(msgList.size() - 1); // 當有新訊息時,重新整理ListView中的顯示
   msgRecyclerView.scrollToPosition(msgList.size() - 1); // 將ListView定位到最後一行
  }break;
  case 2:{}break;
  default:break;
  }
 }
 };

 private void getInter(String content){
 MyConnection.getResponse(RobotManager.getUrl(content),new GetConnection() {
  @Override
  public void onFinish(String response) {
  ContentBean contentBean = new ContentBean();
  Log.e("getResult",response);
  Message msg = new Message();
  Bundle data = new Bundle();
  Gson gson = new Gson();
  contentBean = gson.fromJson(response,ContentBean.class);	//用Gson將返回內容序列化為ContentBean物件。
  if(contentBean.getResult()==0){
   data.putString("result",contentBean.getContent());
  }else{
   data.putString("result","我聽不懂你在說什麼呀!");
  }
  msg.setData(data);
  msg.what = 1;
  handler.sendMessage(msg);
  }

  @Override
  public void onError(Exception e) {
  e.printStackTrace();
  }
 });
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 initMsgs(); // 初始化訊息資料
 inputText = findViewById(R.id.input_text);
 send = findViewById(R.id.send);
 msgRecyclerView = findViewById(R.id.msg_recycler_view);
 LinearLayoutManager layoutManager = new LinearLayoutManager(this);
 msgRecyclerView.setLayoutManager(layoutManager);
 adapter = new MsgAdapter(msgList);
 msgRecyclerView.setAdapter(adapter);
 send.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  String content = inputText.getText().toString();
  if (!"".equals(content)) {
   Msg msg = new Msg(content,Msg.TYPE_SENT);
   msgList.add(msg);
   getInter(content);
   Log.e("url",RobotManager.getUrl(content));
   adapter.notifyItemInserted(msgList.size() - 1); // 當有新訊息時,重新整理ListView中的顯示
   msgRecyclerView.scrollToPosition(msgList.size() - 1); // 將ListView定位到最後一行
   inputText.setText(""); // 清空輸入框中的內容

  }
  }
 });
 }

 private void initMsgs() {
 Msg msg1 = new Msg("我是菲菲,快來和我聊天吧* ( ´͈ ᵕ `͈ )◞♡",Msg.TYPE_RECEIVED);
 msgList.add(msg1);
 }
}

由於介面返回的資料是Json格式,所以我們需要對Json進行解析,本文采用google的Gson庫對其進行解析,將介面內容序列化為一個類ContentBean。解析過程見上面程式碼。

public class ContentBean {

 /**
 * result : 0
 * content : [04月08日] 邯鄲天氣:小雨,白天 17℃,夜晚 9℃,微風,<3級轉3-4級
 */
 private int result;
 private String content;

 public int getResult() {
 return result;
 }

 public void setResult(int result) {
 this.result = result;
 }

 public String getContent() {
 return content;
 }

 public void setContent(String content) {
 this.content = content;
 }
}

(5)其餘程式碼Msg和MsgAdapter用於解析訊息是傳送方還是接收方
並展示在訊息列表上Msg

public class Msg {

 public static final int TYPE_RECEIVED = 0;

 public static final int TYPE_SENT = 1;

 private String content;

 private int type;

 public Msg(String content,int type) {
 this.content = content;
 this.type = type;
 }

 public String getContent() {
 return content;
 }

 public int getType() {
 return type;
 }

}

MsgAdapter

public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {

 private List<Msg> mMsgList;

 static class ViewHolder extends RecyclerView.ViewHolder {

 LinearLayout leftLayout;

 LinearLayout rightLayout;

 TextView leftMsg;

 TextView rightMsg;

 public ViewHolder(View view) {
  super(view);
  leftLayout = (LinearLayout) view.findViewById(R.id.left_layout);
  rightLayout = (LinearLayout) view.findViewById(R.id.right_layout);
  leftMsg = (TextView) view.findViewById(R.id.left_msg);
  rightMsg = (TextView) view.findViewById(R.id.right_msg);
 }
 }

 public MsgAdapter(List<Msg> msgList) {
 mMsgList = msgList;
 }

 @Override
 public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
 View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
 return new ViewHolder(view);
 }

 @Override
 public void onBindViewHolder(ViewHolder holder,int position) {
 Msg msg = mMsgList.get(position);
 if (msg.getType() == Msg.TYPE_RECEIVED) {
  // 如果是收到的訊息,則顯示左邊的訊息佈局,將右邊的訊息佈局隱藏
  holder.leftLayout.setVisibility(View.VISIBLE);
  holder.rightLayout.setVisibility(View.GONE);
  holder.leftMsg.setText(msg.getContent());
 } else if(msg.getType() == Msg.TYPE_SENT) {
  // 如果是發出的訊息,則顯示右邊的訊息佈局,將左邊的訊息佈局隱藏
  holder.rightLayout.setVisibility(View.VISIBLE);
  holder.leftLayout.setVisibility(View.GONE);
  holder.rightMsg.setText(msg.getContent());
 }
 }

 @Override
 public int getItemCount() {
 return mMsgList.size();
 }

}

尾聲

以上程式碼可複製使用,但其中有一些圖片,類庫什麼的需要自行匯入,完整程式碼見geithub:點選此處直達

該專案是我早期專案,只是為了記錄當初的開發流程,所以並不存在什麼設計模式,程式碼結構也比較亂,註釋也比較少,如果有任何問題,歡迎新增我的QQ詢問!

總結

到此這篇關於Android studio開發一個小型對話機器人app的文章就介紹到這了,更多相關android studio 對話機器人內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!