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; @Override public 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() { @Override public 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; } } }; }