編輯:關於 Android 程式設計
上一節我們用 AsyncTask 完成了非同步下載圖片,但留下了三個問題:無網路時點擊會崩潰、進度條沒有真的更新、以及只能用系統內建的 ProgressBar。這次逐一解決。
回頭看那段落下的程式碼:
try {
HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
connection.setDoInput(true);
connection.connect();
inputStream = connection.getInputStream();
downloadImg = BitmapFactory.decodeStream(inputStream);
}
原因很明顯:沒有網路就拿不到串流。由於我們沒做圖片快取,每次點擊都會重新連線,一旦連線失敗 inputStream 就是 null,把 null 丟給 decodeStream 自然炸掉。
所以第一層防護是判斷串流是否為 null。但更好的做法是「一開始就不要讓使用者點」。
WifiManager manager = (WifiManager) getSystemService(WIFI_SERVICE); int wifiState = manager.getWifiState(); // wifi 狀態
狀態常數如下:
WIFI_STATE_DISABLING = 0; // 停用中 WIFI_STATE_DISABLED = 1; // 不可用 WIFI_STATE_ENABLING = 2; // 啟動中 WIFI_STATE_ENABLED = 3; // 已就緒 WIFI_STATE_UNKNOWN = 4; // 未知
看起來很像路由器啟動的過程,但仔細想就會發現:WIFI_STATE_ENABLED 只代表「無線網路已開啟」,並不代表「連上網路」,更不代表「能連上網際網路」。用它來判斷網路可用性會誤判。
另外別忘了權限:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
ConnectivityManager cManager =
(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mInfo = cManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean available = mInfo.isAvailable();
這個 API 才是真正回答「網路是否可用」的問題。
但只判斷網路還不夠——URL 為空的一樣會炸。考慮到健壯性,兩個條件都要 AND,並據此決定按鈕是否可點。
Button downBtn = (Button) findViewById(R.id.downBtn);
if (mInfo.isAvailable() && !TextUtils.isEmpty(url)) {
downBtn.setClickable(true);
downBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new ImageDownloadTask(MainActivity.this, img, bar).execute(url);
}
});
} else {
downBtn.setClickable(false);
downBtn.setOnClickListener(null);
Toast.makeText(MainActivity.this, "當前無網路", Toast.LENGTH_SHORT).show();
}
補充一句:在正式專案裡,判斷網路狀態通常不會寫在 Activity 裡,而是註冊一個網路狀態變化的廣播接收器統一處理。這部分留待談廣播時再說。
要做進度條,需要三樣東西:總長度、當前長度、以及一個通知刷新的方法。關鍵程式碼:
int totalLength; // 總長度
URL imageUrl = new URL(params[0]);
int length = -1;
InputStream inputStream = null;
HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
connection.setDoInput(true);
connection.connect();
inputStream = connection.getInputStream();
totalLength = connection.getContentLength(); // 關鍵:取得總大小
if (inputStream != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count = 0;
while ((length = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, length);
count += length;
// 通知 onProgressUpdate 更新進度
publishProgress((int) ((count / (float) totalLength) * 100));
}
byte[] data = baos.toByteArray();
downloadImg = BitmapFactory.decodeByteArray(data, 0, data.length);
return "ok";
}
然後在 UI 端接收:
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mBar.setProgress(progress[0]);
}
注意 totalLength 若為 -1(伺服器未帶 Content-Length,例如 chunked 編碼),進度計算會變成負數或異常,實務上要加一層判斷退回「不確定進度」模式。
daimajia 的 NumberProgressBar 是一個把數字直接畫在條上的開源元件,視覺比系統 ProgressBar 好得多。專案在 github.com/daimajia/NumberProgressBar,Eclipse 與 Android Studio 的匯入方式都有說明。
版面配置:
<RelativeLayout 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"
tools:context=".MainActivity">
<TextView
android:id="@+id/hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/downBtn"
android:layout_below="@id/hello"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="down"
android:textColor="@android:color/black"
android:textSize="20sp" />
<ImageView
android:id="@+id/img"
android:layout_below="@id/downBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:visibility="gone" />
<com.daimajia.numberprogressbar.NumberProgressBar
android:id="@+id/bar"
android:layout_below="@id/downBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
</RelativeLayout>
與其把一堆屬性寫在標籤上,用 style 集中管理更清爽:
<style name="NumberProgressBar_Funny_Orange">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">match_parent</item>
<item name="max">100</item>
<item name="progress">0</item>
<item name="progress_unreached_color">#CCCCCC</item>
<item name="progress_reached_color">#FF530D</item>
<item name="progress_text_size">10sp</item>
<item name="progress_text_color">#FF530D</item>
<item name="progress_reached_bar_height">1.5dp</item>
<item name="progress_unreached_bar_height">0.75dp</item>
</style>
這個 style 涵蓋了寬高、最大值、進度、顏色、字級等常用屬性,之後套用 style="@style/NumberProgressBar_Funny_Orange" 即可。若匯入後找不到 style,手動把它的 attrs 資源複製進來也能解決。
public class ImageDownloadTask extends AsyncTask<String, Integer, String> {
private Bitmap downloadImg;
private NumberProgressBar mBar;
private Context mContext;
private ImageView netImageView;
public ImageDownloadTask(Context context, ImageView imageView, NumberProgressBar bar) {
this.mContext = context;
this.netImageView = imageView;
this.mBar = bar;
}
@Override
protected void onPreExecute() {
mBar.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(String... params) {
int totalLength;
InputStream inputStream = null;
try {
URL imageUrl = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) imageUrl.openConnection();
connection.setDoInput(true);
connection.connect();
inputStream = connection.getInputStream();
totalLength = connection.getContentLength();
if (inputStream != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count = 0;
int length;
while ((length = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, length);
count += length;
publishProgress((int) ((count / (float) totalLength) * 100));
}
byte[] data = baos.toByteArray();
downloadImg = BitmapFactory.decodeByteArray(data, 0, data.length);
return "ok";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mBar.setProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
mBar.setVisibility(View.GONE);
netImageView.setVisibility(View.VISIBLE);
netImageView.setImageBitmap(downloadImg);
Toast.makeText(mContext, "加載完畢", Toast.LENGTH_LONG).show();
}
}
執行看看:


值得誠實指出的是,這份程式碼仍有幾處會在真實環境出狀況:totalLength 為 -1 時進度計算失效;onPostExecute 未檢查 downloadImg 是否為 null,載入失敗會直接 NPE;以及 ConnectivityManager.getNetworkInfo() 在 Android 10(API 29)已被標記為 deprecated,判斷網路狀態現在推薦用 NetworkCapabilities。
另外,NetworkOnMainThread 之外,圖片下載建議加上磁碟快取(如 Glide、Picasso 已內建),否則每次進入頁面都要重新下載。下次再來談動態設定 progress 的樣式,以及自己動手做一個 progressbar。
從零開始學 Android:內部儲存(Internal Storage)實作教學(三十六)
把資料寫入內部儲存,基本步驟只有三步: 1. 呼叫 openFileOutput(),傳入檔名與操作模式,取得 FileOutputStream 物件。 2. 以 wri
百度地圖圖層玩法:普通圖、衛星圖、實時路況與城市熱力圖
一張地圖不只有「地圖」這一種樣貌。切換衛星影像、疊加實時路況、顯示城市熱力分布——這些效果在百度地圖 Android SDK 裡都只要一行屬性設定就能搞定。本文帶你看懂
自定義 View 時如何加上自己的監聽器
監聽器在 Java 裡無所不在。寫自定義控制項時,往往需要對外通報某些狀態變化,這時就得自己定義監聽器。它與 C++ 的回呼函式概念相通:初始化時把函式交出去,事件發生時
Android 7.0 Nougat 開發者新特性梳理:分屏、通知與功耗
Android 7.0 在走過五個開發者預覽版本之後,於 8 月 22 日正式推送,版本名定為 Nougat(牛軋糖)。 官方總結的主要更新如下。 性能 JIT 編譯器