问题
I have my glass paired by bluetooth with my mobile. My mobile is connected to a WiFi network (and my glass isn't connected to WiFi, it uses the WiFi of my mobile).
I know I can get IP local ip addres with this code:
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipAddress = Formatter.formatIpAddress(ip);
It's work OK if i run this code in a tablet o smartphone, but if i run it in my glass i get ip 0.0.0.0 ( remeber that my glass is connected by bluetooth to my mobile and this one is which has network connection).
So, any suggestions? I need this because i have a Socket in my glass and i need the IP.
Thanks!
回答1:
The code can now be called by any activity
public String getIP(){
WifiManager wifiMgr = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipAddress = Formatter.formatIpAddress(ip);
}
To anyone who is interested. The above code DID work for me in an Activity. Try:
Toast toast = Toast.makeText(this,
"IP Address:\n\r"+getIP(this), Toast.LENGTH_LONG);
toast.show();
Perhaps your UI isn't updating, or print it to the log. Another possibility is that you need to add the following to your manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
Not sure if you need both, but I need both for my application as I do a lot of networking which it sounds like you are too.
来源:https://stackoverflow.com/questions/23559244/how-can-i-get-ip-of-my-glass-when-it-is-connected-by-bluetooth-to-my-mobile