編輯:開發入門
Android 是 Linux® 的一個特殊發行版,目的在於管理最智慧型手機中的各項功能。對程式設計師來說,Linux 裡的一切——裝置、試算表或最喜愛的一首歌曲——都以「檔案」的形式呈現。也就是說,我們能用一套通用的方法來開啟、擷取、操作或保存這些抽象實體的內容。這種通用性正是 UNIX® 的核心理念:一切皆檔案。
常用縮略詞
檔案被組織成一個稱為「檔案系統」的層級結構。一支 Android 手機通常使用兩種檔案系統:非揮發性記憶體或插入式 SD 卡,兩者都呈現為根目錄(/)下的子目錄。因此,一個能讓你在瀏覽器中方便瀏覽這些檔案系統的工具就很有用。本文定義了一個以 C 語言撰寫的小程式,讓你能從工作站或直接從手機內建瀏覽器瀏覽 Android 手機的檔案系統,它提供帶有超連結的頁面,讓你在層級樹中上下移動,並點擊檢視各類檔案。
首先,確保你手上有一支「已取得 root 授權」的 Android 手機,以便執行像開啟 Terminal 並下 su 指令取得根權限這類操作(這個過程有時也稱為「越獄」)。Android 社群主要使用兩種 SDK:最常見的是高階 Android SDK,讓你用 Java™ 撰寫程式並搭配 Eclipse 開發、測試與除錯;另一種較少見的是 Android 核心源碼,保存在名為 git 的儲存庫中。
由於本文聚焦於建立一個通常位於手機 system/bin 目錄中的低級 Web 伺服器,因此必須下載並安裝完整的 Android 核心源碼與建構用的 GNU 工具。這個微型雲端程式會被交叉編譯到工作站的 ARM 平台,請先確保安裝好必要工具:
$ 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,進入後執行 repo sync。當所有源碼下載完成後,會產生許多子目錄,其中:
mydroid/external 中建立一個 cloud 目錄,本專案的 cloud.c 就放在這裡。out/target/product/generic/system/bin 目錄中。cloud 程式啟動後,會先檢查是否有命令列參數傳入。兩個可選參數分別是「要監聽的連接埠」與「要啟動的主目錄」;若都沒指定,預設使用連接埠 80 與程式啟動時的當前工作目錄。完成啟動後,程式會初始化 TCP/IP 套接字來「監聽」呼叫,並將自己轉為守護進程,等待瀏覽器呼叫並提供服務。
當瀏覽器呼叫這個微型雲端伺服器的預設「頁面」時,程式會回傳主目錄的清單,其中包含帶超連結與不帶超連結的檔名——取決於它們是已知的檔案類型還是目錄。若是已知類型,就代表該檔有對應的 MIME 類型。例如 Android 手機的鈴聲存在 .ogg 檔中,MIME 類型 audio/ogg 會告訴瀏覽器用喇叭播放(前提是瀏覽器已正確設定)。清單頂部還有一個「Parent Directory」超連結,點擊可向上瀏覽層級,直到根目錄。
以下依序說明各個部分的程式碼。首先是歸屬、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
接著是全域工作儲存區,可被程式中所有函式存取。由於手機資源有限,程式在處理完請求後會把配置的記憶體歸還給系統:
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 類型之間的對應表。以下結構由 mimeokay 函式使用,把全域字串指標 fstr 設為與副檔名相符的 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;
}
}
}
以下提供一些在開發測試期間可選的行為記錄功能,會把 Android 雲端的行為寫入 cloud.log。由於雲端運行在相對較慢的硬體上,正式在手機上運行時應把 LOGGING 設為 FALSE,因為效能損失相當明顯:
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);
}
以下定義了建立微型雲端 HTML 布局的函式。buildbuf 就是決定整體外觀的地方:
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));
}
以下示範如何回傳具有指定 MIME 類型的檔案內容。瀏覽器會要求伺服器把 MIME 類型作為 Content-Type: 字串送出;只要點擊雲端產生的連結就會呼叫這個函式。若在網址列輸入錯誤的檔名,則會呼叫 error404 通知使用者:
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);
}
}
}
以下示範如何建立帶超連結的檔案清單。fileList 其實就是整個應用程式的核心:
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, ".")) {
// 略
} 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;
}
以下定義微型雲端伺服器的 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)功能,它配置用來監聽瀏覽器請求的 TCP/IP 套接字,初始化全域變數,並把自己建立為一個常駐程式(daemon),在背景安靜地處理請求:
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); }
}
}
}
要正確編譯這個雲端應用程式,需另外建立一個 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 放進去,然後回到源碼根目錄執行 make,等待系統完成編譯。順利的話,你會在 out/target/product/generic/system/bin 找到 cloud 二進位檔。你無須把整個發行版裝進手機,只要把這個二進位檔複製到 SD 卡即可:
$ cd mydroid/external
$ mkdir cloud
$ cd cloud
$ cp ~/src/tinycloud/cloud.c .
$ cp ~/src/tinycloud/Android.mk .
$ cd ../..
$ make --- 訊息會滾動很長一段時間 ---
$ cd out/target/product/generic/system/bin
$ cp cloud /media/androidSDCARD/.
請注意 /media/androidSDCARD 需依實際掛載名稱調整。使用 Android Market 免費提供的 Terminal 程式可在手機中開啟 shell 工作階段,把 SD 卡裡的 cloud 複製到 /data 下的目錄,加上可執行權限後執行:
$ su
# cd data
# mkdir cloud
# cd cloud
# cp /sdcard/cloud .
# chmod 777 cloud
# ./cloud
# ps --- 應能看到 ./cloud 常駐 ---
按下 Home 鍵啟動瀏覽器,前往 https://localhost,就能在手機瀏覽器中看到微型雲端的輸出,並透過點擊連結瀏覽檔案系統。若手機 Wi-Fi 已連上網路,還能用電腦呼叫它——先取得手機的 Wi-Fi IP(可查路由器日誌,或在 Terminal 中執行 netstat -r):
# netstat -r
tcp 0 0 192.168.0.3:80 192.168.0.5:58744 ...
在電腦瀏覽器網址列輸入 https://192.168.0.3/(手機 IP),就能很快看到由微型雲端呈現的手機檔案系統清單。
你可以用許多方式增強這個專案,例如:
當你決定增強功能時,一般步驟是:修改 buildbuf 加入新的選單項;修改 child 為新功能提供服務;撰寫對應函式並在 child 中插入呼叫。
盡可能了解你使用的裝置,永遠是件好事;而撰寫能幫助你了解裝置的工具,更是有趣。把一個微型雲端運算應用程式放進 Android 手機的核心,是一個有趣又能學到很多東西的過程,讓你能窺見這些神奇裝置內部隱藏的大量知識。
Android 2.2 開發環境建置全攻略(Windows 篇)
本文以 Windows 7 為示範平台,記錄從 JDK 安裝一路到建立並啟動 AVD 的完整流程。 環境概要 作業系統:Windows 7 JDK:java ver
Android 開發入門(三):動手做一個簡易手電筒 App
建立第一個 Android 應用 本文以一個修改自 Hello Android 的範例為基礎,示範如何建立最簡單的 Android 應用。這個範例會把畫面背景改為白色,讓
用 Eclipse 與 Android 元件做開發(二):跑起來、看懂專案結構
在模擬器上運行應用程序 要部署並執行應用,得先定義一組執行配置。在 Eclipse 裡選擇 Open > Run > Dialog(或工具列上的捷徑),挑選
Android數據庫事務淺析
在Android應用開發中,數據庫操作時常出現,而數據庫事務的處理對應用的穩定性與效率提升至關重要。 首先,Android的數據庫操作——尤其是寫操作——非常慢,把所有操