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

Android 開發實用小技巧大集合

編輯:關於 Android 程式設計

日常開發中,難免會累積一些常用卻瑣碎的小技巧。以下依「介面、網絡、圖片、系統」四大主題,整理一批可直接取用的實用程式碼片段。

一、介面相關

dip 轉 px:

public int convertDipOrPx(int dip) {
    float scale = getResources().getDisplayMetrics().density;
    return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
}

取得當前窗體並加入自訂 view:

getWindowManager().addView(overlay,
    new WindowManager.LayoutParams(
        LayoutParams.WRAP_CONTENT,
        LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_APPLICATION,
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
        PixelFormat.TRANSLUCENT));

二、網絡相關

判斷網絡是否可用:

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager mgr =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] info = mgr.getAllNetworkInfo();
    if (info != null) {
        for (int i = 0; i < info.length; i++) {
            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                return true;
            }
        }
    }
    return false;
}

判斷是否為 Wifi 連線:

public static boolean isWifiActive(Context icontext) {
    Context context = icontext.getApplicationContext();
    ConnectivityManager connectivity =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] info;
    if (connectivity != null) {
        info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {
                    return true;
                }
            }
        }
    }
    return false;
}

取得下載檔案的真實名稱(透過 Content-Disposition,若無則回退解析 URL):

public String getReallyFileName(String url) {
    String filename = "";
    URL myURL;
    HttpURLConnection conn = null;
    if (url == null || url.length() < 1) {
        return null;
    }
    try {
        myURL = new URL(url);
        conn = (HttpURLConnection) myURL.openConnection();
        conn.connect();
        conn.getResponseCode();
        URL absUrl = conn.getURL(); // 取得真實 Url
        filename = conn.getHeaderField("Content-Disposition");
        if (filename == null || filename.length() < 1) {
            filename = URLDecoder.decode(absUrl.getFile(), "UTF-8");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return filename;
}

三、圖片相關

Bitmap 轉 Byte 陣列(微信分享會用到):

public byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
    if (needRecycle) {
        bmp.recycle();
    }
    byte[] result = output.toByteArray();
    try {
        output.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

Resources 轉 Bitmap:

public Bitmap loadBitmap(Resources res, int id) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inPreferredConfig = Bitmap.Config.RGB_565;
    opt.inPurgeable = true;
    opt.inInputShareable = true;
    InputStream is = res.openRawResource(id);
    return BitmapFactory.decodeStream(is, null, opt);
}

四、系統相關

判斷 APK 是否已安裝:

public boolean checkApkExist(Context context, String packageName) {
    if (packageName == null || "".equals(packageName)) {
        return false;
    }
    try {
        context.getPackageManager().getApplicationInfo(
                packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
        return true;
    } catch (NameNotFoundException e) {
        return false;
    } catch (NullPointerException e) {
        return false;
    }
}

安裝 APK:

public void installApk(Context context, String strFileAllName) {
    File file = new File(strFileAllName);
    Intent intent = new Intent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setAction(Intent.ACTION_VIEW);
    String type = "application/vnd.android.package-archive";
    intent.setDataAndType(Uri.fromFile(file), type);
    context.startActivity(intent);
}

卸載 APK:

public void UninstallApk(Context context, String strPackageName) {
    Uri packageURI = Uri.parse("package:" + strPackageName);
    Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
    context.startActivity(uninstallIntent);
}

判斷 SD 卡是否可用:

public boolean CheckSD() {
    return android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED);
}

取得檔案 MD5 值:

public String getFileMD5(File file) {
    if (!file.isFile()) {
        return null;
    }
    MessageDigest digest = null;
    FileInputStream in = null;
    byte buffer[] = new byte[1024];
    int len;
    try {
        digest = MessageDigest.getInstance("MD5");
        in = new FileInputStream(file);
        while ((len = in.read(buffer, 0, 1024)) != -1) {
            digest.update(buffer, 0, len);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    BigInteger bigInt = new BigInteger(1, digest.digest());
    return bigInt.toString(16);
}

這些片段看似零散,卻都是實戰中反覆用到的「瑞士刀」。整理成自己的工具類,能在開發時省去不少重複查找的時間。

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