編輯:關於 Android 程式設計
這份筆記把幾個容易糾結的基礎知識點串在一起:系統聯絡人資料庫的結構、用 HttpURLConnection 讀取與送出資料、以及以 Handler 更新介面的標準寫法。適合當作入門後的複習材料。
聯絡人透過 ContentProvider 對外開放,資料分散在兩張表中:raw_contacts 保存聯絡人本身的記錄與 id,data 表則以行為單位保存電話、信箱、姓名等具體欄位,並用 raw_contact_id 關聯,再用 mimetype 標明這一行屬於哪一類資料。理解這個結構,才能正確地寫入與讀取。
流程是先在 raw_contacts 建立一筆記錄取得 id,然後针对同一個 id 分別往 data 表插入電話、信箱、姓名三筆資料。
public void click(View view) {
// 1. 在 raw_contacts 表建立一筆聯絡人記錄
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Cursor cursor = getContentResolver().query(uri, new String[]{"_id"}, null, null, null);
cursor.moveToLast();
int _id = cursor.getInt(0);
int newid = _id + 1;
ContentValues values = new ContentValues();
values.put("contact_id", newid);
getContentResolver().insert(uri, values);
// 2. 依聯絡人 id 在 data 表加入對應資料
Uri dataUri = Uri.parse("content://com.android.contacts/data");
// 插入電話
ContentValues phoneValues = new ContentValues();
phoneValues.put("data1", "999999");
phoneValues.put("mimetype", "vnd.android.cursor.item/phone_v2");
phoneValues.put("raw_contact_id", newid);
getContentResolver().insert(dataUri, phoneValues);
// 插入郵箱
ContentValues emailValues = new ContentValues();
emailValues.put("data1", "zhaoqi@itheima.com");
emailValues.put("mimetype", "vnd.android.cursor.item/email_v2");
emailValues.put("raw_contact_id", newid);
getContentResolver().insert(dataUri, emailValues);
// 插入姓名
ContentValues nameValues = new ContentValues();
nameValues.put("data1", "zhaoqi");
nameValues.put("mimetype", "vnd.android.cursor.item/name");
nameValues.put("raw_contact_id", newid);
getContentResolver().insert(dataUri, nameValues);
}
這段寫法有兩個明顯問題值得改進:用「查最大值再加一」產生 id 在併發情境下並不可靠,而且查完 Cursor 沒有關閉會造成洩漏。實務上應改用 BulkInsert 或 ContentProviderOperation 批次交易,並養成 try-with-resources 或 finally 關閉 Cursor 的習慣。此外,寫入聯絡人需要 WRITE_CONTACTS 權限,且屬於執行期危險權限,必須向使用者動態申請。
public static List<ContactInfo> getContactInfos(Context context) {
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Uri dataUri = Uri.parse("content://com.android.contacts/data");
List<ContactInfo> contactInfos = new ArrayList<ContactInfo>();
Cursor cursor = resolver.query(uri, new String[]{"contact_id"}, null, null, null);
while (cursor.moveToNext()) {
String contact_id = cursor.getString(0);
// 依聯絡人 id 查詢 data 表的明細
Cursor dataCursor = resolver.query(dataUri,
new String[]{"data1", "mimetype"},
"raw_contact_id=?", new String[]{contact_id}, null);
ContactInfo contactInfo = new ContactInfo();
while (dataCursor.moveToNext()) {
String data1 = dataCursor.getString(0);
String mimetype = dataCursor.getString(1);
if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {
contactInfo.setPhone(data1);
} else if ("vnd.android.cursor.item/email_v2".equals(mimetype)) {
contactInfo.setEmail(data1);
} else if ("vnd.android.cursor.item/name".equals(mimetype)) {
contactInfo.setName(data1);
}
}
dataCursor.close();
contactInfos.add(contactInfo);
}
cursor.close();
return contactInfos;
}
這裡用了巢狀查詢,聯絡人一多就會明顯變慢,屬於典型的 N+1 問題。可以改為一次撈出 data 表全部資料,在記憶體中依 raw_contact_id 分組,效能會好得多。
取回網頁文字內容的標準流程是:建立連線、設定逾時與請求方式、檢查回應碼、讀取輸入流並轉為字串。
URL url = new URL("https://www.sohu.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);// 設定連線逾時
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗");
InputStream is = conn.getInputStream();// 取得網絡回傳的輸入流
String result = readData(is, "GBK");
conn.disconnect();
// 第一個參數為輸入流,第二個參數為字符集編碼
public static String readData(InputStream inSream, String charsetName) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inSream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inSream.close();
return new String(data, charsetName);
}
別忘了在清單檔中宣告網路權限:
<!-- 訪問 internet 權限 --> <uses-permission android:name="android.permission.INTERNET"/>
下載二進位檔案的邏輯相同,只是把輸出目標換成 FileOutputStream:
URL url = new URL("https://photocdn.sohu.com/20100125/Img269812337.jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗");
InputStream is = conn.getInputStream();
readAsFile(is, new File("Img269812337.jpg"));
public static void readAsFile(InputStream inSream, File file) throws Exception {
FileOutputStream outStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inSream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inSream.close();
}
POST 的特徵是把參數放進請求本文,因此必須先開啟輸出,並正確設定 Content-Type 與 Content-Length,否則服務端收不到資料。
String requestUrl = "https://localhost:8080/itcast/contanctmanage.do";
Map<String, String> requestParams = new HashMap<String, String>();
requestParams.put("age", "12");
requestParams.put("name", "中國");
StringBuilder params = new StringBuilder();
for (Map.Entry<String, String> entry : requestParams.entrySet()) {
params.append(entry.getKey());
params.append("=");
params.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
params.append("&");
}
if (params.length() > 0) params.deleteCharAt(params.length() - 1);
byte[] data = params.toString().getBytes();
URL realUrl = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setDoOutput(true);// 發送 POST 請求必須允許輸出
conn.setUseCaches(false);// 不使用 Cache
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(data);
outStream.flush();
if (conn.getResponseCode() == 200) {
String result = readAsString(conn.getInputStream(), "UTF-8");
outStream.close();
System.out.println(result);
}
與表單的差別只在 Content-Type 改成 text/xml:
StringBuilder xml = new StringBuilder();
xml.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
xml.append("<M1 V=10000>");
xml.append("<U I=1 D=\"N73\">中國</U>");
xml.append("</M1>");
byte[] xmlbyte = xml.toString().getBytes("UTF-8");
URL url = new URL("https://localhost:8080/itcast/contanctmanage.do?method=readxml");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(xmlbyte.length));
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(xmlbyte);
outStream.flush();
if (conn.getResponseCode() != 200) throw new RuntimeException("請求url失敗");
InputStream is = conn.getInputStream();
String result = readAsString(is, "UTF-8");
outStream.close();
網路操作不能寫在主線程,否則會拋出 NetworkOnMainThreadException。標準解法是開子線程抓圖,再用 Handler 把結果送回主線程更新 UI。
public class MainActivity extends Activity {
protected static final int GET_IMAGE_SUCCESS = 1;
protected static final int SERVER_ERROR = 2;
protected static final int LOAD_IMAGE_ERROR = 3;
private ImageView iv_icon;
private EditText et_path;
// 在主線程建立訊息處理器
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case GET_IMAGE_SUCCESS:
iv_icon.setImageBitmap((Bitmap) msg.obj);
break;
case SERVER_ERROR:
Toast.makeText(MainActivity.this, "連接服務器錯誤", 0).show();
break;
case LOAD_IMAGE_ERROR:
Toast.makeText(MainActivity.this, "獲取圖片錯誤", 0).show();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_icon = (ImageView) findViewById(R.id.iv_icon);
et_path = (EditText) findViewById(R.id.et_path);
}
public void click(View view) {
final String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "路徑不能為空", 0).show();
return;
}
new Thread() {
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
// 不可直接更新介面,必須發送訊息
Message msg = new Message();
msg.obj = bitmap;
msg.what = GET_IMAGE_SUCCESS;
handler.sendMessage(msg);
} else {
handler.sendMessage(Message.obtain(handler, SERVER_ERROR));
}
} catch (Exception e) {
e.printStackTrace();
handler.sendMessage(Message.obtain(handler, LOAD_IMAGE_ERROR));
}
}
}.start();
}
}
這段程式仍留有明顯的改進空間:圖片沒有做快取,每次都重新下載;沒有做 downsample,大圖容易引發 OutOfMemoryError;線程也沒有共用的執行緒池。正式專案應改用成熟框架(如 Glide、Fresco)或至少自行實作記憶體與磁碟雙層快取。
原理與圖片版幾乎一致,只是把 BitmapFactory.decodeStream() 換成逐段讀流並轉字串:
public void click(View view) {
final String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "路徑不能為空", 0).show();
return;
}
new Thread() {
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
is.close();
String html = new String(bos.toByteArray(), "gbk");
Message msg = new Message();
msg.what = GET_HTML_FINISH;
msg.obj = html;
handler.sendMessage(msg);
} else {
handler.sendMessage(Message.obtain(handler, LOAD_ERROR));
}
} catch (Exception e) {
e.printStackTrace();
handler.sendMessage(Message.obtain(handler, LOAD_ERROR));
}
}
}.start();
}
登錄是最典型的「背景請求 + 回主線程提示」場景,同時通常搭配本地保存帳密的功能。Context 提供的不只是記憶體中的物件,還包含套件名與 /data/data/ 目錄等環境資訊,因此可直接用它開啟檔案。
public class LoginService {
/**
* 保存用戶信息到文件
*/
public static void saveUserInfoToFile(Context context, String username,
String password) throws Exception {
FileOutputStream fos = context.openFileOutput("info.txt", Context.MODE_PRIVATE);
// 格式:zhangsan##123456
fos.write((username + "##" + password).getBytes());
fos.close();
}
/**
* 讀取用戶的用戶名和密碼
*/
public static String readUserInfoFromFile(Context context) throws Exception {
File file = new File(context.getFilesDir(), "info.txt");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = br.readLine();
fis.close();
br.close();
return line;
}
/**
* 採用 http 的 post 方式提交數據到服務器
*/
public static String loginByHttpPost(String username, String password) throws Exception {
String path = "https://192.168.1.100:8080/web/LoginServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
String data = "username=" + URLEncoder.encode(username, "UTF-8")
+ "&password=" + URLEncoder.encode(password, "UTF-8");
// 必須設定請求頭參數,告知服務端這是表單類型
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length() + "");
conn.setConnectTimeout(5000);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
int code = conn.getResponseCode();
if (code == 200) {
return StreamUtils.readStream(conn.getInputStream());
}
return null;
}
}
Activity 端則是標準的 Handler 回呼寫法:
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case LOGIN:
Toast.makeText(getApplicationContext(), (String) msg.obj, 0).show();
break;
case ERROR:
Toast.makeText(getApplicationContext(), "連接網絡失敗...", 0).show();
break;
}
}
};
public void login(View view) {
final String username = et_username.getText().toString().trim();
final String password = et_password.getText().toString().trim();
if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "用戶名或者密碼不能為空", 0).show();
return;
}
if (cb_remeber_pwd.isChecked()) {
try {
LoginService.saveUserInfoToFile(this, username, password);
} catch (Exception e) {
e.printStackTrace();
}
}
new Thread() {
public void run() {
try {
String result = LoginService.loginByHttpClientPost(username, password);
Message msg = new Message();
msg.what = LOGIN;
msg.obj = result;
handler.sendMessage(msg);
} catch (Exception e) {
handler.sendMessage(Message.obtain(handler, ERROR));
}
}
}.start();
}
流轉換是重複出現的小工具,抽成獨立類別較乾淨:
public class StreamUtils {
/**
* 把 inputstream 的內容轉化為字符串
*/
public static String readStream(InputStream is) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
is.close();
return new String(bos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
自己寫線程加 Handler 的模式重複性太高,因此出現了許多封裝庫。以 loopj 的 AsyncHttpClient 為例,GET 與 POST 都只要一行:
// GET
String path = "https://192.168.1.100:8080/web/LoginServlet?username="
+ URLEncoder.encode(username) + "&password=" + URLEncoder.encode(password);
AsyncHttpClient client = new AsyncHttpClient();
client.get(path, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
Toast.makeText(getApplicationContext(), response, 0).show();
}
});
// POST
AsyncHttpClient postClient = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
postClient.post("https://192.168.1.100:8080/web/LoginServlet", params,
new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String content) {
super.onSuccess(content);
Toast.makeText(getApplicationContext(), content, 0).show();
}
});
這些範例反映的是早期 Android 的寫法,放在今天有幾處需要調整:onStart()、AsyncHttpClient、Apache HttpClient 都已被標記為過時;主線程更新 UI 建議改用 runOnUiThread()、LiveData 或 Kotlin 協程;一律應以 HTTPS 取代明文 HTTP,並在清單檔中關閉 usesCleartextTraffic。此外,把帳密明文寫入檔案並不安全,正式環境應改用 EncryptedSharedPreferences 或系統金鑰庫保存憑證。
Android 支付密碼輸入框的自定義實現
先看效果: 實現思路 關鍵點是:真正接收輸入的仍然是 EditText,但顯示圓點的並不是它,而是覆蓋在下層的六個 ImageView。做法是先用 Relative
音樂播放器App框架設計與實踐總結
音樂播放器 App 通常由界面層與服務層共同構成。界面負責展示音樂列表、歌手、專輯、播放詳情與搜索結果;服務則承擔音樂掃描、播放控制、後台續航與通知欄交互等核心能力。 界
用 WebView 做一個簡易瀏覽器:返回、前進、首頁與網址輸入實作
WebView 是 Android 中非常實用的元件,與 Safari、Chrome 同樣基於 WebKit 渲染引擎,能直接載入 HTML 來呈現介面。本文示範如何用它
應用耗電分析與優化:Battery Historian 實戰指南
在 Android 專案裡,電量消耗一直是最難量化、卻又最被用戶敏感的指標。使用者未必說得出你的產品有多少功能,但只要手機待機掉得比別人快,卸載的決定往往下得毫不留情。指