1. 程式人生 > >在android手機上執行shell指令碼

在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,確認成功後才可以執行