編輯:關於 Android 程式設計
以下 these 都是實際專案裡累積下來的小知識,從開機客製、系統屬性讀取、Git 操作到效能與記憶體優化,按主題分好類,需要時直接查。
換開機 Logo:把圖片放進根目錄的 7627a_splash,執行 splash.sh,再把 splash.txt 裡的數值複製貼到 bootable/bootloader/lk/target/專案名/include/target/splash.h,最後 make aboot。
產出檔在 out/target/product/專案名/ 底下:emmc 平台取 emmc_appsboot.mbn 與 emmc_appsboothd.mbn,nand 平台取 appsboot.mbn 與 appsboothd.mbn,用 QTS 在 Windows 下燒寫進去。
換開關機動畫:把做好的 bootanimation.zip 與 shutdownanimation.zip 放到 /system/core/rootdir/專案名/,或直接 push 到機器的 system/media/ 下,重開機即可看到效果。
Java 層:
import android.os.SystemProperties;
// 判斷機型
private boolean mIsA100 =
"msm7627a_v12_a100".equals(SystemProperties.get("ro.product.name"));
// 把記憶體設為內部儲存
if ("1".equals(SystemProperties.get("persist.sys.emmcsdcard.enabled"))) { ... }
C++ 層:
#include <cutils/properties.h>
char value[PROPERTY_VALUE_MAX];
property_get("sys.secpolicy.camera.disabled", value, "0");
# 查某個人的所有提交 git log --author="xxxx" # 進入 fastboot 模式 adb reboot-bootloader # *#20110606# 可開啟測試開關 # 套用命名 patch cd small-src git am ~/patch/0001-trival-patch.patch # 抓取帶時間的 log adb logcat -v time >> log.txt # 把 log 存到機內並在背景執行 adb shell logcat -v time > /data/log.txt & # 抓網路封包 tcpdump -i any -p -s 0 -w /sdcard/pcap.pcap # 查看記憶體資訊 cat /proc/meminfo # 直接輸入文字到 EditText adb shell input text asdfsff
是否鎖屏:用 Intent.ACTION_USER_PRESENT 廣播代表已解鎖;判斷鎖屏狀態則用 KeyguardManager。
KeyguardManager mKeyguardManager =
(KeyguardManager) getSystemService(KEYGUARD_SERVICE);
if (mKeyguardManager.inKeyguardRestrictedInputMode()) {
// 目前處於鎖屏狀態
}
耳機插拔:監聽 Intent.ACTION_HEADSET_PLUG;查詢目前狀態用:
AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE); return audio.isWiredHeadsetOn();
音樂是否播放中:
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager.isMusicActive()) { ... }
結束本進程:
android.os.Process.killProcess(android.os.Process.myPid());
隱藏別人開的輸入法:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
隱藏本 App 開的輸入法:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
指定應用程式的最小堆積:
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION); VMRuntime.getRuntime().setMinimumHeapSize(CWJ_HEAP_SIZE); private final static float TARGET_HEAP_UTILIZATION = 0.75f; private final static int CWJ_HEAP_SIZE = 6 * 1024 * 1024;
# Monkey 壓力測試 adb shell monkey -v -p com.android.XXX --pct-nav 0 --pct-majornav 0 \ --pct-anyevent 0 --ignore-security-exceptions --throttle 100 -v 50000 # CTS 4.1:單一 case run cts -c android.hardware.cts.CameraGLTest \ -m testCameraToSurfaceTextureMetadata # CTS 4.1:整個測試包 run cts -c android.hardware.cts.CameraGLTest # CTS 2.3:單一 case start --plan CTS -t android.hardware.cts.CameraGLTest#testCameraToSurfaceTextureMetadata # CTS 2.3:整個測試包 start --plan CTS -p android.hardware.cts.CameraGLTest
不經資料庫直接取影片第一幀:用反射呼叫 MediaMetadataRetriever,好處是可以跳過跨版本的 API 差異問題。
public static Bitmap createVideoThumbnail(Context context, Uri uri) {
String className = "android.media.MediaMetadataRetriever";
Object retriever = null;
Method release = null;
try {
retriever = Class.forName(className).newInstance();
Method setModeMethod = Class.forName(className)
.getMethod("setMode", int.class);
setModeMethod.invoke(retriever,
MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
Method setDataSourceMethod = Class.forName(className)
.getMethod("setDataSource", Context.class, Uri.class);
setDataSourceMethod.invoke(retriever, context, uri);
Method captureFrameMethod = Class.forName(className)
.getMethod("captureFrame");
release = Class.forName(className).getMethod("release");
return (Bitmap) captureFrameMethod.invoke(retriever);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (release != null) release.invoke(retriever);
} catch (Exception e) { /* 清理時的失敗就忽略 */ }
}
return null;
}
抓影片 bit stream 與 YUV:
adb shell setprop vidc.dec.log.out 1 # dump 輸出的 yuv setprop vidc.dec.log.in 1 # dump bit stream # 檔案會出現在 /data/misc/media,需具備寫入權限
開啟 OMX 與 kernel log:
adb shell setprop vidc.debug.level 7 adb shell su cd /d/msm_vidc echo 0x1003 > debug_level echo 0x3F > fw_level
8x25 系列已支援的 sensor:後照 500 萬有 ov5640、ov5647、s5k4e1;前照 30 萬有 gc0339、ov9726、ov7692。設定檔在 kernel/arch/arm/configs/msm8x25_d8_eg530-perf_defconfig。
鏡像翻轉有兩個可下手的地方,依情況改其中一處即可:一是在 CameraService.cpp 的 sendCommand() 裡攔截 CAMERA_CMD_SET_DISPLAY_ORIENTATION,讀取呼叫方 /proc/<pid>/cmdline 取得 package name,對特定 App(如微信、手機 QQ)加補 180 度:
orientation = getOrientation(
isqqpimsecure ? (arg1 + 180) : arg1,
mCameraFacing == CAMERA_FACING_FRONT);
二是在 getCameraInfo() 裡針對特定 App 直接調整回傳的 orientation:
if (!isv10_yd && strcmp(buf, "com.tencent.mm") == 0) {
cameraInfo->orientation += 180;
} else if (strcmp(buf, "com.google.android.talk") == 0) {
cameraInfo->orientation += 180;
}
這種「依呼叫來源給不同參數」的做法能解眼前的相容問題,但本質上是特例修補,機型與 App 一多就很難維護,長期還是應該從 driver 或 HAL 層把方向定義統一。
手機沒權限時取得寫入權:
mount -o remount /dev/block/mtdblock1 /system chmod 777 system/app
新增 USB 裝置:在 /etc/udev/rules.d 下建立規則檔。
外接 U 盤掛載失敗:多半是 FAT 檔案系統髒了,在 DOS 下執行 chkdsk F: /f 修復即可。
依專案決定要打包哪份 AndroidManifest:
ifeq ($(filter msm8x25q_d10_j320c, $(TARGET_PRODUCT)), msm8x25q_d10_j320c) LOCAL_MANIFEST_FILE := d10_j320c/AndroidManifest.xml endif
防止 OOM 的解碼範式:先只讀尺寸、算縮放比例,再真正解碼,這是處理大圖的標準寫法。
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// 第一趟只讀邊界,不配置像素記憶體
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// 計算縮放比例
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// 第二趟真正解碼
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
其他小技巧:Java 裡的 +-×÷ 可用 +\u2212\u00d7\u00f7 表示;直接列印陣列內容用 Arrays.toString(陣列名) 最省事。
這份清單的價值不在每一條都驚艷,而在它們都是實測可用、能省下大量查文件和試錯時間的具體解法。建議存成自己的 cheatsheet,遇到對應場景時直接抄。
Android 仿微信語音聊天:錄音、波形與播放完整實作
參考自「Android 模仿微信語音聊天功能」,原始碼跑起來有些問題,我自己改了一輪,目前基本沒什麼大毛病。 先看效果: 一、三個版面檔 activity_main.x
Android 自定義高仿微信 PopupWindow:兩種實現思路
兩種思路本篇分享一種高仿微信功能的 PopupWindow 實作方式,例如掃一掃入口這類常見的浮動操作視窗。實作上可以透過自定義彈窗類,也可以透過獨立 Activity
ViewPager 擴展詳解:打造帶導航的 ViewPagerIndicator(含圖片快取與非同步載入)
用過 ViewPager 的人都知道,它在「橫向切換頁面」這件事上表現很好,但導航樣式的部分預設值相當陽春。GitHub 上有個很不錯的開源專案 ViewPagerInd
Android ListView 基礎入門:版面、Adapter 與複用優化
ListView 簡介ListView 是 Android 中非常常見的列表控制項,適合用來展示大量資料。它的核心概念是透過 Adapter 將資料綁定到列表,再利用 I