关于Android中Java调用外部命令的三种方式

此所谓三种方式,只是个人认为。本人还是菜鸟初涉,所以有所错误,请指正。

个人认为,Java调用外部命令。无非三种情况:

一.是只执行命令,不考虑返回值。

二.是执行命令的同时,还需要得到返回值。

三.是执行命令的同时,等待得到返回值。

二和三的不同在于,前者之间可以得到返回。后者通过某些情况后才可以得到返回。

(一)

Runtime.getRuntime().exec("su");

(二)

process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(cmd1 + "\n");
os.writeBytes("exit\n");
os.flush();
process.getErrorStream().close();
InputStream in = process.getInputStream();
byte[] re = new byte[1024];
while (in.read(re) != -1) {
result = result + new String(re);
}
Log.i(TAG, "result = " + result);
in.close();
process.waitFor();


(三).其实跟二差不多。只是需要另开一个线程执行,并一直循环获取。

my = new Thread() {
public void run() {
Process process = null;
        	DataOutputStream os = null;
        	String result = "";
        	try {
        	process = Runtime.getRuntime().exec("su");
        		os = new DataOutputStream(process.getOutputStream());
        		os.writeBytes("getevent /dev/input/event3" + "\n");
        		os.flush();
        		os.close();
        		process.getErrorStream().close();
        		InputStream in = process.getInputStream();
                    byte[] re = new byte[19];
                    Log.i(TAG, "Thread start---");
                    while(true) {
                    	if (in.read(re) != -1) {
                    		Log.i(TAG, "load string...");
                            result = result + new String(re);
                           Log.i(TAG, "run result = " + result);
                    	} else {
                    		Thread.sleep(100);
                    		Log.i(TAG, "sleep result = " + result);
                    	}
                  }
        	} catch (Exception e) {
        		e.printStackTrace();
        	} finally {
        		try {
        			if (os != null) {
        				os.close();
        			}
        			process.destroy();
        		} catch (Exception e) {
        		}
        	}
        }
};




  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值