android 中如何使用shell命令,并且拿到结果

标签:
android命令行shell |
最近一直在coding,都没时间学习新东西了,今天刚好有空,就尝试的学习了一下在android中如何使用shell命令。今天就以adb命令为例,不管是在windows命令行窗口或是在linux的终端窗口,adb的命令调试我们也用过一些,就说一个最简单的吧,>adb
version,这个是查看adb版本的一个命令,那么在android程序中该如何执行呢?又该如何获取到返回的版本信息呢?
答案即将揭晓,请看demo
package com.aiteu.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements
OnClickListener {
private TextView mMsgText = null;
private EditText mIpEditext = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.conn_btn).setOnClickListener(this);
mMsgText = (TextView)findViewById(R.id.textView1);
mIpEditext = (EditText)findViewById(R.id.ipedittext);
}
//点击按钮,执行命令
@Override
public void onClick(View v) {
//这个类是一个很好用的工具,java中可以执行java命令,android中可以执行shell命令
Runtime mRuntime = Runtime.getRuntime();
try {
//Process中封装了返回的结果和执行错误的结果
Process mProcess =
mRuntime.exec("adb version");
BufferedReader mReader = new
BufferedReader(new
InputStreamReader(mProcess.getInputStream()));
StringBuffer mRespBuff = new
StringBuffer();
char[] buff = new char[1024];
int ch = 0;
while((ch = mReader.read(buff)) !=
-1){
mRespBuff.append(buff, 0,
ch);
}
mReader.close();
mMsgText.setText(mRespBuff.toString());
} catch (IOException e) {
// TODO Auto-generated catch
block
e.printStackTrace();
}
}
}
获得错误提示的操作是这样的:
DateInputStream dis = new
DataInputStream(p.getErrorStream());
运行截图:
前一篇:android应用程序列表