顯示具有 程式設計 標籤的文章。 顯示所有文章
顯示具有 程式設計 標籤的文章。 顯示所有文章

相信在開發 Android 裝置的工程師在做長時間測試的時候一定會遇到一個棘手的問題:
「該怎麼關掉 Screen Timeout?」否則裝置一下子就睡著了該怎麼測試?因為在網路上找不到相關的訊息,索性就自己寫一下。

基本上我有兩個辦法:

  1. 第一個辦法是給有能力可以編譯 Android 的開發人員,從 Android 的根目錄下尋找frameworks/base/packages/SettingsProvider/res/values/defaults.xml ,打開這個檔案,找關鍵字"def_screen_off_timeout",把這一行改成
    -1
    然後重新編譯與更新 Android Sytem。


  2. 第二個方法是給沒有辦法編譯 Android 或者像我這種懶得一直重新編譯的開發人員^^,進入 adb shell 裡面,cd 到 /data/data/com.android.providers.settings/databases/ ,輸入
    sqlite3 settings.db
    SQLite version 3.6.22
    Enter ".help" for instructions
    Enter SQL statements terminated with a ";"
    sqlite> update system SET value='-1' where name='screen_off_timeout';
    sqlite> select * from system where name='screen_off_timeout';
    51|screen_off_timeout|-1
    
    如果結果像最後一行這樣顯示 -1 表示成功了,接著輸入 .exit 離開,然後輸入
    reboot
    重新開機,好!開機完成後應該就可以"不眠不休"的測試了...^_^。

在介紹如何 debug 之前,首先必須知道的是,目前的系統到底有沒有記憶體洩漏?以下先介紹幾個常用的記憶體觀察法:

  • cat /proc/meminfo      // 粗略的觀察目前記憶體的種類以及各個種類的大小
  • ps                             // 觀察每個 process 目前記憶體使用的情況 
  • top                            // 看看前幾個記憶體使用最多的 process 是哪些
  • dumpsys meminfo      // Android 特有的指令,有更多的資訊







方法1 Memory Analyzer :

這個方法必須配合 Eclipse 使用,因為 Memory Analyzer (MAT) 是 Eclipse 的一個 Plugin。
  1. 第一個步驟當然是安裝 MAT,安裝得方法有許多種,你可以下載MemoryAnalyzer-1.0.1.201008091353.zip,解開到Plugins,或者在Eclipse上點選 Help --> Install New Software... --> Add,然後在 Name 輸入 Memory Analyzer ,在 Location 輸入 http://download.eclipse.org/mat/1.0/update-site/ ,如圖所示:
    按下 OK,之後要選擇安裝 Plugin 完成安裝程序。

  2. 一如往常的執行你想要 debug 的 Android 程式,然後透過進入 shell 裡面檢查 /data/misc/ 這個目錄是否有可讀寫的權限,因為我們等一下會 dump file 到這個目錄。另外,也可以簡單的把他的權限設成 777:
    adb shell
    chmod 777 /data/misc/
    

  3. 接下來執行程式到你認為會產生 leak 的地方,來回多執行幾次,然後利用 kill 這個指令送信號 SIGUSR1 (-10) 給你的 process (可以透過 ps 查看 Process ID),假設你要 debug "com.test.debug" 這個 process :
    ps
    ...
    PID UID       VSZ  Stat Command
    100 1000   255255    S  com.test.debug
    ...
    
    kill -10 100
    

  4. 你可以透過 logcat 來確認你的 process 有沒有收到 signal:
    logcat &
    

    如果看到類似如下的訊息表示有收到:
    I/dalvikvm(  236): threadid=3: reacting to signal 10
    I/dalvikvm(  236): SIGUSR1 forcing GC and HPROF dump
    I/dalvikvm(  236): hprof: dumping VM heap to "/data/misc/heap-dump-tm1291081439-pid100.hprof-hptemp".
    I/dalvikvm(  236): hprof: dumping heap strings to "/data/misc/heap-dump-tm1291081439-pid100.hprof".
    I/dalvikvm(  236): hprof: heap dump completed, temp file removed
    D/dalvikvm(  236): GC_HPROF_DUMP_HEAP freed 585 objects / 60000 bytes in 10595ms
    

    查看一下 /data/misc/ 目錄應該可以看到 heap-dump-tm1291081439-pid100.hprof:
    ls /data/misc/
    ...
    heap-dump-tm1291081439-pid100.hprof
    ...
    

  5. 離開 shell
    exit
    

    透過 adb pull 把這個檔案抓下來。
    adb pull /data/misc/heap-dump-tm1291081439-pid100.hprof
    

  6. 透過 hprof-conv 把剛剛抓下來的檔案轉換成 Memory Analyzer 認識的格式:
    hprof-conv heap-dump-tm1291081439-pid100.hprof debug.hprof
    

  7. 開啟 Eclipse,點選 Window --> Open Perspective --> Other... ,然後選擇 Memory Analyer。

  8. 點選 File --> Open Heap Dump... ,然後選擇剛剛轉換過的檔案 (此例為 debug.hprof)。接著會出現一個對話框,詢問你想產生什麼樣的報告,如下圖:
    此時我們的目的是偵測 memory leak,所以自然是選擇 Leak Suspects Report,按下 Finish 後,就會產生一個報告,告訴你可疑的地方。是不是很棒呢!


方法2 libc_debug.so : 

這個方法基本上是將 libc.so 換成 libc_debug.so 利用 libc_debug.so 提供多項偵錯的功能來查看記事體是否被不當的使用。

  1. 將 /system/lib/libc.so 替換成 /system/lib/libc_debug.so
  2. 重啟系統 adb shell reboot 
  3. adb shell setprop libc.debug.malloc 1" (or 5, or 10 for slightly different behaviors)
  4. 新增 "native=true" 到你的 ~/.android/ddms.cfg 檔案中
  5. 啟動 stand-alone 版的 DDMS. 接著你應該會看到有 "Native Heap" tab 出現,切到這個頁面後就可以 native memory 的使用情況。


方法3 c/c++ debugger : 

利用c/c++ debugger 來協助 debug c/c++ 層的 memory leak,接下的例子會使用 dmalloc 來 debug JNI native library.

  1. 先到 dmalloc 的官方網站 http://www.dmalloc.com 下載 source code。
  2. 交叉編譯 dmalloc,我個人是偏好用 Android NDK 來編譯,不過在這之前必須要先產生原本的 Makefile 然後照著 Makefile 來產生 Android.mk
    1. 執行 configure
      ./configure --prefix=/arm-linux/ --enable-cxx --enable-threads
      
      其中/arm-linux/是隨便指定的路徑,反正我們只是想要參考 Makefile。
    2. 參考 Makefile,轉換成 Android.mk
    3. 執行 ndk-build 來編譯 dmalloc
  3. 因為我們是要 debug JNI 的 native library 所以沒辦法透過一般的設定環境變倏地方法來指定 debug options:
    DMALLOC_OPTIONS=debug=0x4e48503,inter=100,log=/sdcard/dmalloc.%p
    export DMALLOC_OPTIONS
    

    必須自行在程式進入點指定 debug option,以 JNI 為例,可以利用 JNI_OnLoad() 當作是進入點,此外,離開的時候也必須關閉:
    #include "dmalloc.h"
    
    JNIEXPORT jint JNICALL JNI_OnLoad (
    ) {
        dmalloc_debug_setup ("debug=0x4e48503,inter=100,log=/sdcard/dmalloc.%p");
    }
    
    JNIEXPORT void JNICALL JNI_OnUnLoad (
    ) {
        dmalloc_shutdown ();
    }
    

    然後利用 dmalloc_mark() 與 dmalloc_log_changed() 來標記要偵錯的區段,下面我們以一個 JNI function 為例,故意造成 memory leak:
    unsigned long mark;
    
    JNIEXPORT void JNICALL JNI_com_example_debug_Test (
        JNIEnv* env,
        jobject thisArg
    ) {
        // Mark the start of debug
        mark = dmalloc_mark();
    
        // Leak memory 1000 bytes.
        char* leak = (char*) malloc (1000);
    
        // log unfreed pointers that have been added to
        // the heap since mark
        dmalloc_log_changed (
            mark,
            1,    // log unfreed pointers
            0,    // do not log freed pointers
            1     // log each pnt otherwise summary
        );
    }
    

    一旦這個 function 被呼叫,就會在 /sdcard/ 目錄下產生類似 dmalloc.1000 (副檔名是這個process 的 PID),然後裡面就會告訴你那一行發生 memory leak了。
    948436802: 1: Dmalloc version '5.5.2' from 'http://dmalloc.com/'
    948436802: 1: flags = 0x4e48503, logfile 'logfile'
    948436802: 1: interval = 100, addr = 0, seen # = 0, limit = 0
    948436802: 1: starting time = 948436802
    948436802: 1: process pid = 1000
    ...
    

Ubuntu 9.04 之前的 gcc 和 g++ 的版本都是 4.3 的,但是 Ubuntu 9.10 以後卻換成了 4.4 的。 而 4.4 除了檢查更加嚴格外也改了某些函數的回傳型別,把 char* 改成了更嚴謹的 const char* 其用意是讓這些函數更安全。

由於修改 android source code 可是一大工程,而且 source code 隨著 google 的修改版本一直在 update ,除非決定自己 maintain 否則修改可不是一個合理的行為。所以把 gcc 和 g++ 還原成 4.3 版是一個比較可行的辦法。

首先安裝 4.3 版的 gcc 和 g++ :


sudo apt-get install gcc-4.3 g++-4.3 g++-4.3-multilib


接著刪掉原本的 link :


sudo rm /usr/bin/gcc
sudo rm /usr/bin/g++


產生指到成舊版的 link :


sudo ln -s /usr/bin/gcc-4.3 /usr/bin/gcc
sudo ln -s /usr/bin/g++-4.3 /usr/bin/g++


補充:在 Ubuntu 10.10 之後有一種稱為 fastjar 的工具, 是以 c 語言寫成的工具,比原本 java 版本的快了 100 倍. 但是目前有一些穩定性的疑慮,所以如果在 Ubuntu 10.10 發現類似 "unable to access file: corrupted zip file" 這樣的錯誤,可以試著執行:

sudo update-alternatives --config jar


然後會出現:
There are 2 choices for the alternative jar (providing /usr/bin/jar).

Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/fastjar 100 auto mode
1 /usr/bin/fastjar 100 manual mode
2 /usr/lib/jvm/java-6-sun/bin/jar 63 manual mode

Press enter to keep the current choice[*], or type selection number:


輸入 2, 選擇 java 版的就可以了。

基本上 Emulator /system 目錄是唯讀的,要解除其唯讀屬性可以透過下列方法:

adb remount
adb push libmy.so /system/lib

但是,在 Android 2.0 (Eclair) 以後,上面的作法會出現這樣的錯誤:
failed to copy 'hosts' to '/system/etc/hosts': No space left on device
或
failed to copy 'hosts' to '/system/etc/hosts': Out of memory

解決方法是,開啟模擬器時不要直接從 AVD Manager介面開,請下指令:
emulator -avd youravdname -partition-size 128
接著再對這個模擬器使用上面的方法就不會出現錯誤了。

深究其原因是 partition size 預設是 64MB。從 adb shell 用 df 指令觀察的結果,/system 在2.x 的 image mount 之後剩下空間是 0K。因此即使 remount 之後也無法寫入。

Filesystem           1k-blocks      Used Available Use% Mounted on
tmpfs                   128276         0    128276   0% /dev
tmpfs                   128276         0    128276   0% /mnt/asec
/dev/block/mtdblock0     77568     77568         0 100% /system
/dev/block/mtdblock1    129152     54988     74164  43% /data
/dev/block/mtdblock2     65536      1156     64380   2% /cache
/dev/block/vold/179:0
                       1044472     65608    978864   6% /mnt/sdcard
/dev/block/vold/179:0
                       1044472     65608    978864   6% /mnt/secure/asec

可惜AVD Manager 沒地方可以設定 partition size。所以目前只能在 console 以手動下指定開emulator囉。

有用過 Android adb shell 的人應該都知道這個 shell 的功能實在是食之無味棄之可惜的雞肋,一些常用的 linux command 幾乎都不支援,所以今天要介紹 busybox 這個工具,它的支援相當豐富,以下是執行的畫面:

$ busybox
BusyBox v1.16.0 (2010-01-27 20:00:00 CET) multi-call binary.
Copyright (C) 1998-2009 Erik Andersen, Rob Landley, Denys Vlasenko
and others. Licensed under GPLv2.
See source distribution for full notice.

Usage: busybox [function] [arguments]...
   or: function [arguments]...

 BusyBox is a multi-call binary that combines many common Unix
 utilities into a single executable.  Most people will create a
 link to busybox for each function they wish to use and BusyBox
 will act like whatever it was invoked as.

Currently defined functions:
 [, [[, acpid, addgroup, adduser, adjtimex, ar, arp, arping, ash, awk,
 basename, beep, blkid, brctl, bunzip2, bzcat, bzip2, cal, cat, catv,
 chat, chattr, chgrp, chmod, chown, chpasswd, chpst, chroot, chrt, chvt,
 cksum, clear, cmp, comm, cp, cpio, crond, crontab, cryptpw, cttyhack,
 cut, date, dc, dd, deallocvt, delgroup, deluser, depmod, devmem, df,
 dhcprelay, diff, dirname, dmesg, dnsd, dnsdomainname, dos2unix, du,
 dumpkmap, dumpleases, echo, ed, egrep, eject, env, envdir, envuidgid,
 ether-wake, expand, expr, fakeidentd, false, fbset, fbsplash, fdflush,
 fdformat, fdisk, fgrep, find, findfs, flash_eraseall, flash_lock,
 flash_unlock, flashcp, fold, free, freeramdisk, fsck, fsck.minix,
 fsync, ftpd, ftpget, ftpput, fuser, getopt, getty, grep, gunzip, gzip,
 halt, hd, hdparm, head, hexdump, hostid, hostname, httpd, hush,
 hwclock, id, ifconfig, ifdown, ifenslave, ifplugd, ifup, inetd, init,
 inotifyd, insmod, install, ionice, ip, ipaddr, ipcalc, ipcrm, ipcs,
 iplink, iproute, iprule, iptunnel, kbd_mode, kill, killall, killall5,
 klogd, last, length, less, linux32, linux64, linuxrc, ln, loadfont,
 loadkmap, logger, login, logname, logread, losetup, lpd, lpq, lpr, ls,
 lsattr, lsmod, lspci, lsusb, lzmacat, lzop, lzopcat, makedevs,
 makemime, man, md5sum, mdev, mesg, microcom, mkdir, mkdosfs, mke2fs,
 mkfifo, mkfs.ext2, mkfs.minix, mkfs.vfat, mknod, mkpasswd, mkswap,
 mktemp, modprobe, more, mount, mountpoint, msh, mt, mv, nameif, nc,
 netstat, nice, nmeter, nohup, nslookup, ntpd, od, openvt, passwd,
 patch, pgrep, pidof, ping, ping6, pipe_progress, pivot_root, pkill,
 popmaildir, poweroff, printenv, printf, ps, pscan, pwd, raidautorun,
 rdate, rdev, readahead, readlink, readprofile, realpath, reboot,
 reformime, renice, reset, resize, rm, rmdir, rmmod, route, rpm,
 rpm2cpio, rtcwake, run-parts, runlevel, runsv, runsvdir, rx, script,
 scriptreplay, sed, sendmail, seq, setarch, setconsole, setfont,
 setkeycodes, setlogcons, setsid, setuidgid, sh, sha1sum, sha256sum,
 sha512sum, showkey, slattach, sleep, softlimit, sort, split,
 start-stop-daemon, stat, strings, stty, su, sulogin, sum, sv, svlogd,
 swapoff, swapon, switch_root, sync, sysctl, syslogd, tac, tail, tar,
 taskset, tcpsvd, tee, telnet, telnetd, test, tftp, tftpd, time,
 timeout, top, touch, tr, traceroute, traceroute6, true, tty, ttysize,
 tunctl, tune2fs, udhcpc, udhcpd, udpsvd, umount, uname, uncompress,
 unexpand, uniq, unix2dos, unlzma, unlzop, unzip, uptime, usleep,
 uudecode, uuencode, vconfig, vi, vlock, volname, wall, watch, watchdog,
 wc, wget, which, who, whoami, xargs, yes, zcat, zcip

網路上已經有人幫忙把 busybox comile 成 android 可以用的 binary 檔了,有需要的人可以到這裡下載。

安裝 busybox 的步驟如下:

1. 建立安裝的目錄
adb shell mkdir /data/busybox

2. 複製 busybox 的 binary 檔到前一個步驟所建立的目錄:
adb push busybox /data/busybox/busybox

3. 開始安裝 busybox
adb shell
cd /data/busybox
./busybox --install. 
然後你可以檢查 /data/busybox 目錄,裡面應該有許多links.
但是預設的路徑並沒有被指定到 /data/busybox 為了讓用起來方便一點,可以修改 init.rc 多加進去 busybox 的安裝路徑,但如果是在 emulator 上 run 那就要去修改 ramdisk.img 才能達到一勞永逸的效果,否則每次開啟 emulator 後 init.rc 會被覆蓋掉。

修改 ramdisk.img 的步驟:

2.6內核開始,initrd.img採用cpio壓縮,ramdisk.img也一樣,使用gunzip解壓縮,然後再使用 cpio解包。

1. 將 ramdisk.img 從 android sdk 的 platroms\android-xx 目錄下複製到 linux 的作業環境其他目錄(如果已經在 linux 下則此一步驟省略)

2. 名稱改為 ramdisk.img.gz 並用 gunzip 解壓
mv ramdisk.img ramdisk.img.gz
gunzip ramdisk.img.gz

3. 新建一個文件夾 ramdisk 並進入此目錄後用 cpio 解開
mkdir ramdisk
cd ramdisk
cpio -i -F ../ramdisk.img
此時現在目錄已經是解開後的 ramdisk 檔案目錄了

4. 修改 init.rc 在 PATH 中加上 /data/busybox 路徑
## Global environment setup
##
env {
#其中, /data/busybox 為busybox安裝路徑,bash也是放在其中
PATH /data/busybox:/sbin:/system/sbin:/system/bin
...
}

5. 重新打包 ramdisk
find . | cpio -o -H newc -O ../new_ramdisk.img
gzip ../new_ramdisk.img

6. 把 new_ramdisk.img.gz 改成 ramdisk.img 並複製到 emulator 原來放置 ramdisk.img 的目錄覆蓋掉。大功告成...^^

應該很多人都知道 Android Dalvik 的 Maximum Heap Size 一般都是 16M,如果你的程式非常龐大可能這 16M 連跑都跑不起來,這時就要把 Heap Size 放寬才行,那麼該如何放寬限制呢?以下提供幾種方法把 heap size 從 16M 改成 64M:

1. 第一種方法是提供給想在實機上執行程式並且有能力修改 android framework 的朋友,直接到 android source code 目錄,打開 frameworks\base\core\jni\AndroidRuntime.cpp 找到有關建字"16m"這一行,改成"64m":

property_get("dalvik.vm.heapsize", heapsizeOptsBuf+4, "64m");
重新產生 android image 就大功告成了。

2. 第二種方法是提供給想在 Emulator 上執行程式的朋友,請修改 config.ini 並加入這一行(註1):
vm.heapSize=64

3. 如果上述兩種辦法都不可行,試試看第三種方法,在 /data 目錄下產生 local.prop 並修改檔案內容,加入 dalvik.vm.heapsize=64m ,例如在 shell 模式下輸入:
cd /data
echo dalvik.vm.heapsize=64m > local.prop


註1:
如果在你是 Windows 底下開發的話,這個檔案一般會放在 "C:\Documents and Settings\YourAccount\.android\avd\YourAVD\"

其實 Android 製作 .apk 的 Private Key 是放在 \build\target\product\security 這個目錄下,這裡有好幾組 Key 而其主要的差異如下:

testkey -- a generic key for packages that do not otherwise specify a key.
platform -- a test key for packages that are part of the core platform.
shared -- a test key for things that are shared in the home/contacts process.
media -- a test key for packages that are part of the media/download system.

因此,如果你希望在 Android 建制 Framework 的過程中把你寫的 Application 改成你所指定的 Private Key ,基本上你需要改動的就是 testkey ,這個目錄下還有個 mkkey.sh 來協助你作這樣的工作, mkkey.sh 的內容如下:

if ["$1" == ""]; then
 echo "Create a test certificate key."
 echo "Usage: $0 NAME"
 echo "Will generate NAME.pk8 and NAME.x509.pem"
 echo "  /C=US/ST=California/L=Mountain View/O=Android/OU=Android/CN=Android/emailAddress=android@android.com"
 return
fi

openssl genrsa -3 -out $1.pem 2048

openssl req -new -x509 -key $1.pem -out $1.x509.pem -days 10000 \
    -subj '/C=US/ST=California/L=Mountain View/O=Android/OU=Android/CN=Android/emailAddress=android@android.com'

openssl pkcs8 -in $1.pem -topk8 -outform DER -out $1.pk8 -nocrypt

說穿了,就是利用 openssl 來產生新的 Private Key,所以更改的方法很簡單,你可以把 openssl req -new ... 這一行改成你所需要的格式, 接著你只要執行 mkkey.sh 就可以產生新的 Private Key 了! 讚吧!

上一個方法是把 Private Key 跟 Certificate 直接換掉,如果你已經有現成的 Certificate 可以使用,令一個比較簡單的方法是更改 Android.mk 的設定,加一行:


LOCAL_CERTIFICATE := vendor/example/certs/app

如此,在 build system 的時候就可以使用指定的 Certificate 了。

可是這樣還離完美差一點點,你也許想把這個 Private Key 放到 Java 的 .keystore 檔案去,關於這個問題可以參考這篇文章http://www.agentbob.info/agentbob/79-AB.html,裡面有很詳細的說明。

OK, 到這裡為止一切就算是大功告成囉!


Java for-each Loop


簡介

很多程式語言都有支援for-each這類的語法,簡單的說for-each語法就是當我們想要存取一個 Array 或 Collection 裡面所有的元時可以更方便、更有效率的語法。for-each 也有人稱為 enhanced for 或 for-in。
使用上要注意的事項有:
  • 只適用於 Java 5.0 以後的版本
  • 只適用於有 implement Iterable  的類別基本上 Array 與 Collection 類別都沒問題。
  • 只能存取裡面元素而不能置換掉它,記住,for-each 裡面的變數是 local 變數離開 for-each 之後就會消失。
  • 只能同時針對一個 Array 或 Collection 進行操作。
  • 只能同時針對一個元素操作。
  • 只能從頭開始訪問每個元素。


語法


底下針對 Array 與 Collection 分別說明:
for-each 迴圈for 迴圈
for (type var : arr) {
    body-of-loop
}
for (int i = 0; i < arr.length; i++) { 
    type var = arr[i];
    body-of-loop
}
for (type var : coll) {
    body-of-loop
}
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
    type var = iter.next();
    body-of-loop
}

範例


這是一個使用 for-each 迴圈的程式碼:
double[] ar = {1.2, 3.0, 0.8};
int sum = 0;
for (double d : ar) {  // d gets successively each value in ar.
    sum += d;
}
這是一個使用一般 for 迴圈的程式碼:
double[] ar = {1.2, 3.0, 0.8};
int sum = 0;
for (int i = 0; i < ar.length; i++) {  // i indexes each element successively.
    sum += ar[i];
}

Resource Type Location Description XML Java
Id /res/values/any-file  
<resources>
<item type="id" name="text"/>
</resources>

 
Color /res/values/any-file Represents color identifiers pointing to color codes. These
resource IDs are exposed in R.java as R.color.*.
<resources>
    <color name="red">#f00</color>
    <color name="blue">#0000ff</color>
    <color name="green">#f0f0</color>
    <color name="main_back_ground_color">#ffffff00</color>
</resources>
<TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:textColor="@color/ red"
          android:text="Sample Text to Show Red Color"/>
int mainBackGroundColor
= activity.getResources.getColor(R.color.main_back_ground_color);
String /res/values/any-file Represents string resources. String resources
allow
Java-formatted strings and raw HTML in addition
to simple
strings. These resource IDs are exposed in
R.java as R.string.*.
<resources>
    <string name="simple_string">simple string</string>
    <string name="quoted_string">"quoted'string"</string>
    <string name="double_quoted_string">\"double quotes\"</string>
    <string name="java_format_string">
           hello %2$s java format string. %1$s again
     </string>
     <string name="tagged_string">
         Hello <b><i>Slanted Android</i></b>, You are bold.
     </string>
</resources>
 
 
<TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:textAlign="center"
          android:text="@string/tagged_string"/>
//Read a simple string and set it in a text view
String 
      simpleString = 
      activity.getString(R.string.simple_string);
textView.setText(simpleString);
//Read 
      a quoted string and set it in a text view
String quotedString = 
      activity.getString(R.string.quoted_string);
textView.setText(quotedString);
//Read 
      a double quoted string and set it in a text view
String 
      doubleQuotedString = 
      activity.getString(R.string.double_quoted_string);
textView.setText(doubleQuotedString);
//Read 
      a Java format string
String javaFormatString = 
      activity.getString(R.string.java_format_string);
//Convert the 
      formatted string by passing in arguments
String substitutedString = 
      String.format(javaFormatString, "Hello" , "Android");
//set the output 
      in a text view
textView.setText(substitutedString);
//Read an html 
      string from the resource and set it in a text view
String 
      htmlTaggedString = 
      activity.getString(R.string.tagged_string);
//Convert it to a text span 
      so that it can be set in a text view
//android.text.Html class allows 
      painting of "html" strings
//This is strictly an Android class and does 
      not support all html tags
Spanned textSpan = 
      android.text.Html.fromHtml(htmlTaggedString);
//Set it in a text 
      view
textView.setText(textSpan);
Dimension /res/values/any-file

Represents dimensions or sizes of various elements
or views in
Android. Supports pixels, inches, mil-
limeters, density-independent
pixels, and scale-
independent pixels. These resource IDs are
exposed
in R.java as R.dimen.*.

  • px: Pixels
  • in: Inches
  • mm: Millimeters
  • pt: Points
  • dp: Density-independent pixels based on a 160-dpi (pixel density per
    inch) screen
    (dimensions adjust to screen density)
  • sp: Scale-independent pixels (dimensions that allow for user sizing;
    helpful for use in
    fonts)


<resources>
    <dimen name="mysize_in_pixels">1px</dimen>
    <dimen name="mysize_in_dp">5dp</dimen>
    <dimen name="medium_size">100sp</dimen>
</resources>
 
 
<TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:textSize="@dimen/medium_size"/>
float dimen = 
      activity.getResources().getDimension(R.dimen.mysize_in_pixels);
Image /res/drawable/multiple-
files
Represents image resources. Supported images
include
.jpg, .gif, and .png. Each image is in a
separate file and gets its own
ID based on the file
name. These resource IDs are exposed in R.java
as
R.drawable.*. The image support also includes an
image type
called a stretchable image that allows
portions of an image to stretch
while other portions
of that image stay static.
<Button
      android:id="@+id/button1"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Dial"
      android:background="@drawable/sample_image"
/>
//Call getDrawable to get the image
BitmapDrawable d = 
      activity.getResources().getDrawable(R.drawable.sample_image);
//You can 
      use the drawable then to set the 
      background
button.setBackgroundDrawable(d);
//or you can set the 
      background directly from the Resource 
      Id
button.setBackgroundResource(R.drawable.icon);
Color
Drawable
/res/values/any-file Represents rectangle of colors to be used as
view
backgrounds or general drawables like bitmaps.
You can use this
instead of specifying a single
colored bitmap as a background. In Java,
this is
equivalent to creating a colored rectangle and set-
ting it
as a background for a view.
The <drawable> value tag in the
values subdirec-
tory supports this. These resource IDs are
exposed
in R.java as R.drawable.*.
Android also supports rounded
rectangles and
gradient rectangles through XML files placed
in
/res/drawable with the root XML tag <shape>.
These resource
IDs are also exposed in R.java as
R.drawable.*. Each file name in this
case translates
to a unique drawable ID.
<resources>
    <drawable name="red_rectangle">#f00</drawable>
    <drawable name="blue_rectangle">#0000ff</drawable>
    <drawable name="green_rectangle">#f0f0</drawable>
</resources>

<TextView android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:textAlign="center"
          android:background="@drawable/red_rectangle"/>
// Get a drawable
ColorDrawble redDrawable 
      =
(ColorDrawable)
activity.getResources().getDrawable(R.drawable.red_rectnagle);
//Set 
      it as a background to a text 
    view
textView.setBackground(redDrawable);
Shape /res/drawable/multiple-
files
 
<shape>
    <solid android:color="#f0600000"/>
    <stroke android:width="3dp" color="#ffff8080"/>
    <corners android:radius="13dp" />
    <padding android:left="10dp" android:top="10dp"
        android:right="10dp" android:bottom="10dp" />
</shape>
// Get a drawable
GradientDrawable roundedRectangle 
      =
(GradientDrawable)
activity.getResources().getDrawable(R.drawable.red_rectnagle);
//Set 
      it as a background to a text 
      view
textView.setBackground(roundedRectangle);
Layout /res/layout/any-file  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView    android:id="@+id/text1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
 <Button    android:id="@+id/b1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@+string/hello"
   />  
</LinearLayout>
public void onCreate(Bundle 
      savedInstanceState)
    
      {
        
      super.onCreate(savedInstanceState);
        
      setContentView(R.layout.main);
        
      TextView tv = 
      (TextView)this.findViewById(R.id.text1);
        
      tv.setText("Try this text instead");
    }
Arbitrary
XML Files
/res/xml/*.xml Android allows arbitrary XML files as resources.
These
files will be compiled by the AAPT com-
piler. These resource IDs are
exposed in R.java as
R.xml.*.
<rootelem1>
   <subelem1>
      Hello World from an xml sub element
   </subelem1>
</rootelem1>
Resources res = 
      activity.getResources();
XmlResourceParser xpp = 
      res.getXml(R.xml.test);
 
private String 
      getEventsFromAnXMLFile(Activity activity)
throws 
      XmlPullParserException, IOException
{
   StringBuffer sb = 
      new StringBuffer();
   Resources res = 
      activity.getResources();
   XmlResourceParser xpp = 
      res.getXml(R.xml.test);
  
   
      xpp.next();
   int eventType = 
      xpp.getEventType();
    while (eventType != 
      XmlPullParser.END_DOCUMENT)
    
      {
        if(eventType == 
      XmlPullParser.START_DOCUMENT)
        
      {
           
      sb.append("******Start 
      document");
        
      }
        else if(eventType == 
      XmlPullParser.START_TAG)
        
      {
           
      sb.append("\nStart tag 
      "+xpp.getName());
        
      }
        else if(eventType == 
      XmlPullParser.END_TAG)
        
      {
           
      sb.append("\nEnd tag 
      "+xpp.getName());
        
      }
        else if(eventType == 
      XmlPullParser.TEXT)
        
      {
           
      sb.append("\nText 
      "+xpp.getText());
        
      }
        eventType = 
      xpp.next();
    }//eof-while
    
      sb.append("\n******End document");
    return 
      sb.toString();
}//eof-function
Arbitrary Raw
Resources
/res/raw/*.* Android allows arbitrary noncompiled binary or
text
files under this directory. Each file gets a unique
resource
ID. These resource IDs are exposed in
R.java as R.raw.*.
String getStringFromRawFile(Activity 
      activity)
{
    Resources r = 
      activity.getResources();
    InputStream is = 
      r.openRawResource(R.raw.test);
    String myText = 
      convertStreamToString(is);
    
      is.close();
    return myText;
}
String 
      convertStreamToString(InputStream is)
{  
    
      ByteArrayOutputStream baos = new 
      ByteArrayOutputStream();
    int i = 
      is.read();
    while (i != -1)
    
      {
        
      baos.write(i);
        i = 
      baos.read();
    }
    return 
      baos.toString();
}
Arbitrary Raw
Assets
/assets/*.*/*.* Android allows arbitrary files in arbitrary
subdirec-
tories, starting at the /assets subdirectory. These
are
not really resources, but raw files. This directo-
ry, unlike the /res
subdirectory, allows an arbitrary
depth of subdirectories. These files
do not generate
any resource IDs. You have to use a relative
path
name starting at and excluding /assets.

 
//Note: Exceptions are not shown in the code
String 
      getStringFromAssetFile(Activity activity)
{
    
      AssetManager am = activity.getAssets();
    InputStream 
      is = am.open("test.txt");
    String s = 
      convertStreamToString(is);
    
      is.close();
    return s;
}

或許大部分有寫過Java程式的人都知道java.lang.Runtime這個class有一個method叫做exec(),可以被用來呼叫(調用)外部的程式。然而大部分的人都不知道這個method存在著幾個機車的小陷阱,一個不小心就會發生災難了,待我娓娓道來...

這個method有幾個overloaded的版本如下:


Process
exec(String[] progArray, String[] envp, File directory)
Executes the specified command and its arguments in a separate native process.
Process
exec(String prog, String[] envp)
Executes the specified program in a separate native process.
Process
exec(String prog)
Executes the specified program in a separate native process.
Process
exec(String prog, String[] envp, File directory)
Executes the specified program in a separate native process.
Process
exec(String[] progArray)
Executes the specified command and its arguments in a separate native process.
Process
exec(String[] progArray, String[] envp)
Executes the specified command and its arguments in a separate native process.

其中prog這個參數是要執行的外部可執行檔名稱,progArray則是可執行檔名稱和一些參數,當然你也可以把progArray合成一個prog參數(中間必須用空白格開),不過,問題多多。envp表示環境變數,directory表示可執行檔的目錄,更詳細的參數說明請參考Java文件。


請看以下的程式碼隱藏著什麼樣的危機?

import java.util.*;
import java.io.*;

public class BadExample1 {
    public static void main (String args[]) {
        try {            
            Runtime rt = Runtime.getRuntime ();
            Process proc = rt.exec ("javac");
            int exitVal = proc.exitValue ();
            System.out.println ("Process exitValue: " + exitVal);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
}

結果是:

java BadExample1
java.lang.IllegalThreadStateException: process has not exited
        at java.lang.Win32Process.exitValue(Native Method)
        at BadExample1.main(BadExample1.java:13)

奇怪,這麼簡單的程式碼,不過就是請exec執行一行javac,怎麼就跳出Exception了呢?讓我們來分析一下,首先這段程式用getRuntime()這個static method取得Runtime物件,然後呼叫exec去執行"javac"外部可執行檔,最後取得回傳值並把它輸出在標準輸出。問題來了,exec會create一個新的process來執行外部可執行檔,如果呼叫proc.exitValue()的時候javac還沒執行完畢,JVM就會丟出IllegalThreadStateException (記得嗎?在多工的作業系統裡,每個process幾乎可以被看成是同時運行的,既然如此沒有人可以保證process執行完成的先後順序。) ,有方法可以等外部process執行完畢嗎?YES,Process這個class提供了一個waitFor() method正好可以用來解決這個問題,而且waitFor()還會回傳等同於
exitValue()回傳值,所以程式再度改寫如下:

import java.util.*;
import java.io.*;

public class BadExample2 {
    public static void main (String) {
        try {            
            Runtime rt = Runtime.getRuntime ();
            Process proc = rt.exec ("javac");
            int exitVal = proc.waitFor ();
            System.out.println ("Process exitValue: " + exitVal);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Sorry, Sorry, Sorry...讓我想起當紅的SorrySorry舞,很抱歉,這次程式直接當在那裡給你看,奇怪?為什麼會當,原來JDK裡面有一段話是這麼說的:

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

好吧,所以以這個例子而言,應該要把stderr跟stdout裡面的buffer趕快讀走,再度改寫程式如下:

import java.util.*;
import java.io.*;

public class OkExample1 {
    public static void main (String args[]) {
        try {            
            Runtime rt = Runtime.getRuntime ();
            Process proc = rt.exec ("javac");
            String line = null;

            InputStream stderr = proc.getErrorStream ();
            InputStreamReader esr = new InputStreamReader (stderr);
            BufferedReader ebr = new BufferedReader (esr);
            System.out.println ("<error>");
            while ( (line = ebr.readLine ()) != null)
                System.out.println(line);
            System.out.println ("</error>");
            
            InputStream stdout = proc.getInputStream ();
            InputStreamReader osr = new InputStreamReader (stdout);
            BufferedReader obr = new BufferedReader (osr);
            System.out.println ("<output>");
            while ( (line = obr.readLine ()) != null)
                System.out.println(line);
            System.out.println ("</output>");

            int exitVal = proc.waitFor ();
            System.out.println ("Process exitValue: " + exitVal);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

輸出結果:

java OkExample1
<error>
Usage: javac <options> <source files>
where <options> includes:
  -g                     Generate all debugging info
  -g:none                Generate no debugging info
  -g:{lines,vars,source} Generate only some debugging info
  -O                     Optimize; may hinder debugging or enlarge class files
  -nowarn                Generate no warnings
  -verbose               Output messages about what the compiler is doing
  -deprecation           Output source locations where deprecated APIs are used
  -classpath <path>      Specify where to find user class files
  -sourcepath <path>     Specify where to find input source files
  -bootclasspath <path>  Override location of bootstrap class files
  -extdirs <dirs>        Override location of installed extensions
  -d <directory>         Specify where to place generated class files
  -encoding <encoding>   Specify character encoding used by source files
  -target <release>      Generate class files for specific VM version
</error>
Process exitValue: 2

雖然程式醜了點,但至少結果是還OK的,更好的作法是create兩個thread分別把stdout與stderr的資料讀出來。不過這裡有一點需要注意,得到stdout的方法是呼叫getInputStream()名稱上比較容易搞混。

另一個常犯的錯誤是把console指令或shell指令當作是可執行檔,例如win32上的dir和copy:

import java.util.*;
import java.io.*;

public class BadExample3 {
    public static void main (String args[]) {
        try {            
            Runtime rt = Runtime.getRuntime ();
            Process proc = rt.exec ("dir");

            InputStream stderr = proc.getErrorStream ();
            InputStreamReader esr = new InputStreamReader (stderr);
            BufferedReader ebr = new BufferedReader (esr);
            System.out.println ("<error>");
            while ( (line = ebr.readLine ()) != null)
                System.out.println(line);
            System.out.println ("</error>");
            
            InputStream stdout = proc.getInputStream ();
            InputStreamReader osr = new InputStreamReader (stdout);
            BufferedReader obr = new BufferedReader (osr);
            System.out.println ("<output>");
            while ( (line = obr.readLine ()) != null)
                System.out.println(line);
            System.out.println ("</output>");

            int exitVal = proc.waitFor ();            
            System.out.println ("Process exitValue: " + exitVal);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

輸出結果:

java BadExample3
java.io.IOException: CreateProcess: dir error=2
        at java.lang.Win32Process.create(Native Method)
        at java.lang.Win32Process.<init>(Unknown Source)
        at java.lang.Runtime.execInternal(Native Method)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at java.lang.Runtime.exec(Unknown Source)
        at BadExecWinDir.main(BadExecWinDir.java:12)

error=2表示找不到這個檔案,也就是系統並不存在dir.exe,哪是因為dir只是window command interpreter(command.com或cmd.exe)的其中一個指令。所以我們把上面的例子再改寫:

import java.util.*;
import java.io.*;

class StreamConsumer extends Thread {
    InputStream is;
    String type;
    
    StreamConsumer (InputStream is, String type) {
        this.is = is;
        this.type = type;
    }
    
    public void run () {
        try {
            InputStreamReader isr = new InputStreamReader (is);
            BufferedReader br = new BufferedReader (isr);
            String line = null;
            while ((line = br.readLine()) != null)
                System.out.println (type + ">" + line);    
        } catch (IOException ioe) {
            ioe.printStackTrace();  
        }
    }
}

public class GoodExample1 {
    public static void main (String args[]) {
        if (args.length < 1) {
            System.out.println ("USAGE: java GoodWindowsExec <cmd>");
            System.exit (1);
        }
        
        try {            
            String osName = System.getProperty ("os.name");
            String[] cmd = new String[3];
            if (osName.equals ("Windows NT")) {
                cmd[0] = "cmd.exe";
                cmd[1] = "/C";
                cmd[2] = args[0];
            } else if( osName.equals ("Windows 95")) {
                cmd[0] = "command.com";
                cmd[1] = "/C";
                cmd[2] = args[0];
            }
            
            Runtime rt = Runtime.getRuntime ();
            System.out.println ("Execing " + cmd[0] + " " + cmd[1] 
                               + " " + cmd[2]);
            Process proc = rt.exec (cmd);
            // any error message?
            StreamConsumer errorConsumer = new 
                StreamConsumer (proc.getErrorStream(), "error");            
            
            // any output?
            StreamConsumer outputConsumer = new 
                StreamConsumer (proc.getInputStream(), "output");
                
            // kick them off
            errorConsumer.start ();
            outputCosumer.start ();
                                    
            // any error???
            int exitVal = proc.waitFor ();
            System.out.println ("ExitValue: " + exitVal);        
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
}

輸出結果:

java GoodExample1 "dir *.java"
Execing cmd.exe /C dir *.java
output> Volume in drive E has no label.
output> Volume Serial Number is 5C5F-0CC9
output>
output> Directory of E:\classes\com\javaworld\jpitfalls\article2
output>
output>10/23/00  09:01p                   805 BadExecBrowser.java
output>10/22/00  09:35a                   770 BadExecBrowser1.java
output>10/24/00  08:45p                   488 BadExecJavac.java
output>10/24/00  08:46p                   519 BadExecJavac2.java
output>10/24/00  09:13p                   930 BadExecWinDir.java
output>10/22/00  09:21a                 2,282 BadURLPost.java
output>10/22/00  09:20a                 2,273 BadURLPost1.java
... (省略)
output>10/12/00  09:29p                   151 SuperFrame.java
output>10/24/00  09:23p                 1,814 TestExec.java
output>10/09/00  05:47p                23,543 TestStringReplace.java
output>10/12/00  08:55p                   228 TopLevel.java
output>              22 File(s)         46,661 bytes
output>                         19,678,420,992 bytes free
ExitValue: 0

還有一個常犯的錯誤是認為所有console或shell上可以執行的指令以為都可以透過exec()來達成,例如redirect >,請看:

import java.util.*;
import java.io.*;

public class BadExample4 {
    public static void main (String args[]) {
        try {            
            Runtime rt = Runtime.getRuntime ();
            Process proc = rt.exec ("echo 'Hello World' > test.txt");
            // any error message?
            StreamGobbler errorConsumer = new 
                StreamConsumer (proc.getErrorStream (), "error");            
            
            // any output?
            StreamGobbler outputConsumer = new 
                StreamConsumer (proc.getInputStream (), "output");
                
            // kick them off
            errorConsumer.start();
            outputConsumer.start();
                                    
            // any error???
            int exitVal = proc.waitFor ();
            System.out.println ("ExitValue: " + exitVal);        
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
}

輸出結果:

java BadExample4
OUTPUT>'Hello World' > test.txt
ExitValue: 0

如果這段command可以成功執行,那麼理論上test.txt應該會有一行'Hello World',但是事實上test.txt並不存在,也就是說redirect無法正確的被執行。

解決的辦法是:

  1. 自己開檔案把字串寫到test.txt裡面去。
  2. 建立一個.bat(win32)或.sh(linux)然後去執行。

參考資料: