利用WifiManager取得IP
AndroidManifest.xml需要加入
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="johnson.layout" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Layout_testActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Java部份:
import android.app.Activity; import android.net.wifi.WifiManager; import android.net.wifi.WifiInfo; import android.os.Bundle; import android.widget.TextView; public class test extends Activity { TextView ans = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ans = (TextView) findViewById( R.id.ans ); ans.setText("IP:" + getMyIp() ); } //取得IP private String getMyIp(){ //新增一個WifiManager物件並取得WIFI_SERVICE WifiManager wifi_service = (WifiManager)getSystemService(WIFI_SERVICE); //取得wifi資訊 WifiInfo wifiInfo = wifi_service.getConnectionInfo(); //取得IP,但這會是一個詭異的數字,還要再自己換算才行 int ipAddress = wifiInfo.getIpAddress(); //利用位移運算和AND運算計算IP String ip = String.format("%d.%d.%d.%d",(ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff)); return ip; } }