易网时代-编程资源站
Welcome
微信登录
编程资源
图片资源库
蚂蚁家优选
PDF转换器
软件资源
软件开发
、
小程序制作
、
系统集成与运维
、
空间租用
、
硬件开发
、
视频监控
、
技术咨询与支持
——联系电话:0311-88999002/88999003
首页
/
操作系统
/
Linux
/
Android中级篇之用JAVA代码执行shell命令
在Android可能有的系统信息没有直接提供API接口来访问,为了获取系统信息时我们就要在用shell指令来获取信息,这时我们可以在代码中来执行命令 ,这里主要用到
ProcessBuilder
这个类.
代码部分 :
package
com.yin.system_analysis;
import
java.io.File;
import
java.io.IOException;
import
java.io.InputStream;
import
android.app.Activity;
import
android.os.Bundle;
import
android.util.Log;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.TextView;
public
class
MainActivity
extends
Activity {
private
final
static
String[] ARGS = {
"ls"
,
"-l"
};
private
final
static
String TAG =
"com.yin.system"
;
Button mButton;
TextView myTextView;
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton = (Button) findViewById(R.id.myButton);
myTextView = (TextView) findViewById(R.id.textView);
mButton.setOnClickListener(
new
OnClickListener() {
public
void
onClick(View v) {
myTextView.setText(getResult());
}
});
}
public
String getResult(){
ShellExecute cmdexe =
new
ShellExecute ( );
String result=
""
;
try
{
result = cmdexe.execute(ARGS,
"/"
);
}
catch
(IOException e) {
Log.e(TAG,
"IOException"
);
e.printStackTrace();
}
return
result;
}
private
class
ShellExecute {
/*
* args[0] : shell 命令 如"ls" 或"ls -1";
* args[1] : 命令执行路径 如"/" ;
*/
public
String execute ( String [] cmmand,String directory)
throws
IOException {
String result =
""
;
try
{
ProcessBuilder builder =
new
ProcessBuilder(cmmand);
if
( directory !=
null
)
builder.directory (
new
File ( directory ) ) ;
builder.redirectErrorStream (
true
) ;
Process process = builder.start ( ) ;
//得到命令执行后的结果
InputStream is = process.getInputStream ( ) ;
byte
[] buffer =
new
byte
[
1024
] ;
while
( is.read(buffer) != -
1
) {
result = result +
new
String (buffer) ;
}
is.close ( ) ;
}
catch
( Exception e ) {
e.printStackTrace ( ) ;
}
return
result ;
}
}
}
布局文件很简单就不列出了
收藏该网址
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图