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

Android 開發實戰小抄:29 個日常會用到的技巧與指令

編輯:關於 Android 程式設計

以下 these 都是實際專案裡累積下來的小知識,從開機客製、系統屬性讀取、Git 操作到效能與記憶體優化,按主題分好類,需要時直接查。

一、開機 Logo 與開關機動畫

換開機 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");

三、常用 adb 與 Git 指令

# 查某個人的所有提交
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 測試與 CTS

# 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

八、Camera 客製

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,遇到對應場景時直接抄。

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