Android - 代码执行shell命令的应用

2023-12-24 04:21:03


前言

本文只上代码,没有什么好讲的,直接复制粘贴拿去用就行了


一、执行命令无返回

    /*
    执行命令无返回
    用法:execSuCmd("logcat -c")
     */
    public void execSuCmd(String cmd) {
        Process process = null;
        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec("sh");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
            os.close();
            process.destroy();
        } catch (Exception e) {
        } finally {
            try {
                if (os != null) os.close();
            } catch (IOException e) {
            }
        }
    }

二、执行命令并接收返回结果

    /*
        执行命令并接收返回结果,执行失败返回失败打印,执行成功返回成功打印
        用法:execCommand("ifconfig")
     */
    public String execCommand(String cmd) {
        String result = "";
        Process process = null;
        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec("sh");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();

            char[] buff = new char[1024];
            int ch = 0;

            //命令执行成功,接收输出内容
            BufferedReader bfsd = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer sbs = new StringBuffer();
            while ((ch = bfsd.read(buff)) != -1) {
                sbs.append(buff, 0, ch);
            }
            bfsd.close();
            //命令执行失败,接收错误信息
            BufferedReader ero = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            StringBuffer era = new StringBuffer();
            while ((ch = ero.read(buff)) != -1) {
                era.append(buff, 0, ch);
            }
            ero.close();
            os.close();
            process.destroy();

            if (sbs.length() != 0) {
                result = String.valueOf(sbs);
            } else {
                result = String.valueOf(era);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

三、查询是否有指定的节点

    /*
    查询是否有指定的节点,没有则返回-1
    用法:getATTRData("cat /sys/devices/platform/ff140000.i2c/i2c-5/5-0027/PCF8574_TO_ZigbeeGPIO5");
    */
    public int getATTRData(String sys_path) {
        int ret = -1;
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(sys_path);
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            while (null != (line = br.readLine())) {
                ret = Integer.parseInt(line);
                return ret;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

四、查询系统中指定路径的文件是否存在

   /*
    查询系统中指定路径的文件是否存在
    用法:ttyPathExist("/sys/devices/platform/fec80000.i2c/i2c-6/6-0062/testLED");
    */
    public boolean ttyPathExist(String path) {
        File ttyPath_ok = new File(path);
        boolean exist = ttyPath_ok.exists();
        if (exist)
            return true;
        else
            return false;
    }

五、执行命令后循环接收返回内容

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button on_log;
    private Button off_log;
    private TextView tx;
    private ScrollView slv;
    private String reslut = null;
    private Process process = null;
    private DataOutputStream os = null;
    private BufferedReader bfsd = null;
    private boolean onoff = false;
    private Handler myHander = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 111) {
                tx.setText(reslut);
                slv.fullScroll(ScrollView.FOCUS_DOWN);
            }
        }

    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.on_log:
                //打开接收
                onoff = true;
             //   threaadExecSuCmd("screenrecord /sdcard/demo.mp4");
             //   threaadExecSuCmd("ifconfig");
                threaadExecSuCmd("logcat");
                break;
            case R.id.off_log:
                //关闭接收
                onoff = false;
                break;
        }
    }

    public void threaadExecSuCmd(String cmd) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    process = Runtime.getRuntime().exec("su");
                    os = new DataOutputStream(process.getOutputStream());
                    os.writeBytes(cmd + "\n");
                    os.writeBytes("exit\n");
                    os.flush();
                    bfsd = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    StringBuffer sbs = new StringBuffer();
                    char[] buff = new char[1024];
                    int ch = 0;
                    while ((ch = bfsd.read(buff)) != -1 && onoff) {
                        sbs.append(buff, 0, ch);
                        reslut = String.valueOf(sbs);
                        myHander.sendEmptyMessage(111);
                    }
                    bfsd.close();
                    os.close();
                    process.destroy();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void initView() {
        on_log = (Button) findViewById(R.id.on_log);
        off_log = (Button) findViewById(R.id.off_log);
        tx = (TextView) findViewById(R.id.tx);

        on_log.setOnClickListener(this);
        off_log.setOnClickListener(this);
        slv = (ScrollView) findViewById(R.id.slv);
        slv.setOnClickListener(this);
    }
}

总结

部分shell命令需要系统签名后才能使用,比如下滑通知栏的命令

文章来源:https://blog.csdn.net/2301_77563065/article/details/132741794
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。