Java/Android中实现Shell命令
16lz
2021-01-26
有时候我们需要实现一个功能。不过这个功能用我们传统的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;}}};}
更多相关文章
- android TextView EditTextView一些技巧使用 (视图代码布局)
- 10.28,python,django中templates的奇偶性,python,swift多语言文件
- Android(安卓)当修改一些代码时,使用什么编译命令可以最有效率
- Android上的Guice RoboGuice
- Android开发_微信分享功能
- Android(安卓)查看动态库依赖的库文件
- Android调用相机拍摄照片并显示到 ImageView控件中
- Android的handler和callback机制
- 2011年沈大海讲师Android的腾讯微博客户端源代码,实现oauth_verif