Wi-Fi開啟、偵測、連線、中斷、IP轉換

1.首先要在AndroidManifest.xml加入Wi-Fi讀取權限與更改Wi-Fi權限 :
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
2.接下來就是在程式端(.java)控制Wi-Fi的設定囉 :
P.S.小黑人在這裡放置3個按鈕,分別是”Wi-Fi偵測”,”Wi-Fi連線”,”Wi-Fi斷線” :
//首先取得Wi-Fi服務控制Manager
WifiManager mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
※ Wi-Fi偵測 :
//先判斷是否有開啟Wi-Fi,有開啟則回傳true沒有則回傳false
if(mWifiManager.isWifiEnabled())
{
//重新掃描Wi-Fi資訊
mWifiManager.startScan();
//偵測周圍的Wi-Fi環境(因為會有很多組Wi-Fi,所以型態為List)
mWifiScanResultList = mWifiManager.getScanResults();
//手機內已存的Wi-Fi資訊(因為會有很多組Wi-Fi,所以型態為List)
mWifiConfigurationList = mWifiManager.getConfiguredNetworks();
//目前已連線的Wi-Fi資訊
mWifiInfo = mWifiManager.getConnectionInfo();

for(int i = 0 ; i < mWifiScanResultList.size() ; i++ )
{
//手機目前周圍的Wi-Fi環境
SSID (Wi-Fi名稱) = mWifiScanResultList.get(i).SSID ;
LEVEL (Wi-Fi訊號強弱) = mWifiScanResultList.get(i).level) ;
}

for(int i = 0 ; i < mWifiConfigurationList.size() ; i++ )
{
//手機內已儲存(已連線過)的Wi-Fi資訊
SSID (Wi-Fi名稱) = mWifiConfigurationList.get(i).SSID ;
NETWORKID (Wi-Fi連線ID) = mWifiConfigurationList.get(i).networkId ;
}

//目前手機已連線(現在連線)的Wi-Fi資訊
SSID (Wi-Fi名稱) = mWifiInfo.getSSID() ;
NETWORKID (Wi-Fi連線ID) = mWifiInfo.getNetworkId() ;
IPADRRESS (Wi-Fi連線位置) = mWifiInfo.getIpAddress() ;
IP (Wi-Fi IP位置) = String.format(“%d.%d.%d.%d”, (IPADRRESS & 0xff), (IPADRRESS >> 8 & 0xff), (IPADRRESS >> 16 & 0xff),( IPADRRESS >> 24 & 0xff)) ;
}
else
{
//把Wi-Fi開啟
mWifiManager.setWifiEnabled(true);
Toast.makeText(MainActivity.this, “Wi-Fi開啟中”, Toast.LENGTH_SHORT).show();
}

※ Wi-Fi連線 :
//選擇欲連線的Wi-Fi ID帶入即可進行連線
int NETWORKID = 已連線過的Wi-Fi ID ;
mWifiManager.enableNetwork(NETWORKID,true);

※ Wi-Fi中斷 :
//中斷目前的Wi-Fi連線訊號
mWifiManager.disconnect();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s