Java/Android中实现Shell命令
生活随笔
收集整理的這篇文章主要介紹了
Java/Android中实现Shell命令
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
有時候我們需要實現一個功能。不過這個功能用我們傳統的Java代碼實現起來會有一些困難,這時我們可以嘗試利用Shell命令來實現。你可以按照下面的代碼模塊來進行你想要實現的Shell命令(注:也不是所有的Shell命令都能用Java代碼來實現)。
public class MainActivity extends Activity {private final String TAG = "---MainActivity---";public final String SHELL_0 = "busybox ps";public final String SHELL_1 = "su";public final String SHELL_2 = "cd mnt/shell/emulated/0/.ZFSafeFS";public final String SHELL_3 = "busybox mount .a1.img ./.abc";public final String SHELL_4 = "busybox umount ./.abc";public final String EXECUTE_SHELL = SHELL_0;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button sendButton = (Button) findViewById(R.id.send_btn);Button suButton = (Button) findViewById(R.id.su_button);Button cdButton = (Button) findViewById(R.id.alert_path_button);Button mountButton = (Button) findViewById(R.id.mount_button);Button umountButton = (Button) findViewById(R.id.umount_button);suButton.setText(SHELL_1);cdButton.setText(SHELL_2);mountButton.setText(SHELL_3);umountButton.setText(SHELL_4);sendButton.setOnClickListener(viewOnClickListener);suButton.setOnClickListener(viewOnClickListener);cdButton.setOnClickListener(viewOnClickListener);mountButton.setOnClickListener(viewOnClickListener);umountButton.setOnClickListener(viewOnClickListener);handleShell(EXECUTE_SHELL);}private void handleShell(String shell) {TextView textView = (TextView) findViewById(R.id.textview);Process p = null;try {p = Runtime.getRuntime().exec(shell);if (p == null) {textView.setText("p == null");} else {BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));int read = 0;char[] buffer = new char[4096];StringBuffer output = new StringBuffer();Log.i(TAG, "read = " + read);Log.i(TAG, "output = " + output);while((read = bufferedReader.read(buffer)) > 0) {output.append(buffer, 0, read);}bufferedReader.close();String string = String.copyValueOf(buffer);Log.i(TAG, "string = " + string);textView.setText("result:\n" + string);}} catch (IOException e) {textView.setText("e=" + e);e.printStackTrace();}}private OnClickListener viewOnClickListener = new OnClickListener() {@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.su_button:handleShell(SHELL_1);break;case R.id.alert_path_button:handleShell(SHELL_2);break;case R.id.mount_button:handleShell(SHELL_3);break;case R.id.umount_button:handleShell(SHELL_4);break;default:break;}}}; }
總結
以上是生活随笔為你收集整理的Java/Android中实现Shell命令的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android实现程序之间的跳转
- 下一篇: android sina oauth2.