在Android应用程序中设置以太网连接

时间:2014-11-25 14:46:57

标签: android static ip ethernet gateway

在尝试为在Jellybean上运行的Android设备提供以太网连接时, 我使用ifconfig和route命令来设置以太网连接。 现在我尝试从Android应用程序执行这些命令,但无法设置IP和网关地址。 有没有其他方法来执行这些命令? 我使用了以下代码,

public void root_command(String cmd)
{
try{
      Process p=Runtime.getRuntime().exec("su");
      DataOutputStream  stream=new DataOutputStream(p.getOutputStream());
      stream.writeBytes(cmd);
      stream.writeBytes("exit \n");
      p.waitFor();
}
catch(IOException e)
{
}
catch(InterruptedException e)
{
}

}

这些是命令,

                 busybox ifconfig eth0 <ip_address> up
                 busybox route add default gw <gateway_address> eth0

1 个答案:

答案 0 :(得分:0)

使用它:

 Read.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String[] returncommand = new String[8];
            returncommand=read_file(filename);
            line1.setText(returncommand[0]);
            line2.setText(returncommand[1]);
            line3.setText(returncommand[2]);

            String[] mycommand = {"ifconfig eth0" + " " + returncommand[0] + " " + "netmask" + " " + returncommand[1] + " ", "netcfg eth0 up",
                    "route add default gw" + " " + returncommand[2] + " " + "dev eth0"};
            if (returncommand[0] != null & returncommand[1] != null & returncommand[2] != null)
                RunasRoot(mycommand);

        }
    });
}

public void RunasRoot(String[] cmds) {
    try {
        java.lang.Process process = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(process.getOutputStream());
        for (String tmpcmd : cmds) {
            outputStream.writeBytes(tmpcmd + "\n");
        }
        outputStream.writeBytes("exit\n");
        outputStream.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }