JAVA代码执行shell命令 并解析
16lz
2021-01-26
在Android可能有的系统信息没有直接提供API接口来访问,为了获取系统信息时我们就要在用shell指令来获取信息,这时我们可以在代码中来执行命令 ,这里主要用到ProcessBuilder这个类.
代码部分 :
[java] view plain copy
- packagecom.yin.system_analysis;
- importjava.io.File;
- importjava.io.IOException;
- importjava.io.InputStream;
- importandroid.app.Activity;
- importandroid.os.Bundle;
- importandroid.util.Log;
- importandroid.view.View;
- importandroid.view.View.OnClickListener;
- importandroid.widget.Button;
- importandroid.widget.TextView;
- publicclassMainActivityextendsActivity{
- privatefinalstaticString[]ARGS={"ls","-l"};
- privatefinalstaticStringTAG="com.yin.system";
- ButtonmButton;
- TextViewmyTextView;
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mButton=(Button)findViewById(R.id.myButton);
- myTextView=(TextView)findViewById(R.id.textView);
- mButton.setOnClickListener(newOnClickListener(){
- publicvoidonClick(Viewv){
- myTextView.setText(getResult());
- }
- });
- }
- publicStringgetResult(){
- ShellExecutecmdexe=newShellExecute();
- Stringresult="";
- try{
- result=cmdexe.execute(ARGS,"/");
- }catch(IOExceptione){
- Log.e(TAG,"IOException");
- e.printStackTrace();
- }
- returnresult;
- }
- privateclassShellExecute{
- /*
- *args[0]:shell命令如"ls"或"ls-1";
- *args[1]:命令执行路径如"/";
- */
- publicStringexecute(String[]cmmand,Stringdirectory)
- throwsIOException{
- Stringresult="";
- try{
- ProcessBuilderbuilder=newProcessBuilder(cmmand);
- if(directory!=null)
- builder.directory(newFile(directory));
- builder.redirectErrorStream(true);
- Processprocess=builder.start();
- //得到命令执行后的结果
- InputStreamis=process.getInputStream();
- byte[]buffer=newbyte[1024];
- while(is.read(buffer)!=-1){
- result=result+newString(buffer);
- }
- is.close();
- }catch(Exceptione){
- e.printStackTrace();
- }
- returnresult;
- }
- }
- }
更多相关文章
- 配置ionic+Android开发环境
- Android(安卓)Info类的总结
- 在Android模拟器中模拟GPS、打电话、发短信
- Android(安卓)unbindservice异常相关问题
- Android开发之获取SHA1
- Xposed Android(安卓)hook -方法介绍
- Android模拟器SD卡的使用
- 第2.3节 android目录中manifest的介绍
- [android]MonkeyRunner-andrec实现思路