編輯:關於 Android 程式設計
UrlConnection 常用於通過網絡發送和獲取數據,數據可以是任意類型、任意長度。而 HttpURLConnection 專門用於發送和接收長度未知的流式數據。
它的使用可以拆成五步:
創建連接——調用 url.openConnection(),並轉型為 HttpURLConnection。
設置請求——URL 是最基本的信息,此外可以設置請求頭(數據類型、長度等)。
設置請求體——並非必需,若需要則必須先調用 setOutput(true)。
讀取響應——響應頭包含數據類型與長度;通過 getInputStream() 讀取響應體。如果沒有 body,會返回一個空流。
斷開連接——調用 disconnect() 釋放資源。
一個簡單示例:從遠程下載圖片並顯示到 ImageView。
ImageView imageView = (ImageView) findViewById(R.id.imageview);
URL url = new URL("https://www.jycoder.com/json/movies/1.jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
try {
InputStream in = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
imageView.setImageBitmap(bitmap);
} finally {
conn.disconnect();
}
除此之外,還有幾個值得掌握的知識點:
響應錯誤處理——響應異常時直接調 getInputStream() 會拋異常,此時可用 getErrorStream() 讀取錯誤信息,用 getHeaderFields() 查看響應頭。
Post Content——發送數據前先 setOutput(true)。為提升性能,若已知內容大小可用 setFixedLengthStreamingMode(int);若未知則用 setChunkedStreamingMode(int)。
HTTP Method——通過 setRequestMethod(String) 指定請求方法。
Cookie 與 Cache——HttpURLConnection 支持 CookieManager 與 CookieHandler 管理 Cookie,並提供 HttpResponseCache 類處理緩存。
Android 官方從 API 22 起已棄用 HttpClient,新項目應優先使用 HttpURLConnection 或第三方庫(如 OkHttp)。上面示例中出現的 DefaultHttpClient 僅為兼容老代碼保留。
AsyncTask 是一種異步執行機制。主線程不能執行耗時操作,否則會引發 ANR 甚至崩潰;AsyncTask 讓我們不必手動管理線程的創建與切換。它適合短時操作,長時間任務則應交給 Service 或 WorkManager。
三個泛型參數:
Params——啟動任務時傳入的參數,對應 new MyTask().execute(params)。
Progress——任務執行過程中的進度,配合 publishProgress() 與 onProgressUpdate() 使用。
Result——任務完成後返回的結果。
四個核心方法:
onPreExecute()——任務執行前回調,運行於 UI 線程,適合初始化進度條等。
doInBackground()——運行於後台線程,網絡請求等耗時操作都在這裡進行。
onProgressUpdate()——運行於 UI 線程,doInBackground 中調用 publishProgress() 時觸發,用於更新進度。
onPostExecute()——運行於 UI 線程,任務完成後回調。
提示:四個方法中只有 doInBackground() 在後台線程執行,其餘均在 UI 線程,因此更新界面的動作只能放在後三者中。
啟動與取消:必須在主線程實例化並執行 AsyncTask,且每個實例只能執行一次;任何時候都可以通過 cancel(true) 取消任務。
新建項目 UseAsyncTask,在 Manifest.xml 中加上網絡權限,然後編寫布局:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#1C9439"
android:gravity="center"
android:layout_margin="10dp"
android:padding="5dp"
android:text="豆瓣電影 Top10"
android:textColor="#fff"
android:textSize="24sp" />
<ImageView
android:id="@+id/movie_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="3dp"
android:background="#ffcc" />
</LinearLayout>
接著完成 MainActivity:
public class MainActivity extends ActionBarActivity {
private ImageView imageView;
private static final String URL = "https://www.jycoder.com/json/movies/2.jpg";
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(this);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setMessage("Loading...");
pDialog.setMax(100);
imageView = (ImageView) findViewById(R.id.movie_image);
new ImageDownloadTask().execute(URL);
}
public class ImageDownloadTask extends AsyncTask<String, Integer, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
@Override
protected Bitmap doInBackground(String... urls) {
HttpURLConnection connection = null;
Bitmap bitmap = null;
try {
URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(connection.getInputStream());
int length = connection.getContentLength();
int len, total = 0, value = 0;
byte[] data = new byte[1024];
while ((len = in.read(data)) != -1) {
total += len;
value = (int) ((total / (float) length) * 100);
publishProgress(value); // 回主線程更新進度
}
in.close();
bitmap = BitmapFactory.decodeStream(
connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) connection.disconnect();
}
return bitmap;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pDialog.setProgress(values[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
imageView.setImageBitmap(bitmap);
}
}
}
運行效果:

這部分內容本身並不難,真正的門檻在於理解 UI 線程的約束,以及判斷什麼場景該用 AsyncTask、什麼場景該用 Service。推薦閱讀 Android 官方文檔中的 Processes and Threads 章節,把線程模型徹底理清楚。另外需要提醒的是,AsyncTask 在 API 30 中已被標記為廢棄,新項目建議改用 Kotlin 協程或 LiveData + 線程池的方案。
Android 常用號碼功能實作:SQLite 搭配 ExpandableListView
不少 Android 手機都內建了常用號碼功能,例如訂餐電話、公共服務電話、航空機票等分類,點一下對應號碼就會跳出撥號介面。本文就來實作一個類似的小範例。 一、實作原理
用 GridLayout 打造自定義日曆控件
系統沒有現成的日曆選擇器?那就自己畫一個。GridLayout 天生適合這種棋盤式排版——設定行數與列數,把日期按鈕一個個填進去,再補上月份推導邏輯,一個完整的日曆控件就
全面解讀 Android Adapter 數據適配器:從原理到實戰
一、Adapter 是什麼 在 Android 開發裡,Adapter(數據適配器)扮演著「橋樑」的角色,負責把底層的數據源與上層的 View 連接起來。簡單來說,你只要
Android 日期與時間選擇對話框實作
Android 提供 DatePickerDialog 與 TimePickerDialog,讓使用者能以系統標準介面選擇日期與時間。兩者都屬於 AlertDialog