前幾天有需要在java代碼中調用二進制程式,就在網上找了些資料,寫點東西記錄下。
Android 也是基于linux
的系統,當然也可以運作二進制的可執行檔案。隻不過Android
限制了直接的方式隻能安裝運作apk檔案。雖然有NDK可以用動态連結庫的方式來用C的二進制代碼,但畢竟不友善。至少我們可以調用linux的一些基本
指令,如ls,rm等。
第一種方法:Runtime.exec(String[] args)
這種方法是java語言本身來提供的,在Android裡面也可以使用。args是要執行的參數數組。大概用法如下:
S
tring[] args = new String[2];
args[0] = "ls";
args[1] = "-l";
try
{
Process process = Runtime.getRuntime().exec(arg);
//get the err line
InputStream stderr = process.getErrorStream();
InputStreamReader isr
err = new InputStreamReader(stderr);
BufferedReader br
err = new BufferedReader(isr
err);
//get the output line
InputStream outs = process.getInputStream();
InputStreamReader isrout = new InputStreamReader(outs);
BufferedReader brout = new BufferedReader(isrout);
String
errline = null;
String result
= "";
// get the whole error message string
while ( (line = br
err.readLine()) != null)
result
+= line;
+= "/n";
}
i
f( result != "" )
// put the result string on the screen
// get the whole standard output string
while ( (line = brout.readLine()) != null)
result += line;
result += "/n";
if( result != "" )
}catch(Throwable t)
t.printStackTrace();
以上
代碼執行了linux的标準指令 ls -l。執行此指令後的标準輸出是在brout中。如果出錯,像參數錯誤,指令錯誤等資訊就會放在brerr中。
有需要的話從裡面讀出來便可。
第二種方法:Class.forName("android.os.Exec")
代碼大概是這樣:
try {
這種方法是用了 Android 提供的android.os.Exec類。在 Android 的源代碼中已經提供了類似 terminal 的ap,在
/development/apps/Term/src/com/android/term 中,這個ap就是用android.os.Exec來調用linux的基本指令的。不過這個類隻有在Android的内置ap中才可以使用。單獨寫一個非
内置ap的話是無法直接調用android.os.Exec的。間接的方法就是類似上面,用
Class.forName("android.os.Exec")來得到這個
類,execClass.getMethod("createSubprocess", ...
)來得到類裡面的方法,這樣就可以使用本來不能用的類了。這就是反射?...
這個方法看起來要麻煩一些,而且比較歪,我覺得還是用java本身提供的東西比較好,畢竟簡單,移植性也好點。
至于自己寫的二進制執行程式如何放到apk裡面如何調用,原帖也說的很清楚,不過要提醒一下,assets檔案夾對單個檔案大小有限制為1MB. 是以如果有資源檔案大于1MB我看隻好自己先切割一下了