Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 專案實用工具類:網路狀態檢查與 Bitmap 處理

編輯:關於 Android 程式設計

延續專案學習系列,這篇整理兩塊幾乎每個 App 都會用到的基礎設施:網路狀態判斷,以及圖片處理工具類。

一、網路連線相關

a. 檢查網路是否可用

/**
 * 檢查網路是否可用
 */
public static boolean detect(Context context) {
    ConnectivityManager manager = (ConnectivityManager) context
            .getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (manager == null) {
        return false;
    }
    NetworkInfo networkinfo = manager.getActiveNetworkInfo();
    if (networkinfo == null || !networkinfo.isAvailable()) {
        return false;
    }
    return true;
}

b. 檢查 WIFI 是否連接

/**
 * 檢查當前 WIFI 是否連接——兩層意思:是否連接,且連接的是不是 WIFI
 * @return true 表示網路處於連接狀態且為 WIFI,否則 false
 */
public static boolean isWifiConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null && info.isConnected()
            && ConnectivityManager.TYPE_WIFI == info.getType()) {
        return true;
    }
    return false;
}

c. 檢查行動網路是否連接

/**
 * 檢查當前 GPRS 是否連接——兩層意思:是否連接,且連接的是不是行動網路
 */
public static boolean isGprsConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null && info.isConnected()
            && ConnectivityManager.TYPE_MOBILE == info.getType()) {
        return true;
    }
    return false;
}

d. 檢查當前是否已連接

/**
 * 檢查當前是否連接
 */
public static boolean isConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null && info.isConnected()) {
        return true;
    }
    return false;
}

這四個方法的共同邏輯是「先取 ConnectivityManager,再取 ActiveNetworkInfo,最後檢查狀態」。記得在 manifest 加上 android.permission.ACCESS_NETWORK_STATE,否則 getActiveNetworkInfo() 會回傳 null。

另外要提醒:這組 API 只能告訴你「有沒有連上網路」,不能告訴你「網路通不通」。連上沒有 DSN 出口的 Wi-Fi 時,isConnected() 依然回傳 true。若要真正確認可用性,仍需搭配一次輕量級的連線探測(例如 ping 或 HEAD 請求)。此外 NetworkInfo 已在 API 29 之後被標記為不建議使用,新專案建議改用 NetworkCapabilities 搭配 registerDefaultNetworkCallback。

二、Bitmap 工具類

圖片處理是記憶體問題的重災區。以下工具類涵蓋解碼、縮放、格式轉換、圓角處理與檔案存取:

package com.example.syc_util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import android.content.Context;

public class BitmapTools {

    /** 依輸入流取得位圖 */
    public static Bitmap getBitmap(InputStream is) {
        return BitmapFactory.decodeStream(is);
    }

    /** 依輸入流與縮小比例取得位圖 */
    public static Bitmap getBitmap(InputStream is, int scale) {
        Options opts = new Options();
        opts.inSampleSize = scale;
        return BitmapFactory.decodeStream(is, null, opts);
    }

    /**
     * 依指定寬高、保持長寬比縮小讀取 byte[] 中的圖片
     * 關鍵是先只讀邊界資訊,決定縮放比後才真正解碼
     */
    public static Bitmap getBitmap(byte[] bytes, int width, int height) {
        Options opts = new Options();
        opts.inJustDecodeBounds = true;   // 只讀尺寸,不配置像素記憶體
        BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
        opts.inJustDecodeBounds = false;

        int scaleX = opts.outWidth / width;
        int scaleY = opts.outHeight / height;
        opts.inSampleSize = scaleX > scaleY ? scaleX : scaleY;
        Log.i("info", "scale : " + opts.inSampleSize);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
    }

    /** 依指定寬高等比例縮小讀取指定路徑的圖片 */
    public static Bitmap getBitmap(String fileName, int width, int height) {
        String abPath = fileName;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(abPath, options);

        float realWidth = options.outWidth;
        float realHeight = options.outHeight;
        if (realHeight == 0 || realWidth == 0) {
            return null;
        }

        int scaleX = options.outWidth / width;
        int scaleY = options.outHeight / height;
        options.inSampleSize = scaleX > scaleY ? scaleX : scaleY;
        options.inJustDecodeBounds = false;   // 這次才真的要讀出具體像素
        return BitmapFactory.decodeFile(abPath, options);
    }

    /** 依指定寬高拉伸讀取指定路徑的圖片 */
    public static Bitmap getBitmapDeng(String fileName, int width, int height) {
        String abPath = fileName;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(abPath, options);

        float realWidth = options.outWidth;
        float realHeight = options.outHeight;
        if (realHeight == 0 || realWidth == 0) {
            return null;
        }

        float scaleX = width / realWidth;
        float scaleY = height / realHeight;
        options.inSampleSize = (int) (scaleX > scaleY ? scaleX : scaleY);

        Matrix matrix = new Matrix();
        matrix.postScale(scaleX, scaleY);

        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(abPath, options);
        return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    }

    /** Bitmap 轉 byte[] */
    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /** 依路徑從檔案讀取位圖 */
    public static Bitmap getbiBitmap(String path) {
        return BitmapFactory.decodeFile(path);
    }

    /** 儲存位圖到指定位置 */
    public static void saveBitmap(String path, Bitmap bitmap) throws IOException {
        if (path != null && bitmap != null) {
            File file = new File(path);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            OutputStream stream = new FileOutputStream(file);
            String name = file.getName();
            String end = name.substring(name.lastIndexOf(".") + 1);
            if ("png".equals(end)) {
                bitmap.compress(CompressFormat.PNG, 100, stream);
            } else {
                bitmap.compress(CompressFormat.JPEG, 100, stream);
            }
            stream.close();
        }
    }

    /** 把串流內容解析成 byte 陣列 */
    public static byte[] readStream(InputStream inStream) throws Exception {
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }

    /** 把 byte 陣列轉為 ImageView 可用的 Bitmap */
    public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) {
        if (bytes != null) {
            if (opts != null) {
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
            }
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        }
        return null;
    }

    /** 圖片縮放到指定寬高 */
    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale((float) w / width, (float) h / height);
        return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    }

    /** 等比縮放並回收原圖 */
    public static Bitmap zoomBitmapDeng(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) w / width);
        float scaleHeight = ((float) h / height);
        float scale = scaleWidth > scaleHeight ? scaleWidth : scaleHeight;
        matrix.postScale(scale, scale);
        Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        bitmap.recycle();
        return newBmp;
    }

    /** 依比例縮放 */
    public static Bitmap zoomBitmap(Bitmap bitmap, float scale) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);
        return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
    }

    /** 把 byte 陣列存成檔案 */
    public static File getFileFromBytes(byte[] b, String outputFile) {
        BufferedOutputStream stream = null;
        File file = null;
        try {
            file = new File(outputFile);
            stream = new BufferedOutputStream(new FileOutputStream(file));
            stream.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return file;
    }

    /**
     * 取得圓角位圖
     * @param pixels 圓角度數,數值越大圓角越大
     */
    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(
                bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        // 關鍵:用 SRC_IN 混合模式,只保留重疊區域
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    /** 判斷 SD 卡是否可用 */
    public static String getPicture(int fileItem, Context context) {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(context, "請插入 SD 卡", Toast.LENGTH_LONG).show();
            return null;
        }
        return null;
    }
}

這份工具類裡最值得學的三個技巧

一、兩段式解碼(inJustDecodeBounds)。這是 Bitmap 記憶體優化的核心手法。第一次把 inJustDecodeBounds 設為 true,BitmapFactory 只讀取圖片的寬高資訊而不配置像素記憶體;算出縮放比、設定 inSampleSize 之後,第二次才真正解碼。少了這一步,載入一張 4000×3000 的照片就可能直接 OOM。工具類裡三個 getBitmap 重載全部用了這個技巧,值得照抄。

二、inSampleSize 取的是較大的比例。程式碼用 scaleX > scaleY ? scaleX : scaleY,也就是取兩軸中縮得更狠的那個,確保結果不會超出目標尺寸。反過來若取較小值,圖片會比預期大,仍有爆記憶體的風險。

三、圓角處理用 PorterDuff.Mode.SRC_IN。先畫一個圓角矩形當遮罩,再用 SRC_IN 混合模式把原圖畫上去——只有兩者重疊的部分會保留,圓角就自然出現了。setAntiAlias(true) 則是讓圓角邊緣不鋸齒的必要設定,少了它邊緣會出現毛糙的鋸齒。

可以更好的地方

recycle() 的使用要謹慎。程式中 zoomBitmapDeng 呼叫了 bitmap.recycle(),但如果呼叫方之後還要使用原圖,就會拿到一個已回收的物件而崩潰。在 Android 4.0 以上,Bitmap 的像素記憶體已改由 Java 堆管理,GC 能自行回收,手動 recycle 反而容易出問題。建議移除,把記憶體管理交給 GC。

uncompressed PNG 不一定最好。所有 Bitmap2Bytes 都固定用 PNG 編碼,但 PNG 是無失真壓縮,檔案通常比 JPEG 大得多。若用途是網路傳輸且不需要透明背景,改用 JPEG 並調整 quality 會省下大量流量。

檔案寫入要養成關閉習慣。範例中 saveBitmap 沒有關閉 OutputStream,這是資源洩漏。用 try-with-resources 或 finally 區塊確保關閉,是基本紀律。

外部儲存權限。getPicture 檢查了 MEDIA_MOUNTED,但 Android 6.0 以後讀寫外部儲存還需要 READ/WRITE_EXTERNAL_STORAGE 的執行期授權;Android 10 之後更導入 Scoped Storage,直接寫任意路徑的做法已被限制,應改用 MediaStore 或 App 專用目錄。

Mr.傅:學習筆記。歡迎轉載,轉載請註明出處,謝謝。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved