Android中级篇之用JAVA代码执行shell命令
16lz
2021-01-26
http://www.linuxidc.com/Linux/2011-12/48958.htm
在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 ;
- }
- }
- }
布局文件很简单就不列出了
更多相关文章
- Android开发——AsyncTask的使用以及源码解析
- WINDOWS下ADB基本的教程和命令
- Android官方命令深入分析之etc1tool
- Android(安卓)耗时代码(ANR)的查找检测和分析解决 TraceView的使
- 命令行下查看android sqlit3数据库信息
- Android(安卓)Service基本知识
- android failed to start daemon 问题
- Android(安卓)- adb - Linux - 程序“adb”尚未安装
- android关于轮询的一种解决方案