Android(安卓)用Shell命令设置静态ip
16lz
2022-05-18
源码下载 https://download.csdn.net/download/qq_31939617/10592340‘>
Android 用Shell命令设置静态ip,我的设备是4.3版本,带一个LAN口。这种方式应该要5.0以下的才行,具体没有测试过。
图拍得比较难看,还是上一看,看效果:
MainActivity.class
package com.example.sz.ip;import android.app.Activity;import android.app.ActivityManager;import android.content.BroadcastReceiver;import android.content.ContentProvider;import android.content.ContentResolver;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.IntentFilter;import android.graphics.Bitmap;import android.os.Bundle;import android.provider.Settings;import android.util.Log;import android.view.View;import android.webkit.JsResult;import android.webkit.WebChromeClient;import android.webkit.WebSettings;import android.webkit.WebView;import android.webkit.WebViewClient;import android.widget.Button;import android.widget.EditText;import android.widget.RadioButton;import android.widget.RadioGroup;import android.widget.Toast;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import butterknife.BindView;import butterknife.ButterKnife;import butterknife.OnClick;public class MainActivity extends Activity //implements View.OnClickListener{ private static final String TAG = "MainActivity"; @BindView(R.id.et_ip) EditText mIp; @BindView(R.id.et_mask) EditText mMask; @BindView(R.id.et_gw) EditText mGw; @BindView(R.id.et_dns0) EditText mDns0; @BindView(R.id.et_dns1) EditText mDns1; @BindView(R.id.rb_dech) RadioButton mDech; @BindView(R.id.rb_static) RadioButton mStatic; @BindView(R.id.rb_automaticv_dns) RadioButton mAutomaticv; @BindView(R.id.rb_manual_dns) RadioButton mManual; @BindView(R.id.rg_ip) RadioGroup mRgIp; @BindView(R.id.rg_dns) RadioGroup mRgDns; @BindView(R.id.confrim) Button mConfrim; @BindView(R.id.hao123) Button mHao123; @BindView(R.id.webview) WebView webView; private String ip, mask, gw, dns0, dns1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mDech.setChecked(true); mAutomaticv.setChecked(true); } @OnClick({R.id.confrim, R.id.hao123}) public void onClick(View view) { switch (view.getId()) { case R.id.confrim://// String s = et.getText().toString().trim();//// Intent intent = new Intent("static_ip");// //静态ip地址// intent.putExtra("ipAdd", s);// //默认网关// intent.putExtra("gw", "192.168.1.1");// //子网掩码// intent.putExtra("mask", "255.255.255.0");// intent.putExtra("dns1", "8.8.8.8");// intent.putExtra("dns2", "192.168.1.1");//// sendBroadcast(intent);//// Log.e(TAG, "onClick: --------------------btn_static------------"+s); if (mStatic.isChecked()) { ip = mIp.getText().toString().trim(); mask = mMask.getText().toString().trim(); gw = mGw.getText().toString().trim(); } if (mManual.isChecked()) { dns0 = mDns0.getText().toString().trim(); dns1 = mDns1.getText().toString().trim(); } ShellUtils mShellUtils = new ShellUtils(); //ip,子网掩码 //mShellUtils.execCommand("ifconfig eth0 192.168.1.222 netmask 255.255.255.0 ",true,true); //mShellUtils.execCommand("route add default gw 192.168.1.1 dev eth0", true, true); //mShellUtils.execCommand("setprop net.eth0.dns1 202.96.134.33 ", true, true); //mShellUtils.execCommand("setprop net.eth0.dns1 202.96.128.86 ", true, true); String s = "ifconfig eth0 " + ip + " netmask " + mask + " \""; Log.e(TAG, "onClick: ----------------------" + s); mShellUtils.execCommand("ifconfig eth0 " + ip + " netmask " + mask, true, true); //网关 mShellUtils.execCommand("route add default gw " + gw + " dev eth0" , true, true); //DNS //mShellUtils.execCommand("echo nameserver 202.96.134.33 etcresolv.conf " ,true,true); mShellUtils.execCommand("setprop net.eth0.dns0 " + dns0, true, true); mShellUtils.execCommand("setprop net.eth0.dns1 " + dns1, true, true); break; case R.id.hao123: initWeb(); break; default: break; } } public void initWeb() { WebSettings setting = webView.getSettings(); setting.setJavaScriptEnabled(true);//让webview支持javascript webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//设置允许js弹出alert对话框 setting.setDefaultTextEncodingName("utf-8");//设置字符集 //setting.setBlockNetworkImage(true);//设置不能访问网络图片 setting.setSupportZoom(true);//开启网页的缩放 setting.setBuiltInZoomControls(true); setting.setLoadWithOverviewMode(true);//设置网页缩放至手机大小 setting.setUseWideViewPort(true); webView.getSettings().setJavaScriptEnabled(true);//让webview支持javascript webView.setWebChromeClient(new WebChromeClient());//支持特殊javascript // mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); // mWebView.setBackgroundColor(Color.parseColor("#000000")); //load本地 // mWebView.loadUrl("file:///android_asset/hellotest.html"); //load在线 //mWebView.loadUrl("http://www.google.com"); // mWebView.loadUrl(url); //js访问android,定义接口 //webView.addJavascriptInterface(new JsInteration(), "control"); //设置了Alert才会弹出,重新onJsAlert()方法return true可以自定义处理信息 webView.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { //return super.onJsAlert(view, url, message, result); return true; } }); //所有的请求在本地webview打开 webView.setWebViewClient(new WebViewClient() { /* @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return super.shouldOverrideUrlLoading(view, request); // view.loadUrl(url); //return true; //请求连接 } */ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); //开始加载连接 // dialog.show(); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); //mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); //禁止硬件加速 //加载结束 // dialog.dismiss(); } }); webView.loadUrl("http://www.hao123.com"); } //gu /* public class IPReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { android.util.Log.e(TAG, "onReceive: --------------------static_ip-------------------------"); //静态ip地址 *//* String ip = intent.getStringExtra("ipAdd"); //默认网关 String mask = intent.getStringExtra("gw"); //子网掩码 String dns = intent.getStringExtra("newMask"); String gw = intent.getStringExtra("dns1"); String name = intent.getStringExtra("dns2"); } }*/}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#030303" android:orientation="vertical" tools:context=".MainActivity"> <RadioGroup android:id="@+id/rg_ip" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginLeft="20dp" android:layout_marginTop="10dp" android:gravity="center" android:orientation="horizontal"> <RadioButton android:id="@+id/rb_dech" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:button="@null" android:drawableLeft="@android:drawable/btn_radio" android:drawablePadding="20dp" android:text="自动获取" android:textColor="#eeeeee" android:textSize="16sp" /> <RadioButton android:id="@+id/rb_static" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:background="@null" android:button="@null" android:drawableLeft="@android:drawable/btn_radio" android:drawablePadding="10dp" android:text="手动分配" android:textColor="#eeeeee" android:textSize="16sp" /> RadioGroup> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:text=" IP 地址 " android:textColor="#eeeeee" android:textSize="16sp"/> <EditText android:id="@+id/et_ip" android:layout_width="260dp" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:background="@drawable/shape_input" android:ellipsize="end" android:maxHeight="16sp" android:paddingLeft="10dp" android:paddingRight="20dp" android:singleLine="true" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#eeeeee" /> LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:text="子网掩码" android:textColor="#eeeeee" android:textSize="16sp" /> <EditText android:id="@+id/et_mask" android:layout_width="260dp" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:background="@drawable/shape_input" android:ellipsize="end" android:maxHeight="16sp" android:paddingLeft="10dp" android:paddingRight="20dp" android:singleLine="true" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#eeeeee" /> LinearLayout> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:text="默认网关" android:textColor="#eeeeee" android:textSize="16sp" /> <EditText android:id="@+id/et_gw" android:layout_width="260dp" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:background="@drawable/shape_input" android:ellipsize="end" android:maxHeight="16sp" android:paddingLeft="10dp" android:paddingRight="20dp" android:singleLine="true" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#eeeeee" /> LinearLayout> <RadioGroup android:id="@+id/rg_dns" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_marginLeft="20dp" android:layout_marginTop="10dp" android:gravity="center" android:orientation="horizontal"> <RadioButton android:id="@+id/rb_automaticv_dns" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:button="@null" android:drawableLeft="@android:drawable/btn_radio" android:drawablePadding="10dp" android:text="自动获取DNS服务器地址" android:textColor="#eeeeee" android:textSize="16sp" /> <RadioButton android:id="@+id/rb_manual_dns" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:button="@null" android:drawableLeft="@android:drawable/btn_radio" android:drawablePadding="10dp" android:text="使用下面DNS服务器地址" android:textColor="#eeeeee" android:textSize="16sp" /> RadioGroup> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:text="首选DNS" android:textColor="#eeeeee" android:textSize="16sp" /> <EditText android:id="@+id/et_dns0" android:layout_width="260dp" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:background="@drawable/shape_input" android:ellipsize="end" android:maxHeight="16sp" android:paddingLeft="10dp" android:paddingRight="20dp" android:singleLine="true" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#eeeeee" /> LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:text="备用DNS" android:textColor="#eeeeee" android:textSize="16sp" /> <EditText android:id="@+id/et_dns1" android:layout_width="260dp" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:background="@drawable/shape_input" android:ellipsize="end" android:maxHeight="16sp" android:paddingLeft="10dp" android:paddingRight="20dp" android:singleLine="true" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="#eeeeee" /> LinearLayout> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <Button android:id="@+id/confrim" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="确定"/> <Button android:id="@+id/hao123" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:text="hao123"/> LinearLayout> <WebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent">WebView>LinearLayout>
ShellUtils.class
package com.example.sz.ip;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.List;public class ShellUtils { public static final String COMMAND_SU = "su"; public static final String COMMAND_SH = "sh"; public static final String COMMAND_EXIT = "exit\n"; public static final String COMMAND_LINE_END = "\n"; //这一段看个人情况,我不需要 /*public ShellUtils() { throw new AssertionError(); }*/ /** * 查看是否有了root权限 * * @return */ public static boolean checkRootPermission() { return execCommand("echo root", true, false).result == 0; } /** * 执行shell命令,默认返回结果 * * @param command * command * @param * //运行是否需要root权限 * @return * @see ShellUtils#execCommand(String[], boolean, boolean) */ public static CommandResult execCommand(String command, boolean isRoot) { return execCommand(new String[] { command }, isRoot, true); } /** * 执行shell命令,默认返回结果 * * @param commands * command list * @param * //运行是否需要root权限 * @return * @see ShellUtils#execCommand(String[], boolean, boolean) */ public static CommandResult execCommand(List commands, boolean isRoot) { return execCommand( commands == null ? null : commands.toArray(new String[] {}), isRoot, true); } /** * 执行shell命令,默认返回结果 * * @param commands * command array * @param * //运行是否需要root权限 * @return * @see ShellUtils#execCommand(String[], boolean, boolean) */ public static CommandResult execCommand(String[] commands, boolean isRoot) { return execCommand(commands, isRoot, true); } /** * execute shell command * * @param command * command * @param * //运行是否需要root权限 * @param isNeedResultMsg * whether need result msg * @return * @see ShellUtils#execCommand(String[], boolean, boolean) */ public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) { return execCommand(new String[] { command }, isRoot, isNeedResultMsg); } /** * execute shell commands * * @param commands * command list * @param * //运行是否需要root权限 * @param * //是否需要返回运行结果 * @return * @see ShellUtils#execCommand(String[], boolean, boolean) */ public static CommandResult execCommand(List commands, boolean isRoot, boolean isNeedResultMsg) { return execCommand( commands == null ? null : commands.toArray(new String[] {}), isRoot, isNeedResultMsg); } /** * execute shell commands * * @param commands * command array * @param * //运行是否需要root权限 * @param * //是否需要返回运行结果 * @return * - if isNeedResultMsg is false, {@link CommandResult#successMsg} * is null and {@link CommandResult#errorMsg} is null.
* - if {@link CommandResult#result} is -1, there maybe some * excepiton.
*
*/ public static CommandResult execCommand(String[] commands, boolean isRoot, boolean isNeedResultMsg) { int result = -1; if (commands == null || commands.length == 0) { return new CommandResult(result, null, null); } Process process = null; BufferedReader successResult = null; BufferedReader errorResult = null; StringBuilder successMsg = null; StringBuilder errorMsg = null; DataOutputStream os = null; try { process = Runtime.getRuntime().exec( isRoot ? COMMAND_SU : COMMAND_SH); os = new DataOutputStream(process.getOutputStream()); for (String command : commands) { if (command == null) { continue; } // donnot use os.writeBytes(commmand), avoid chinese charset // error os.write(command.getBytes()); os.writeBytes(COMMAND_LINE_END); os.flush(); } os.writeBytes(COMMAND_EXIT); os.flush(); result = process.waitFor(); // get command result if (isNeedResultMsg) { successMsg = new StringBuilder(); errorMsg = new StringBuilder(); successResult = new BufferedReader(new InputStreamReader( process.getInputStream())); errorResult = new BufferedReader(new InputStreamReader( process.getErrorStream())); String s; while ((s = successResult.readLine()) != null) { successMsg.append(s); } while ((s = errorResult.readLine()) != null) { errorMsg.append(s); } } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (os != null) { os.close(); } if (successResult != null) { successResult.close(); } if (errorResult != null) { errorResult.close(); } } catch (IOException e) { e.printStackTrace(); } if (process != null) { process.destroy(); } } return new CommandResult(result, successMsg == null ? null : successMsg.toString(), errorMsg == null ? null : errorMsg.toString()); } /** * 运行结果 * * - {@link CommandResult#result} means result of command, 0 means normal, * else means error, same to excute in linux shell
* - {@link CommandResult#successMsg} means success message of command * result
* - {@link CommandResult#errorMsg} means error message of command result
*
* * @author Trinea * 2013-5-16 */ public static class CommandResult { /** 运行结果 **/ public int result; /** 运行成功结果 **/ public String successMsg; /** 运行失败结果 **/ public String errorMsg; public CommandResult(int result) { this.result = result; } public CommandResult(int result, String successMsg, String errorMsg) { this.result = result; this.successMsg = successMsg; this.errorMsg = errorMsg; } }}
源码下载 https://download.csdn.net/download/qq_31939617/10592340‘>
更多相关文章
- Android(安卓)编译环境配置搭建(Ubuntu 12.04)及环境导致编译错
- Android通知
- 第一讲:Android开发环境的搭建
- android中视频播放的处理
- android对象池之Message
- ubuntu 64位 无法安装android SDK解决办法
- 拥抱Android:编译nodejs搭建移动平台
- Android(安卓)AES加密算法及其实现
- 配置flutter --Android(安卓)license status unknown.sdk 没有to