編輯:進階開發
Android 是 Linux 作業系統的一個特殊發行版,旨在管理最智慧手機所提供的功能。對程式設計師來說,Linux 裡的一切——裝置、試算表,或最喜歡的一首曲子——都以檔案的形式呈現。也就是說,可以用一組通用方法來開啟、提取、操作或保存這些抽象實體的資訊內容。這種通用性正是 UNIX 的核心理念:一切皆檔案。
檔案被組織成一個稱為「檔案系統」的層次結構。一支 Android 手機通常使用兩種檔案系統:非揮發(non-volatile)記憶體,或插入式 SD 卡。兩者都表現為根目錄下的子目錄(/)。因此,一個能讓你在瀏覽器中方便瀏覽這些檔案系統的工具就很有用。本專案定義了一個以 C 語言編寫的小程式,讓你能從工作站或直接從手機內建瀏覽器瀏覽 Android 的檔案系統。它提供帶有超連結的頁面,讓你在層次樹中上下移動,並透過點擊各類檔案來查看每一項內容。
設置開發環境
首先,確保你擁有一支「已取得 root 授權」的 Android 手機,以便執行類似啟動 Terminal 並運行 su 命令取得 root 權限的操作。若不知道如何對手機執行 root 操作,快速搜尋一下網路應能找到答案(這一過程有時也稱為「破解」,jail-breaking)。
Android 社群主要使用兩種 SDK:最常見的是高階 Android SDK,讓你用 Java 撰寫程式碼,並常用 Eclipse 編寫、測試與除錯;另一種較少見,即 Android 內核源碼,保存在名為 git 的儲存庫中。
由於本文聚焦於建立通常位於手機 system/bin 目錄中的低階 Web 伺服器,因此必須下載並安裝完整的 Android 內核源碼與用於構建它的 GNU 工具。Android Kernel Source 專案首頁提供了使用 repo 腳本下載整個平台的說明。
這個微型雲程式將被交叉編譯到工作站上的 ARM 平台,因此請確保安裝了所有必要工具,使用 apt-get 安裝(見清單 1):
清單 1. 安裝交叉編譯工具
$ sudo apt-get install git-core gnupg \ sun-java5-jdk flex bison gperf libsdl-dev \ libesd0-dev libwxgtk2.6-dev build-essential \ zip curl libncurses5-dev zlib1g-dev
開發目錄的結構
使用目錄名 mydroid 安裝 Android 內核源碼。回到主目錄並執行 mkdir mydroid,然後 cd mydroid 並在其中執行 repo sync 命令。
當 repo sync 把所有 Android 源碼下載到 mydroid 目錄後,會在其中建立許多子目錄,包括:
Android cloud 專案
當 cloud 程式啟動後,它會立即檢查是否有命令列參數傳入。兩個可選的預期參數分別為要監看的埠與要從中啟動的主目錄。若兩者都未指定,程式預設使用標準埠 80 與默認主目錄(即程式啟動時的當前工作目錄)。
啟動完成後,程式會初始化 TCP/IP 插座以透過該埠「偵聽」對它的呼叫,然後將自身轉換為一個守護進程,等待瀏覽器呼叫並提供服務。當瀏覽器呼叫這個微型雲伺服器的預設「頁面」時,程式會回傳「主」目錄的清單作為回應,其中列出含超連結與不含超連結的檔名,取決於它們是已知檔案類型還是目錄。若是已知檔案類型,代表該檔具有對應的 MIME 類型。例如,手機內核的鈴聲以 .ogg 檔儲存,MIME 類型 audio/ogg 會告訴瀏覽器用揚聲器播放它(前提是瀏覽器已正確配置)。
檔案清單頂部還有一個「Parent Directory」超連結,點擊它就能向上瀏覽層次結構,直到抵達最高一級的根目錄。過程中,其他子目錄名都顯示為超連結,點擊即可進入查看其中檔案。
因此,這個 cloud 應用非常實用,能方便地瀏覽手機檔案系統,源碼也為你提供了一個良好的功能模板,可在此基礎上按需修改。本文結尾還給出了修改程式碼的建議方法。(你也可以編譯它並在自己的工作站上運行,瀏覽工作站的檔案系統。)
C 源碼
每個程式的源碼都應盡可能簡潔地標示程式名稱與作者。清單 2 展示了歸屬、include 檔與一些有用的常數。
清單 2. 歸屬、include 檔與有用的常數
// Android Cloud Application by Bill Zimmerly. // Based on "NWEB" by Nigel Griffiths. #include <dirent.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define TRUE -1 #define FALSE 0 #define SBUF 1048576 #define LBUF 4096 #define LAPN 64 #define ERROR 1 #define LOG 2 #define LOGGING FALSE
清單 3 提供了全局工作儲存,可由程式中定義的所有函數存取。當瀏覽器呼叫微型雲時,大多數緩衝區指標都被配置了儲存;當把內容回傳給瀏覽器時,所配置的內容又被釋放回手機。對資源有限的裝置而言,這種實踐比其他許多考量都更為重要。
清單 3. 全局工作儲存
char* about="</pre>Cloud is a simple application that enables " "web-based browsing of the Android file system " "and is intended for use by people who like to " "explore the lowest levels of their device. It " "runs on a rooted android phone and is only for " "browsing the file system. See the IBM " "developerWorks article for a full description " "of this application.<pre>"; char* mainbuf; char* theDir; char* thePort[8]; char* theList; char* fstr; char logDir[LBUF]; int ret;
在此程式中,要正確處理檔案內容,瀏覽器需要知道「副檔名對應 MIME 類型」的簡單映射表。清單 4 的結構由 mimeokay 函數使用,用來把全局字串指標 fstr 設為與副檔名 fext 相匹配的合適 MIME 類型。透過這項資訊,微型雲可以決定把檔名顯示為帶超連結或純文字,並在把檔案內容送給瀏覽器時提供 MIME 類型。
清單 4. 判斷 MIME 類型
struct {
char *ext;
char *mimetype;
} mimes [] = {
{".htm", "text/html" }, {".html", "text/html" },
{".xml", "text/xml" }, {".gif", "image/gif" },
{".jpg", "image/jpeg"}, {".jpeg", "image/jpeg"},
{".png", "image/png" }, {".log", "text/plain"},
{".conf", "text/plain"}, {".rc", "text/plain"},
{".sh", "text/plain"}, {".prop", "text/plain"},
{".txt", "text/plain"}, {".TXT", "text/plain"},
{".cpp", "text/plain"}, {".c", "text/plain"},
{".h", "text/plain"}, {".ogg", "audio/ogg" },
{0,0} };
void mimeokay(char* fext) {
int buflen;
int len;
long i;
buflen=strlen(fext);
fstr = (char*) 0;
for(i=0; mimes[i].ext != 0; i++) {
len = strlen(mimes[i].ext);
if(!strncmp(&fext[buflen-len], mimes[i].ext, len)) {
fstr=mimes[i].mimetype;
break;
}
}
}
清單 5 是一段可選程式碼,可在開發與測試期間把微型雲的行為記錄到 cloud.log 檔。由於雲運行在相對較慢的硬體上,除非你在改動程式碼時確實需要了解其中發生的事,否則最好停用這項功能。若要啟用記錄,清單 1 中的 LOGGING 常數應設為 TRUE;但若是跑在手機上,應設為 FALSE,因為效能損失相當明顯。
清單 5. 記錄行為
void aclog(int type, char *s1, char *s2, int num) {
int fd ;
char aclogbuffer[LBUF];
char logFile[LBUF];
if(!LOGGING) return;
switch(type) {
case ERROR:
sprintf(aclogbuffer, "ERROR: %s:%s Error Number=%d, PID=%d", s1, s2, errno, getpid());
break;
case LOG:
sprintf(aclogbuffer, "INFO: %s:%s:%d", s1, s2, num);
break;
}
strcpy(logFile, logDir);
strcat(logFile, "/cloud.log");
if((fd = open(logFile, O_CREAT | O_WRONLY | O_APPEND, 0644)) >= 0) {
ret=write(fd, aclogbuffer, strlen(aclogbuffer));
ret=write(fd, "\n", 1);
close(fd);
}
if(type == ERROR) exit(3);
}
清單 6 提供了一些為建立微型雲 HTML 版面而定義的函數。注意,設計良好的網站每個頁面都應維持一致的外觀,而 buildbuf 函數正是定義整體外觀的地方。
清單 6. 生成 HTML 輸出
void apname(void) {
strcat(mainbuf, "Android Cloud Application");
}
void buildbuf(char* data) {
mainbuf[0]=0;
strcat(mainbuf, "<html>\n<head>\n<title>");
apname();
strcat(mainbuf, "</title>\n</head>\n");
strcat(mainbuf, "<body>\n<h3>");
apname();
strcat(mainbuf, "</h3>\n");
strcat(mainbuf, "<a href=\"/About_\">About</a><br>\n");
strcat(mainbuf, "<a href=\"/Home_\">Home</a><br>\n");
strcat(mainbuf, "<hr>\n");
strcat(mainbuf, "Dir: ");
strcat(mainbuf, theDir);
strcat(mainbuf, "<br>\n<hr>\n<pre>\n");
strcat(mainbuf, data);
strcat(mainbuf, "\n</pre>\n");
strcat(mainbuf, "</body>\n</html>\n");
}
void htmlout(int fd, char* data) {
fstr=mimes[0].mimetype;
sprintf(mainbuf, "HTTP/1.0 200 OK\r\nContent-Type: %s\r\n\r\n", fstr);
ret=write(fd, mainbuf, strlen(mainbuf));
buildbuf(data);
ret=write(fd, mainbuf, strlen(mainbuf));
}
void error404(int fd) {
fstr=mimes[0].mimetype;
sprintf(mainbuf, "HTTP/1.0 404 OK\r\nContent-Type: %s\r\n\r\n", fstr);
ret=write(fd, mainbuf, strlen(mainbuf));
buildbuf("404 Error - File not found!");
ret=write(fd, mainbuf, strlen(mainbuf));
}
清單 7 展示微型雲如何回傳具指定 MIME 類型的檔案內容。注意,瀏覽器要求伺服器把 MIME 類型作為 Content-Type 字串送出。只需點擊由雲生成的連結,就會呼叫該函數回傳檔案內容;若瀏覽器網址列中編輯了錯誤檔名,則前面定義的 error404 函數會向使用者提示錯誤。
清單 7. 回傳檔案內容
void retfile(int fd, int hit) {
int file_fd;
long ret;
mimeokay(mainbuf);
if(fstr == 0) { error404(fd); return; }
if((file_fd = open(&mainbuf[4], O_RDONLY)) == -1) {
error404(fd);
} else {
aclog(LOG, "SEND", &mainbuf[4], hit);
sprintf(mainbuf, "HTTP/1.0 200 OK\r\nContent-Type: %s\r\n\r\n", fstr);
ret=write(fd, mainbuf, strlen(mainbuf));
while((ret=read(file_fd, mainbuf, SBUF)) > 0 ) {
ret=write(fd, mainbuf, ret);
}
}
}
清單 8 展示微型雲如何建構含超連結的主檔案清單。hyper 函數被多次使用,因此把它獨立成一個函數是明智的。isDir 值會把完整路徑前面的 /CD_ 文字放到檔名開頭,好讓微型雲知道要顯示該目錄的內容。fileList 函數其實是這個應用的真正核心。
清單 8. 目錄清單功能
void hyper(int isDir, char* name) {
strcat(theList, "<a href=\"");
if(isDir) strcat(theList, "/CD_");
strcat(theList, (char*) theDir);
if(strcmp(theDir, "/")) strcat(theList, "/");
strcat(theList, name);
strcat(theList, "\">");
strcat(theList, name);
strcat(theList, "</a>");
strcat(theList, "\n");
}
char* fileList(void) {
struct dirent **namelist;
int n;
long i;
long j;
theList[0]=0;
n=scandir(".", &namelist, 0, (void*) alphasort);
if (n < 0) perror("scandir");
else {
for(i=0; i<n; i++) {
if(namelist[i]->d_type == DT_DIR) {
if(!strcmp(namelist[i]->d_name, ".")) {
// strcat(theList, namelist[i]->d_name);
} else if(!strcmp(namelist[i]->d_name, "..")) {
if(strcmp(theDir, "/")) {
strcat(theList, "<a href=\"");
strcat(theList, "/CD_");
strcat(theList, (char*) theDir);
j=strlen(theList);
while(j--) {
if(theList[j] == '/') {
theList[j]=0;
j=1;
}
}
if(!strcmp(&theList[strlen(theList)-4], "/CD_")) {
strcat(theList, "/");
}
strcat(theList, "\">Parent Directory</a>");
strcat(theList, "\n");
}
} else hyper(TRUE, namelist[i]->d_name);
} else {
mimeokay(namelist[i]->d_name);
if(fstr == 0) {
strcat(theList, namelist[i]->d_name);
strcat(theList, "\n");
} else hyper(FALSE, namelist[i]->d_name);
}
free(namelist[i]);
}
free(namelist);
}
return theList;
}
清單 9 定義了微型雲伺服器的 child 功能。它在伺服器每次收到瀏覽器請求時運行,提供一個簡單功能:配置滿足請求所需的緩衝、處理緩衝,然後釋放緩衝,這樣在不需要使用記憶體時,配置的系統記憶體就會降低。在手機中,記憶體是極稀缺的資源,因此程式處理完一個請求後,應把所占用的記憶體還給系統。
清單 9. Daemon child 功能
void child(int fd, int hit) {
long i;
long ret;
char* cret;
mainbuf=malloc(SBUF+1);
theList=malloc(SBUF+1);
theDir=malloc(LBUF+1);
cret=getcwd(theDir, LBUF);
ret=read(fd, mainbuf, SBUF);
if(ret == 0 || ret == -1) {
error404(fd);
} else {
if(ret > 0 && ret < SBUF) mainbuf[ret]=0;
else mainbuf[0]=0;
for(i=0; i<ret; i++) if(mainbuf[i] == '\r' || mainbuf[i] == '\n') mainbuf[i]='*';
aclog(LOG, "request", mainbuf, hit);
for(i=4; i < SBUF; i++) {
if(mainbuf[i] == ' ') {
mainbuf[i]=0;
break;
}
}
if(!strncmp(&mainbuf[0], "GET /\0", 6) || !strncmp(&mainbuf[0], "get /\0", 6)) {
htmlout(fd, fileList());
} else {
if(!strncmp(&mainbuf[5], "About_", 6)) {
htmlout(fd, about);
} else if(!strncmp(&mainbuf[5], "Home_", 5)) {
htmlout(fd, fileList());
} else if(!strncmp(&mainbuf[5], "CD_", 3)) {
if(chdir(&mainbuf[8]) == -1) {
error404(fd);
} else {
if(strcmp(theDir, &mainbuf[8])) strcpy(theDir, &mainbuf[8]);
htmlout(fd, fileList());
}
} else {
retfile(fd, hit);
}
}
}
free(theDir);
free(theList);
free(mainbuf);
sleep(1);
exit(1);
}
微型雲的 main(parent)功能在清單 10 中定義。它配置了將在其上偵聽瀏覽器請求呼叫的 TCP/IP 插座,接著初始化一些全局變量(如 theDir,微型雲將在這些變量中啟動),最終把自身建立為一個駐留程式(也稱 daemon),以便在執行其他進程的同時,於背景安靜地處理瀏覽器請求。
清單 10. Main 函數
int main(int argc, char **argv) {
char* str;
char* cret;
static struct sockaddr_in cli_addr;
static struct sockaddr_in serv_addr;
socklen_t length;
int i;
int port;
int pid;
int listenfd;
int socketfd;
int hit;
cret=getcwd(logDir, LBUF);
if(argc < 2) {
strcpy((char*) thePort, "80");
port=atoi((char*) thePort);
} else {
if(!strcmp(argv[1], "-?")) {
printf("Usage: cloud [Port Directory]\n");
exit(0);
}
strcpy((char*) thePort, argv[1]);
port=atoi((char*) thePort);
if(port < 0 || port > 60000) aclog(ERROR, "Invalid port number (try 1 --> 60000)", argv[1], 0);
if(chdir(argv[2]) == -1) {
printf("ERROR: Invalid directory %s\n", argv[2]);
exit(4);
}
}
if(fork() != 0) return 0;
signal(SIGCHLD, SIG_IGN);
signal(SIGHUP, SIG_IGN);
for(i=0; i<32; i++) close(i);
setpgrp();
aclog(LOG, "Cloud Port/PID=", (char*) thePort, getpid());
if((listenfd=socket(AF_INET, SOCK_STREAM, 0)) < 0) aclog(ERROR, "syscall", "socket", 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(port);
if(bind(listenfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0) aclog(ERROR, "syscall", "bind", 0);
if(listen(listenfd, 64) <0) aclog(ERROR, "syscall", "listen", 0);
for(hit=1; ;hit++) {
length=sizeof(cli_addr);
if((socketfd=accept(listenfd, (struct sockaddr*) &cli_addr, (socklen_t*) &length)) < 0) aclog(ERROR, "syscall", "accept", 0);
if((pid=fork()) < 0) {
aclog(ERROR, "syscall", "fork", 0);
} else {
if(pid == 0) {
close(listenfd);
child(socketfd, hit);
} else {
close(socketfd);
}
}
}
}
編譯、部署與測試應用程式
你需要另外建立一個檔,以配合內核源碼的 makefile 正確編譯這個雲應用。建立一個名為 android.mk 的檔,並把清單 11 的內容貼入其中。
清單 11. android.mk
ifneq ($(TARGET_SIMULATOR),true) LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES:= cloud.c LOCAL_MODULE := cloud LOCAL_STATIC_LIBRARIES := libcutils libc include $(BUILD_EXECUTABLE) endif # TARGET_SIMULATOR != true
導航到 Android 內核源碼的 external 目錄,建立一個名為 cloud 的子目錄,把 cloud.c 與 android.mk 全部放入其中,然後就可以開始構建新的 Android 內核系統,微型雲應用便會位於其中。
移動到 Android 內核源碼的根目錄,輸入 make 並耐心等待——這一過程會花些時間,讓系統完成它的工作。若一切順利並完成編譯,你應能在 out/target/product/generic/system/bin 目錄中找到微型雲的二進位檔。你無須把整個發行版安裝到已 root 的手機中,只需把雲二進位檔複製到 SD 卡即可。清單 12 展示了如何完成這一步(假設 mydroid 目錄包含所有 Android 內核源碼):
清單 12. 編譯內核與雲
$ cd mydroid/external $ mkdir cloud $ cd cloud $ cp ~/src/tinycloud/cloud.c . $ cp ~/src/tinycloud/android.mk . $ cd ../.. $ make --- Android system "make" messages scroll up the screen for a long time. --- $ cd out/target/product/generic/system/bin $ cp cloud /media/androidSDCARD/.
注意,/media/androidSDCARD 意味著你已把手機連上電腦並完成設定,SD 卡的名稱可能不同,可查看 /media 子目錄(若在 Ubuntu Linux 下運行)取得正確名稱。
執行 Android Market 免費提供的 Terminal 程式,能讓你在手機中運行一個 shell 會話。Android 雲一般駐留在 system/bin 目錄,但這不是必須的。為滿足測試需求,可把它放在不同目錄。在 /data 下建立一個名為 cloud 的目錄,把 /sdcard 中的 cloud 二進位檔複製到 /data/cloud,然後用 chmod 讓它可執行,再輸入 cloud 運行它。清單 13 展示了這些步驟:
清單 13. 在手機上測試雲
$ su # cd data # mkdir cloud # cd cloud # cp /sdcard/cloud . # chmod 777 cloud # ./cloud # ps --- Listing of resident daemons, and "./cloud" should be one of them. ---
按下 Home 鍵,啟動瀏覽器並前往 https://localhost,你就會在手機瀏覽器中看到微型雲的輸出,透過點擊顯示的連結即可存取手機的檔案系統。
接下來,若手機的 Wi-Fi 正在網路中運行,就能用電腦呼叫微型雲。為此你需要知道手機的 Wi-Fi IP 位址,可透過檢查 Wi-Fi 路由器的日誌取得;另一種方法是回到 Terminal 並輸入 netstat -r,你應會看到類似清單 14 的條目。
清單 14. 使用 Netstat 取得手機 IP 位址
# netstat -r Proto Recv-Q Send-Q Local Address Foreign Address ... . . . tcp 0 0 192.168.0.3:80 192.168.0.5:58744 ... . . .
在瀏覽器網址列輸入 https://192.168.0.3/(手機的 IP 位址),你就會很快看到經由微型雲呈現的手機檔案系統清單。
同時,要在手機中用微型雲瀏覽你建立的網頁,只需長按 Home 鍵並點擊瀏覽器或編輯器來切換應用;若點擊瀏覽器,就刷新選單以查看已編輯的修改。透過反覆「編輯/測試/編輯/測試」直到找到理想內容,當你在牙醫診所排隊等候時,就能上網衝浪了。
增強專案
你可以用許多方法增強這個專案,以下提供一些建議:
當你決定為微型雲做一項改進時,可執行以下三個一般步驟來新增功能:
結束語
盡可能多地了解你所用的裝置,始終是一件好事;而編寫能幫助你了解裝置的工具,也非常有趣。把一個微型雲應用放進 Android 手機的內核中,是一個有趣又能學到許多知識的過程,它將讓你窺見這些神奇裝置內部所隱藏的種種奧妙。
Android 開發經驗分享(3):好用的產品,永遠勝過功能堆疊
好的使用者體驗能讓產品達到事半功倍的效果。在一堆同類軟體裡,下載量最高的那一個,往往就是讓人用起來最舒服的,哪怕它的功能並不比對手出色,甚至略遜一籌。 我看過不少開發者把
Android 全家福:從 1.0 到 3.0 的發展歷程回顧
2010 年 5 月 20 日的 Google I/O 大會上,Android 2.2 Froyo 正式發布;同年 12 月 7 日凌晨一時,Android 2.3 Gi
Android Service 教學:建立與管理背景服務
Service 是一種在背景執行、處理長時間作業而且不需要使用者互動的元件。典型情境像是背景播放音樂,或是在使用者切換到其他 App 時仍持續從網路抓取資料,而不阻塞前景
完美的Android手機作業系統:從Eee PC到電視機
Android手機作業系統的設計初衷是智慧型手機平台,但已有數家筆記型電腦與數位相框廠商對它做了嘗試,並進一步探索在自家領域拓展這項業務的可能。 為什麼它能跨出 } A