前言
- 偶然在網上看到一個免費機器人接口,所以生此想法,接口地址: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();
}
}
尾聲
- 以上代碼可複製使用,但其中有一些圖片,類庫什麼的需要自行導入,完整代碼見github:點擊此處直達
- 完整項目+apk安裝包直接下載地址
- 該項目是我早期項目,只是爲了記錄當初的開發流程,所以並不存在什麼設計模式,代碼結構也比較亂,註釋也比較少,如果有任何問題,歡迎添加我的QQ詢問!
Tip:本文代碼,內容均個人原創,個別代碼曾經參考過資料,如涉及侵權請聯繫作者刪除。