編輯:關於 Android 程式設計


要實現一個圖靈機器人,首先需要到圖靈機器人官網(www.tuling123.com)註冊,創建一個應用,便能透過應用的 API key 使用圖靈機器人。它非常方便的一點是不需要引入額外的庫類——只需發起 GET 請求訪問 www.tuling123.com/openapi/api,就能獲得 JSON 資料,解析即可。
先簡單了解 JSON 解析格式。JSON(JavaScript Object Notation)是一種比 XML 更輕巧的輕量級資料格式,它建構於兩種結構之上:
1、「名稱/值」對的集合,在不同語言中被理解為對象、記錄、結構、字典、雜湊表等,如:
{
"name": "jackson",
"age": 100
}
2、值的有序清單,在大部分語言中被理解為陣列,如:
{
"students": [
{"name": "jackson", "age": 100},
{"name": "michael", "age": 51}
]
}
下面具體看看圖靈機器人的實作。
一、創建接口 HttpGetData:
package com.example.rootpeople1;
public interface HttpGetData {
void getDataUrl(String data);
}
二、創建 HttpData.java,封裝異步網路請求:
package com.example.rootpeople1;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
public class HttpData extends AsyncTask<String, String, String> {
private HttpClient httpClient;
private HttpGet httpGet;
private String url;
private HttpResponse httpResponse;
private HttpEntity httpEntity;
private InputStream in;
private HttpGetData listener;
public HttpData(String url, HttpGetData listener) {
this.url = url;
this.listener = listener;
}
@Override
protected String doInBackground(String... params) {
try {
httpClient = new DefaultHttpClient();
httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
in = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
// 處理異常
}
return null;
}
@Override
protected void onPostExecute(String result) {
listener.getDataUrl(result);
super.onPostExecute(result);
}
}
三、創建 ListData.java,作為聊天訊息的資料模型:
package com.example.rootpeople1;
public class ListData {
private String content;
public static final int send = 1;
public static final int receiver = 2;
private int flag;
private String time;
public String getTime() { return time; }
public void setTime(String time) { this.time = time; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public int getFlag() { return flag; }
public void setFlag(int flag) { this.flag = flag; }
public ListData(String content, int flag, String time) {
super();
setContent(content);
setFlag(flag);
setTime(time);
}
}
四、創建 TextAdapter.java,負責聊天清單的渲染,根據 flag 區分左右氣泡:
package com.example.rootpeople1;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class TextAdapter extends BaseAdapter {
private List<ListData> lists;
private Context mContext;
private RelativeLayout layout;
public TextAdapter(List<ListData> lists, Context mContext) {
this.lists = lists;
this.mContext = mContext;
}
public int getCount() { return lists.size(); }
public Object getItem(int position) { return lists.get(position); }
public long getItemId(int position) { return position; }
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
if (lists.get(position).getFlag() == ListData.receiver) {
layout = (RelativeLayout) inflater.inflate(R.layout.leftitem, null);
}
if (lists.get(position).getFlag() == ListData.send) {
layout = (RelativeLayout) inflater.inflate(R.layout.rightem, null);
}
TextView tv = (TextView) layout.findViewById(R.id.tv);
TextView time = (TextView) layout.findViewById(R.id.time);
time.setText(lists.get(position).getTime());
tv.setText(lists.get(position).getContent());
return layout;
}
}
五、MainActivity.java,串起整個聊天流程:初始化介面、發送訊息、請求圖靈接口並解析返回的 JSON:
package com.example.rootpeople1;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements HttpGetData, OnClickListener {
private HttpData httpdata;
private List<ListData> list;
private ListView lv;
private Button send_btn;
private EditText sendtext;
private String content_str;
private TextAdapter adapter;
private String[] welcomeArray;
private double currenttime, oldTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initeview();
}
private void initeview() {
list = new ArrayList<ListData>();
lv = (ListView) findViewById(R.id.lv);
send_btn = (Button) findViewById(R.id.send_btn);
sendtext = (EditText) findViewById(R.id.senText);
send_btn.setOnClickListener(this);
adapter = new TextAdapter(list, this);
lv.setAdapter(adapter);
ListData listData = new ListData(getRandomWelcomeTips(), ListData.receiver, getTime());
list.add(listData);
}
public void getDataUrl(String data) {
parseText(data);
}
public void parseText(String str) {
try {
JSONObject jb = new JSONObject(str);
ListData listData = new ListData(jb.getString("text"), ListData.receiver, getTime());
list.add(listData);
adapter.notifyDataSetChanged();
} catch (Exception e) {
// 處理異常
}
}
public void onClick(View v) {
content_str = sendtext.getText().toString();
sendtext.setText("");
String droph = content_str.replace(" ", "").replace("\n", "");
ListData listdata = new ListData(content_str, ListData.send, getTime());
list.add(listdata);
adapter.notifyDataSetChanged();
httpdata = new HttpData(
"https://www.tuling123.com/openapi/api?key=你的KEY&info=" + droph, this);
httpdata.execute();
}
private String getRandomWelcomeTips() {
welcomeArray = this.getResources().getStringArray(R.array.welcome_tips);
int index = (int) (Math.random() * (welcomeArray.length - 1));
return welcomeArray[index];
}
private String getTime() {
currenttime = System.currentTimeMillis();
SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date curdata = new Date();
String str = format.format(curdata);
if (currenttime - oldTime >= 5 * 60 * 1000) {
oldTime = currenttime;
return str;
} else {
return "";
}
}
}
最后是佈局檔案。activity_main.xml 由一個 ListView 與底部的輸入區組成:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<ListView
android:id="@+id/lv"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="@null"
android:listSelector="@android:color/transparent"
android:transcriptMode="alwaysScroll"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/senText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:drawable/edit_text"/>
<Button
android:id="@+id/send_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send"/>
</LinearLayout>
</LinearLayout>
leftitem.xml 與 rightem.xml 分別定義了左側(機器人)與右側(使用者)的聊天气泡,並透過 RoundedImageView 呈現圓角頭像。
最終運行介面:



如需源碼,可點擊連接下載:https://pan.baidu.com/s/1gfbKRcv(提取碼 eyb2)。
Android 動態載入 APK 實作:Fragment 與 Activity 兩種做法
起因是專案膨脹到編譯不過——Android 對單一應用中的方法數量有上限(就是知名的 65536 或 DEX 64K 限制)。於是開始研究能否把某些模塊做成獨立 APK,
Android 開發實作:android_apk 在線安裝(源碼分享)
要實現 Android 應用的在線安裝(即軟體的在線升級),除了要撰寫 Android 客戶端程式碼,還需要搭建一個服務器端,模擬並驅動整個升級流程。本文完整分享這套實作
告別命令行:Android Studio 項目提交與更新到 GitHub 保姆級教程
用 Android Studio 開發到一定階段,總會想把項目推到 GitHub 上留個備份或者做開源。以前只能靠 cmd 敲命令,其實 Studio 自帶的 Git 集
為 Android RecyclerView 加上「上拉加載更多」
上一篇已經介紹了如何為 RecyclerView 加上 FootView,在此基礎上要實作分頁加載,其實已經非常簡單了。 上一篇:為 RecyclerView 添加 Fo