JavaShuo
欄目
標籤
Android Wifi IP 設置
時間 2019-11-18
標籤
android
wifi
設置
欄目
Android
简体版
原文
原文鏈接
android
string
exception
null
object
dialog
[java]
view plain
copy
<EMBED id=ZeroClipboardMovie_1 height=18 name=ZeroClipboardMovie_1 type=application/x-shockwave-flash align=middle pluginspage=http://www.macromedia.com/go/getflashplayer width=18 src=http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf wmode="transparent" flashvars="id=1&width=18&height=18" allowfullscreen="false" allowscriptaccess="always" bgcolor="#ffffff" quality="best" menu="false" loop="false">
import
java.lang.reflect.Constructor;
import
java.lang.reflect.Field;
import
java.lang.reflect.InvocationTargetException;
import
java.net.InetAddress;
import
java.util.ArrayList;
import
java.util.List;
import
android.app.Activity;
import
android.app.AlertDialog;
import
android.content.BroadcastReceiver;
import
android.content.Context;
import
android.content.DialogInterface;
import
android.content.IntentFilter;
import
android.net.wifi.ScanResult;
import
android.net.wifi.WifiConfiguration;
import
android.net.wifi.WifiManager;
import
android.net.wifi.p2p.WifiP2pManager;
import
android.net.wifi.p2p.WifiP2pManager.Channel;
import
android.os.Bundle;
import
android.text.TextUtils;
import
android.view.LayoutInflater;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.EditText;
import
android.widget.ImageButton;
import
android.widget.ListView;
import
android.widget.Toast;
public
class
WifiActivity
extends
Activity
implements
OnClickListener{
protected
static
final
String TAG =
"WifiActivity"
;
public
final
static
String KEY_WIFI_PRIORITY =
"wifi_priority"
;
public
final
static
String KEY_WIFI_STATIC_IP =
"wifi_static_ip"
;
WifiP2pManager mManager;
Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
private
WifiManager mWifiManager;
private
List<ScanResult> mListResult;
private
WifiAdapter mWifiAdapter;
private
ListView mList;
/** Called when the activity is first created. */
@Override
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.wifi_list);
ImageButton btn = (ImageButton)findViewById(R.id.back);
btn.setOnClickListener(
this
);
mList = (ListView)findViewById(R.id.list_view);
mReceiver =
new
WifiReceiver(
new
WifiScanListener() {
@Override
public
void
suppStateChange() {
}
@Override
public
void
stateChange() {
}
@Override
public
void
endScan() {
endScanWifi(mWifiManager.getScanResults());
}
});
mIntentFilter =
new
IntentFilter();
mIntentFilter.addAction(
"android.net.wifi.WIFI_STATE_CHANGED"
);
mIntentFilter.addAction(
"android.net.wifi.SCAN_RESULTS"
);
mIntentFilter.addAction(
"android.net.wifi.supplicant.STATE_CHANGE"
);
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mWifiManager.setWifiEnabled(
true
);
mWifiAdapter =
new
WifiAdapter(
this
,
null
);
mList.setAdapter(mWifiAdapter);
}
// void showLog(String msg) {
// new AlertDialog.Builder(this).setTitle(R.string.alert_dialog_prompt).setMessage(msg).show();
// }
void
promptMessage(String msg) {
Toast.makeText(
this
, msg, Toast.LENGTH_LONG).show();
}
public
void
showEditWifi(
final
ScanResult sr){
LayoutInflater factory = LayoutInflater.from(
this
);
final
View textEntryView = factory.inflate(R.layout.dialog_wifi_setting,
null
);
new
AlertDialog.Builder(
this
).setIconAttribute(android.R.attr.dialogIcon).setTitle(sr.SSID).setView(textEntryView).setCancelable(
false
)
.setPositiveButton(R.string.alert_dialog_ok,
new
DialogInterface.OnClickListener() {
public
void
onClick(DialogInterface dialog,
int
whichButton) {
try
{
EditText edtWifiPwd = (EditText) textEntryView.findViewById(R.id.edt_wifi_pwd);
EditText edtStaticIp = (EditText) textEntryView.findViewById(R.id.edt_static_ip);
EditText edtStaticGateway = (EditText) textEntryView.findViewById(R.id.edt_static_gateway);
EditText edtStaticNetmask = (EditText) textEntryView.findViewById(R.id.edt_static_netmask);
EditText edtStaticDns = (EditText) textEntryView.findViewById(R.id.edt_static_dns);
String wifiPwd = edtWifiPwd.getText().toString().trim();
String ip = edtStaticIp.getText().toString().trim();
String gateway = edtStaticGateway.getText().toString().trim();
String prefixLength = edtStaticNetmask.getText().toString().trim();
String dns = edtStaticDns.getText().toString().trim();
saveStaticWifiConfig(sr,wifiPwd,ip,Integer.parseInt(prefixLength));
}
catch
(IllegalArgumentException e) {
promptMessage(getString(R.string.system_wifi_ip_error));
}
catch
(Exception e) {
e.printStackTrace();
promptMessage(getString(R.string.system_wifi_setting_error));
}
}
}).setNegativeButton(R.string.alert_dialog_cancel,
new
DialogInterface.OnClickListener() {
public
void
onClick(DialogInterface dialog,
int
whichButton) {
dialog.cancel();
}
}).create().show();
try
{
WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);
EditText edtWifiPwd = (EditText) textEntryView.findViewById(R.id.edt_wifi_pwd);
EditText edtStaticIp = (EditText) textEntryView.findViewById(R.id.edt_static_ip);
EditText edtStaticGateway = (EditText) textEntryView.findViewById(R.id.edt_static_gateway);
EditText edtStaticNetmask = (EditText) textEntryView.findViewById(R.id.edt_static_netmask);
EditText edtStaticDns = (EditText) textEntryView.findViewById(R.id.edt_static_dns);
if
(historyWifiConfig !=
null
){
InetAddress address = getIpAddress(historyWifiConfig);
if
(address !=
null
){
edtStaticIp.setText(address.getHostAddress());
address =
null
;
}
address = getGateway(historyWifiConfig);
if
(address !=
null
){
edtStaticGateway.setText(address.getHostAddress());
address =
null
;
}
address = getDNS(historyWifiConfig);
if
(address !=
null
){
edtStaticDns.setText(address.getHostAddress());
address =
null
;
}
edtStaticNetmask.setText(getNetworkPrefixLength(historyWifiConfig));
}
if
(TextUtils.isEmpty(edtStaticIp.getText().toString().trim())){
String ipString = SmartHomePreference.getStringProperty(KEY_WIFI_STATIC_IP);
int
intIp = inetAddressToInt(InetAddress.getByName(ipString));
String dns = (intIp &
0xFF
) +
"."
+ ((intIp >>
8
) &
0xFF
) +
"."
+ ((intIp >>
16
) &
0xFF
) +
".1"
;
edtStaticIp.setText(ipString);
edtStaticNetmask.setText(
"24"
);
edtStaticGateway.setText(dns);
edtStaticDns.setText(dns);
}
}
catch
(Exception e) {
e.printStackTrace();
}
}
/**
* 設置wifi,編輯靜態IP
* @param sr
* @param pwd
* @param ip
* @throws Exception
*/
public
void
saveStaticWifiConfig(
final
ScanResult sr,String pwd, String ip,
int
networkPrefixLength)
throws
Exception{
InetAddress intetAddress = InetAddress.getByName(ip);
int
intIp = inetAddressToInt(intetAddress);
WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);
if
(historyWifiConfig ==
null
){
historyWifiConfig = createComWifiConfig(sr.SSID,pwd);
}
else
{
if
(!TextUtils.isEmpty(pwd)){
historyWifiConfig.preSharedKey =
"\""
+ pwd +
"\""
;
}
}
String dns = (intIp &
0xFF
) +
"."
+ ((intIp >>
8
) &
0xFF
) +
"."
+ ((intIp >>
16
) &
0xFF
) +
".1"
;
setIpAssignment(
"STATIC"
, historyWifiConfig);
//"STATIC" or "DHCP" for dynamic setting
setIpAddress(intetAddress, networkPrefixLength, historyWifiConfig);
setGateway(InetAddress.getByName(dns), historyWifiConfig);
setDNS(InetAddress.getByName(dns), historyWifiConfig);
mWifiManager.removeNetwork(historyWifiConfig.networkId);
int
netId = mWifiManager.addNetwork(historyWifiConfig);
mWifiManager.enableNetwork(netId,
true
);
mWifiManager.updateNetwork(historyWifiConfig);
//apply the setting
SmartHomePreference.setProperty(WifiActivity.KEY_WIFI_PRIORITY, sr.SSID);
mWifiManager.startScan();
}
/***
* Convert a IPv4 address from an InetAddress to an integer
* @param inetAddr is an InetAddress corresponding to the IPv4 address
* @return the IP address as an integer in network byte order
*/
public
static
int
inetAddressToInt(InetAddress inetAddr)
throws
IllegalArgumentException {
byte
[] addr = inetAddr.getAddress();
if
(addr.length !=
4
) {
throw
new
IllegalArgumentException(
"Not an IPv4 address"
);
}
return
((addr[
3
] &
0xff
) <<
24
) | ((addr[
2
] &
0xff
) <<
16
) |
((addr[
1
] &
0xff
) <<
8
) | (addr[
0
] &
0xff
);
}
public
void
editStaticWifiConfig(
final
ScanResult sr,String pwd, String ip, String gateway,
int
prefixLength,String dns)
throws
Exception{
WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);
if
(historyWifiConfig ==
null
){
historyWifiConfig = createComWifiConfig(sr.SSID,pwd);
int
netId = mWifiManager.addNetwork(historyWifiConfig);
mWifiManager.enableNetwork(netId,
true
);
}
setIpAssignment(
"STATIC"
, historyWifiConfig);
//"STATIC" or "DHCP" for dynamic setting
setIpAddress(InetAddress.getByName(ip), prefixLength, historyWifiConfig);
setGateway(InetAddress.getByName(gateway), historyWifiConfig);
setDNS(InetAddress.getByName(dns), historyWifiConfig);
mWifiManager.updateNetwork(historyWifiConfig);
//apply the setting
}
public
void
editDhcpWifiConfig(
final
ScanResult sr,String pwd)
throws
Exception{
WifiConfiguration historyWifiConfig = getHistoryWifiConfig(sr.SSID);
if
(historyWifiConfig ==
null
){
historyWifiConfig = createComWifiConfig(sr.SSID,pwd);
int
netId = mWifiManager.addNetwork(historyWifiConfig);
mWifiManager.enableNetwork(netId,
true
);
}
setIpAssignment(
"DHCP"
, historyWifiConfig);
//"STATIC" or "DHCP" for dynamic setting
mWifiManager.updateNetwork(historyWifiConfig);
//apply the setting
}
/**
* 新建wifi配置項
* @param ssid
* @param pwd
* @return
*/
public
WifiConfiguration createComWifiConfig(String ssid,String pwd){
WifiConfiguration wc =
new
WifiConfiguration();
wc.SSID =
"\""
+ ssid +
"\""
;
//配置wifi的SSID,即該熱點的名稱,如:TP-link_xxx
wc.preSharedKey =
"\""
+ pwd +
"\""
;
//該熱點的密碼
wc.hiddenSSID =
true
;
wc.status = WifiConfiguration.Status.ENABLED;
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
return
wc;
}
/**
* 查找已經設置好的Wifi
* @param ssid
* @return
*/
public
WifiConfiguration getHistoryWifiConfig(String ssid){
List<WifiConfiguration> localList = mWifiManager.getConfiguredNetworks();
for
(WifiConfiguration wc : localList){
if
((
"\""
+ ssid +
"\""
).equals(wc.SSID)){
return
wc;
}
mWifiManager.disableNetwork(wc.networkId);
}
return
null
;
}
public
static
void
setIpAssignment(String assign, WifiConfiguration wifiConf)
throws
SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException {
setEnumField(wifiConf, assign,
"ipAssignment"
);
}
public
static
void
setIpAddress(InetAddress addr,
int
prefixLength,WifiConfiguration wifiConf)
throws
SecurityException,IllegalArgumentException,
NoSuchFieldException,IllegalAccessException, NoSuchMethodException,ClassNotFoundException, InstantiationException,InvocationTargetException {
Object linkProperties = getField(wifiConf,
"linkProperties"
);
if
(linkProperties ==
null
)
return
;
Class laClass = Class.forName(
"android.net.LinkAddress"
);
Constructor laConstructor = laClass.getConstructor(
new
Class[] {InetAddress.
class
,
int
.
class
});
Object linkAddress = laConstructor.newInstance(addr, prefixLength);
ArrayList mLinkAddresses = (ArrayList) getDeclaredField(linkProperties,
"mLinkAddresses"
);
mLinkAddresses.clear();
mLinkAddresses.add(linkAddress);
}
public
static
void
setGateway(InetAddress gateway,WifiConfiguration wifiConf)
throws
SecurityException,IllegalArgumentException,
NoSuchFieldException,IllegalAccessException, ClassNotFoundException,NoSuchMethodException, InstantiationException,InvocationTargetException {
Object linkProperties = getField(wifiConf,
"linkProperties"
);
if
(linkProperties ==
null
)
return
;
Class routeInfoClass = Class.forName(
"android.net.RouteInfo"
);
Constructor routeInfoConstructor = routeInfoClass.getConstructor(
new
Class[] { InetAddress.
class
});
Object routeInfo = routeInfoConstructor.newInstance(gateway);
ArrayList mRoutes = (ArrayList) getDeclaredField(linkProperties,
"mRoutes"
);
mRoutes.clear();
mRoutes.add(routeInfo);
}
public
static
void
setDNS(InetAddress dns, WifiConfiguration wifiConf)
throws
SecurityException, IllegalArgumentException,NoSuchFieldException, IllegalAccessException {
Object linkProperties = getField(wifiConf,
"linkProperties"
);
if
(linkProperties ==
null
)
return
;
ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(linkProperties,
"mDnses"
);
mDnses.clear();
// or add a new dns address , here I just want to replace DNS1
mDnses.add(dns);
}
public
static
String getNetworkPrefixLength(WifiConfiguration wifiConf) {
String address =
""
;
try
{
Object linkProperties = getField(wifiConf,
"linkProperties"
);
if
(linkProperties ==
null
)
return
null
;
if
(linkProperties !=
null
){
ArrayList mLinkAddresses = (ArrayList) getDeclaredField(linkProperties,
"mLinkAddresses"
);
if
(mLinkAddresses !=
null
&& mLinkAddresses.size() >
0
){
Object linkAddressObj = mLinkAddresses.get(
0
);
address = linkAddressObj.getClass().getMethod(
"getNetworkPrefixLength"
,
new
Class[]{}).invoke(linkAddressObj,
null
) +
""
;
}
}
}
catch
(Exception e) {
e.printStackTrace();
}
return
address;
}
public
static
InetAddress getIpAddress(WifiConfiguration wifiConf) {
InetAddress address =
null
;
try
{
Object linkProperties = getField(wifiConf,
"linkProperties"
);
if
(linkProperties ==
null
)
return
null
;
if
(linkProperties !=
null
){
ArrayList mLinkAddresses = (ArrayList) getDeclaredField(linkProperties,
"mLinkAddresses"
);
if
(mLinkAddresses !=
null
&& mLinkAddresses.size() >
0
){
Object linkAddressObj = mLinkAddresses.get(
0
);
address = (InetAddress)linkAddressObj.getClass().getMethod(
"getAddress"
,
new
Class[]{}).invoke(linkAddressObj,
null
);
}
}
}
catch
(Exception e) {
e.printStackTrace();
}
return
address;
}
public
static
InetAddress getGateway(WifiConfiguration wifiConf) {
InetAddress address =
null
;
try
{
Object linkProperties = getField(wifiConf,
"linkProperties"
);
if
(linkProperties !=
null
){
ArrayList mRoutes = (ArrayList) getDeclaredField(linkProperties,
"mRoutes"
);
if
(mRoutes !=
null
&& mRoutes.size() >
0
){
Object linkAddressObj = mRoutes.get(
0
);
address = (InetAddress)linkAddressObj.getClass().getMethod(
"getGateway"
,
new
Class[]{}).invoke(linkAddressObj,
null
);
}
}
}
catch
(Exception e) {
e.printStackTrace();
}
return
address;
}
public
static
InetAddress getDNS(WifiConfiguration wifiConf) {
InetAddress address =
null
;
try
{
Object linkProperties = getField(wifiConf,
"linkProperties"
);
if
(linkProperties !=
null
){
ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>) getDeclaredField(linkProperties,
"mDnses"
);
if
(mDnses !=
null
&& mDnses.size() >
0
){
address = (InetAddress)mDnses.get(
0
);
}
}
}
catch
(Exception e) {
e.printStackTrace();
}
return
address;
}
public
static
Object getField(Object obj, String name)
throws
SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getField(name);
Object out = f.get(obj);
return
out;
}
public
static
Object getDeclaredField(Object obj, String name)
throws
SecurityException, NoSuchFieldException,IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getDeclaredField(name);
f.setAccessible(
true
);
Object out = f.get(obj);
return
out;
}
public
static
void
setEnumField(Object obj, String value, String name)
throws
SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field f = obj.getClass().getField(name);
f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value));
}
@Override
protected
void
onResume() {
super
.onResume();
registerReceiver(mReceiver, mIntentFilter);
if
(mWifiManager !=
null
) mWifiManager.startScan();
}
@Override
protected
void
onPause() {
super
.onPause();
unregisterReceiver(mReceiver);
}
@Override
public
void
onClick(View v) {
switch
(v.getId()) {
case
R.id.back:
// if(mWifiManager != null) mWifiManager.startScan();
finish();
break
;
default
:
break
;
}
}
public
void
endScanWifi(
final
List<ScanResult> list){
runOnUiThread(
new
Runnable() {
@Override
public
void
run() {
if
(mWifiAdapter !=
null
){
mWifiAdapter.setList(list);
mWifiAdapter.notifyDataSetChanged();
}
}
});
}
}
上一篇
迴音消除技術概述
下一篇
IP經常使用操做工具類
相關文章
1.
Android--WIFI--Mac--Ip
2.
Android: 設置wifi設備名
3.
android設置 默認wifi
4.
Mac 鏈接WIFI設置不一樣IP
5.
Mac 連接WIFI設置不同IP
6.
wifi 漫遊設置
7.
過濾Android系統設置中Wifi
8.
parallels設置centos7 ip
9.
Ubuntu14.04 設置wifi熱點
10.
WiFi共享設置
更多相關文章...
•
MySQL AS:設置別名
-
MySQL教程
•
Kotlin Android 環境搭建
-
Kotlin 教程
•
IntelliJ IDEA代碼格式化設置
•
IntelliJ IDEA 代碼格式化配置和快捷鍵
相關標籤/搜索
wifi
設置
ip&ip
設置分頁
wifi+sensors
wifi+gprs
8.1+wifi
wifi&bt
無線
Android
TCP/IP教程
網站建設指南
MyBatis教程
設計模式
0
分享到微博
分享到微信
分享到QQ
每日一句
每一个你不满意的现在,都有一个你没有努力的曾经。
最新文章
1.
如何將PPT某一頁幻燈片導出爲高清圖片
2.
Intellij IDEA中使用Debug調試
3.
build項目打包
4.
IDEA集成MAVEN項目極簡化打包部署
5.
eclipse如何導出java工程依賴的所有maven管理jar包(簡單明瞭)
6.
新建的Spring項目無法添加class,依賴下載失敗解決:Maven環境配置
7.
記在使用vue-cli中使用axios的心得
8.
分享提高自己作品UI設計形式感的幾個小技巧!
9.
造成 nginx 403 forbidden 的幾種原因
10.
AOP概述(什麼是AOP?)——Spring AOP(一)
本站公眾號
歡迎關注本站公眾號,獲取更多信息
相關文章
1.
Android--WIFI--Mac--Ip
2.
Android: 設置wifi設備名
3.
android設置 默認wifi
4.
Mac 鏈接WIFI設置不一樣IP
5.
Mac 連接WIFI設置不同IP
6.
wifi 漫遊設置
7.
過濾Android系統設置中Wifi
8.
parallels設置centos7 ip
9.
Ubuntu14.04 設置wifi熱點
10.
WiFi共享設置
>>更多相關文章<<