在android手机上运行shell脚本

public class MainActivity extends AppCompatActivity {
    TextView editText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editText);

        Button startButton = findViewById(R.id.startButton);
        startButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                do_exec("sh /system/a.sh");
            }
        });
    }

    String do_exec(String cmd) {
        String s = "\n";
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = in.readLine()) != null) {
                System.out.println(line);
                s += line + "/n";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        editText.setText(s);
        return cmd;
    }


}
 
 

xml页面就是一个TextView 和一个按钮

点击按钮,执行shell脚本。


注意:

1.手机必须root

2.shell脚本需要放在/system目录下,并且chmod 777 a.sh,确认成功后才可以执行





猜你喜欢

转载自blog.csdn.net/liuhu767/article/details/79495856