Android: 通過Runtime.getRuntime().exec呼叫底層Linux下的程式或指令碼
阿新 • • 發佈:2019-02-04
Android Runtime使得直接呼叫底層Linux下的可執行程式或指令碼成為可能
比如Linux下寫個測試工具,直接編譯後apk中通過Runtime來呼叫
或者寫個指令碼,apk中直接呼叫,省去中間層或者JNI
這個至少效率應該比較高吧
程式碼:
- publicclass test extends Activity {
- TextView text;
- /** Called when the activity is first created. */
- @Override
-
publicvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- text = (TextView) findViewById(R.id.text);
- Button btn_ls = (Button) findViewById(R.id.btn_ls);
- btn_ls.setOnClickListener(new OnClickListener() {
-
publicvoid onClick(View v) {
- do_exec("ls /mnt/sdcard");
- }
- });
- Button btn_cat = (Button) findViewById(R.id.btn_cat);
- btn_cat.setOnClickListener(new OnClickListener() {
- publicvoid onClick(View v) {
-
do_exec("cat /proc/version"
- }
- });
- Button btn_rm = (Button) findViewById(R.id.btn_rm);
- btn_rm.setOnClickListener(new OnClickListener() {
- publicvoid onClick(View v) {
- do_exec("rm /mnt/sdcard/1.jpg");
- }
- });
- Button btn_sh = (Button) findViewById(R.id.btn_sh);
- btn_sh.setOnClickListener(new OnClickListener() {
- publicvoid onClick(View v) {
- do_exec("/system/bin/sh /mnt/sdcard/test.sh 123");
- }
- });
- }
- String do_exec(String cmd) {
- String s = "/n";
- try {
- Process p = Runtime.getRuntime().exec(cmd);
- BufferedReader in = new BufferedReader(
- new InputStreamReader(p.getInputStream()));
- String line = null;
- while ((line = in.readLine()) != null) {
- s += line + "/n";
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- text.setText(s);
- return cmd;
- }
- }
test.sh:
echo test.sh
echo $1
需要注意:
1. exec不等於console命令
2. exec的輸入輸出流需要自己處理
3. exec執行時阻塞、非阻塞,返回結果問題
4. 注意許可權問題
有個文章講的比較深入,貼出來研究: