2010年4月24日 星期六

如何取得無線ip

如何使用WifiInfo 來取得無線網卡的IP位置

...前面省略
WifiManager wifiManager;
WifiInfo wifiInfo;
EditText txtInfo;
String strAddress;

@Override

Public void onCreate(Bundle saveInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

try {

wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
//完成了這裏會出現第一個錯誤,錯誤的內容忘了,但是要加下列的東東
strAddress = new Integer(ipAddress).toString();

//將資訊放入EditText就可以了
textInfo.setText(strAddress.toString());

} catch {
Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
Log.d(e.getMessage().toString(),"訊息");
}
}

完成上述的程式之後,其實一直都沒有辨法成功的執行程式,e.getMessage()是後來才加入。
也是在加入之後出現了錯誤訊息

neither user 10025 nor current process has android.permission.ACCESS_WIFI_STATE

谷了一下才知道原來是沒有開啟 WIFI狀態的讀取權限
就開啟了 AndroidManifest.xml 並加入了權限宣告

<application>
</application>
<uses-permission name="android.permission.ACCESS_WIFI_STATE" />

需注意的是要加在application 的外層。如果誤加在application內層會無法動作

沒有留言:

張貼留言