編輯:關於 Android 程式設計
做一個「輸入網址、抓圖、顯示」的小工具,剛好把資源管理、版面配置與網路請求串在一起。以下按開發順序走一遍。
養成習慣,畫面上出現的文字不要寫死在版面檔裡。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">網絡圖片查看器</string>
<string name="imgpath">輸入圖片地址:</string>
<string name="getBtn">獲取圖片</string>
<string name="error">獲取圖片失敗</string>
</resources>
用垂直 LinearLayout 依序排下來:提示文字、輸入框、按鈕、顯示區。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/imgpath" />
<EditText
android:id="@+id/imgpathInput"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text" />
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/getBtn" />
<ImageView
android:id="@+id/imgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
為了方便閱讀,這裡把網路方法都放在同一個類別。實務上建議把兩個 static 方法抽到工具類中,結構會清楚很多。
public class MainActivity extends Activity implements OnClickListener {
private EditText pathText;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pathText = (EditText) findViewById(R.id.imgpathInput);
imageView = (ImageView) findViewById(R.id.imgView);
Button button = (Button) findViewById(R.id.getBtn);
button.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
String path = pathText.getText().toString();
byte[] data = null;
try {
data = getImgData(path);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
return; // 取得失敗就不該繼續解碼
}
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmap);
}
/** 抓取圖片並回傳位元組陣列 */
public static byte[] getImgData(String path) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream in = conn.getInputStream();
return read(in);
}
Log.d("tong.getImg", "服務器無響應");
return null;
}
/** 把輸入流讀進記憶體並轉為 byte[] */
public static byte[] read(InputStream in) throws IOException {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[10240];
int len = 0;
while ((len = in.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
return outStream.toByteArray();
}
}
<uses-permission android:name="android.permission.INTERNET"/>
上面這段程式碼能跑,但直接搬上線會遇到幾個麻煩,值得逐一說明。
網路請求寫在主執行緒。 從 Android 3.0(Honeycomb)開始,NetworkOnMainThreadException 會直接讓程式崩潰。必須改用背景執行緒,例如 AsyncTask、Kotlin 協程或 ExecutorService。
缺少例外處理的完整性。 getImgData() 可能回傳 null,而 BitmapFactory.decodeByteArray() 收到 null 會丟出 NullPointerException。原範例的 catch 區塊沒有 return,會帶著 null 繼續往下走。這類「失敗路徑沒走完」的問題在網路程式裡特別常見。
沒有連線關閉與 read timeout。 只設了 connectTimeout,還應加上 setReadTimeout(),並在 finally 中確實關閉串流,否則弱網環境下容易累積洩漏。
整張圖直接載入記憶體。 大圖會輕易觸發 OOM。正確做法是先讀取圖片邊界資訊決定縮放比例(inJustDecodeBounds + inSampleSize),再進行解碼。
重複按鈕會觸發多次請求。 應在請求期間停用按鈕或顯示進度指示。
若只是想完成「顯示網路圖片」這件事,成熟方案是直接用 Glide 或 Coil:一行 Glide.with(context).load(url).into(imageView) 就涵蓋了背景執行緒、快取、縮放、錯誤佔位圖與生命週期管理。上述手刻版本的價值在於理解底層發生了什麼——特別是當你遇到 OOM 或需要客製解碼流程時,這些知識就會派上用場。
Android App 架構經驗總結:從 API 設計到分層與環境分離
架構因人而異,也因專案而異——不同的架構師有不同看法,不同的產品需求也會導向不同方案。但有些東西是共通的,是所有架構師都必須面對的問題:API 該怎麼設計?架構該怎麼分層
Android 透過 JSON 將資料寫入 MySQL 的完整實作(寫入篇)
上一篇講了讀取,這篇來談寫入。Android 把本地資料(例如定位、感測器讀數)上傳到資料庫,流程是:把參數封裝成 POST 表單 → 送到 PHP → PHP 寫入 M
在 Activity、Service、Window 中監聽 Home 鍵與返回鍵的實踐与思考
關於按鍵監聽,相信很多人都已經很熟悉,所以本文不會在基礎部分花費太多筆墨,而是重點探討後半段——如何把監聽到的事件「傳遞出來」,尤其是在 Window 場景下的巧妙做法。
(16)XML/DTD/Sax 解析/Schema 語法簡介
Xml 概述:Java 是跨平台的開發語言,而 XML 是跨平台的數據傳輸格式。XML 是一種標簽語言,語法類似 HTML。 關於 XML 的亂碼問題: 1. 文檔聲明