如何在程序中设置 Android 的 IP、DNS 和网关?

本文转自:http://www.oschina.net/question/163910_26207

该方法适用于android2.3版本,4.0不得行

首先设置权限

<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>

设置的代码如下

import android.provider.Settings;

Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_USE_STATIC_IP, "0");
Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_DNS1, "192.168.0.2");
Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_DNS2, "192.168.0.3");
Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_GATEWAY, "192.168.0.1");
Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_NETMASK, "255.255.255.0");
Settings.System.putString(getContentResolver(), android.provider.Settings.System.WIFI_STATIC_IP, "1");

读取配置代码如下,原文中代码有误,应该是下面的写法

String statdns1 = Settings.System.getString(getContentResolver(), Settings.System.WIFI_STATIC_DNS1);
		
String statdns2 = Settings.System.getString(getContentResolver(), Settings.System.WIFI_STATIC_DNS2);
				
String sgateway = Settings.System.getString(getContentResolver(), Settings.System.WIFI_STATIC_GATEWAY);
				
String staticip = Settings.System.getString(getContentResolver(), Settings.System.WIFI_STATIC_IP);
				
String snetmask = Settings.System.getString(getContentResolver(), Settings.System.WIFI_STATIC_NETMASK);
				
String staticus = Settings.System.getString(getContentResolver(), Settings.System.WIFI_USE_STATIC_IP);

用putString配置,用getString读取,详情可以看 http://developer.android.com/reference/android/provider/Settings.System.html

你可能感兴趣的:(如何在程序中设置 Android 的 IP、DNS 和网关?)