public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

doSU();
}

@Override
protected void onResume() {
super.onResume();
doSU();
}

private void doSU() {
try {
Process process = Runtime.getRuntime().exec("su");// (这里执行是系统已经开放了root权限,而不是说通过执行这句来获得root权限)
DataOutputStream os = new DataOutputStream(process.getOutputStream());
// os.writeBytes("ifconfig eth0 192.168.18.122\n");
os.writeBytes("exit\n");
os.flush();
/*
* //如果已经root,但是用户选择拒绝授权,e.getMessage() = write failed: EPIPE (Broken pipe)
//如果没有root,,e.getMessage()= Error running exec(). Command: [su] Working Directory: null Environment: null
*/
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}