List of usage examples for android.net.wifi WifiManager getConnectionInfo
public WifiInfo getConnectionInfo()
From source file:eu.intermodalics.tango_ros_streamer.activities.RunningActivity.java
/** * This function initializes the tango ros node with RosJava interface. *//*from w ww .j a va 2 s. co m*/ private void initAndStartRosJavaNode() { this.nodeMainExecutorService.addListener(new NodeMainExecutorServiceListener() { @Override public void onShutdown(NodeMainExecutorService nodeMainExecutorService) { unbindFromTango(); mLogger.saveLogToFile(); // This ensures to kill the process started by the app. android.os.Process.killProcess(android.os.Process.myPid()); } }); if (mRunLocalMaster) { try { this.nodeMainExecutorService.startMaster(/*isPrivate*/ false); mMasterUri = this.nodeMainExecutorService.getMasterUri().toString(); // The URI returned by getMasterUri is correct but looks 'weird', // e.g. 'http://android-c90553518bc67cf5:1131'. // Instead of showing this to the user, we show the IP address of the device, // which is also correct and less confusing. WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); String deviceIP = Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress()); mUriTextView = (TextView) findViewById(R.id.master_uri); mUriTextView.setText("http://" + deviceIP + ":11311"); } catch (RosRuntimeException e) { e.printStackTrace(); Log.e(TAG, getString(R.string.local_master_error)); displayToastMessage(R.string.local_master_error); return; } } if (mMasterUri != null) { URI masterUri; try { masterUri = URI.create(mMasterUri); } catch (IllegalArgumentException e) { Log.e(TAG, "Wrong URI: " + e.getMessage()); return; } this.nodeMainExecutorService.setMasterUri(masterUri); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { RunningActivity.this.init(nodeMainExecutorService); return null; } }.execute(); } else { Log.e(TAG, "Master URI is null"); } }
From source file:org.deviceconnect.android.message.DevicePluginContext.java
/** * ??IP????./*from w w w. j a v a 2 s. c o m*/ * * @return IP */ private String getCurrentIPAddress() { Context appContext = getContext().getApplicationContext(); int state = ContextCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_WIFI_STATE); if (state != PackageManager.PERMISSION_GRANTED) { return null; } // TODO IPv6 ????? // TODO Wi-Fi ??????? WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); return String.format(Locale.getDefault(), "%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)); } return null; }
From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java
/** Called when the activity is first created. */ @Override/* w w w . j a v a2 s. c o m*/ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); fixScreenOrientation(); DoCommand dc = new DoCommand(getApplication()); Log.i("SUTAgentAndroid", dc.prgVersion); dc.FixDataLocalPermissions(); // Get configuration settings from "ini" file File dir = getFilesDir(); File iniFile = new File(dir, "SUTAgent.ini"); String sIniFile = iniFile.getAbsolutePath(); String lc = dc.GetIniData("General", "LogCommands", sIniFile); if (lc != "" && Integer.parseInt(lc) == 1) { SUTAgentAndroid.LogCommands = true; } SUTAgentAndroid.RegSvrIPAddr = dc.GetIniData("Registration Server", "IPAddr", sIniFile); SUTAgentAndroid.RegSvrIPPort = dc.GetIniData("Registration Server", "PORT", sIniFile); SUTAgentAndroid.HardwareID = dc.GetIniData("Registration Server", "HARDWARE", sIniFile); SUTAgentAndroid.Pool = dc.GetIniData("Registration Server", "POOL", sIniFile); SUTAgentAndroid.sTestRoot = dc.GetIniData("Device", "TestRoot", sIniFile); SUTAgentAndroid.Abi = android.os.Build.CPU_ABI; log(dc, "onCreate"); dc.SetTestRoot(SUTAgentAndroid.sTestRoot); Log.i("SUTAgentAndroid", "Test Root: " + SUTAgentAndroid.sTestRoot); tv = (TextView) this.findViewById(R.id.Textview01); if (getLocalIpAddress() == null) setUpNetwork(sIniFile); String macAddress = "Unknown"; if (android.os.Build.VERSION.SDK_INT > 8) { try { NetworkInterface iface = NetworkInterface .getByInetAddress(InetAddress.getAllByName(getLocalIpAddress())[0]); if (iface != null) { byte[] mac = iface.getHardwareAddress(); if (mac != null) { StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); for (int i = 0; i < mac.length; i++) { f.format("%02x%s", mac[i], (i < mac.length - 1) ? ":" : ""); } macAddress = sUniqueID = sb.toString(); } } } catch (UnknownHostException ex) { } catch (SocketException ex) { } } else { // Fall back to getting info from wifiman on older versions of Android, // which don't support the NetworkInterface interface WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (wifiMan != null) { WifiInfo wifi = wifiMan.getConnectionInfo(); if (wifi != null) macAddress = wifi.getMacAddress(); if (macAddress != null) sUniqueID = macAddress; } } if (sUniqueID == null) { BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter(); if ((ba != null) && (ba.isEnabled() != true)) { ba.enable(); while (ba.getState() != BluetoothAdapter.STATE_ON) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } sUniqueID = ba.getAddress(); ba.disable(); while (ba.getState() != BluetoothAdapter.STATE_OFF) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } else { if (ba != null) { sUniqueID = ba.getAddress(); sUniqueID.toLowerCase(); } } } if (sUniqueID == null) { TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); if (mTelephonyMgr != null) { sUniqueID = mTelephonyMgr.getDeviceId(); if (sUniqueID == null) { sUniqueID = "0011223344556677"; } } } String hwid = getHWID(this); sLocalIPAddr = getLocalIpAddress(); Toast.makeText(getApplication().getApplicationContext(), "SUTAgent [" + sLocalIPAddr + "] ...", Toast.LENGTH_LONG).show(); String sConfig = dc.prgVersion + lineSep; sConfig += "Test Root: " + sTestRoot + lineSep; sConfig += "Unique ID: " + sUniqueID + lineSep; sConfig += "HWID: " + hwid + lineSep; sConfig += "ABI: " + Abi + lineSep; sConfig += "OS Info" + lineSep; sConfig += "\t" + dc.GetOSInfo() + lineSep; sConfig += "Screen Info" + lineSep; int[] xy = dc.GetScreenXY(); sConfig += "\t Width: " + xy[0] + lineSep; sConfig += "\t Height: " + xy[1] + lineSep; sConfig += "Memory Info" + lineSep; sConfig += "\t" + dc.GetMemoryInfo() + lineSep; sConfig += "Network Info" + lineSep; sConfig += "\tMac Address: " + macAddress + lineSep; sConfig += "\tIP Address: " + sLocalIPAddr + lineSep; displayStatus(sConfig); sRegString = "NAME=" + sUniqueID; sRegString += "&IPADDR=" + sLocalIPAddr; sRegString += "&CMDPORT=" + 20701; sRegString += "&DATAPORT=" + 20700; sRegString += "&OS=Android-" + dc.GetOSInfo(); sRegString += "&SCRNWIDTH=" + xy[0]; sRegString += "&SCRNHEIGHT=" + xy[1]; sRegString += "&BPP=8"; sRegString += "&MEMORY=" + dc.GetMemoryConfig(); sRegString += "&HARDWARE=" + HardwareID; sRegString += "&POOL=" + Pool; sRegString += "&ABI=" + Abi; String sTemp = Uri.encode(sRegString, "=&"); sRegString = "register " + sTemp; pruneCommandLog(dc.GetSystemTime(), dc.GetTestRoot()); if (!bNetworkingStarted) { Thread thread = new Thread(null, doStartService, "StartServiceBkgnd"); thread.start(); bNetworkingStarted = true; Thread thread2 = new Thread(null, doRegisterDevice, "RegisterDeviceBkgnd"); thread2.start(); } monitorBatteryState(); // If we are returning from an update let'em know we're back Thread thread3 = new Thread(null, doUpdateCallback, "UpdateCallbackBkgnd"); thread3.start(); final Button goButton = (Button) findViewById(R.id.Button01); goButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); }
From source file:org.deviceconnect.android.manager.core.util.DConnectUtil.java
/** * Gets the ip address.//from www . j av a2 s .c o m * * @param context Context of application * @return Returns ip address */ public static String getIPAddress(final Context context) { Context appContext = context.getApplicationContext(); WifiManager wifiManager = (WifiManager) appContext.getSystemService(Context.WIFI_SERVICE); ConnectivityManager cManager = (ConnectivityManager) appContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo network = cManager.getActiveNetworkInfo(); String en0Ip = null; if (network != null) { switch (network.getType()) { case ConnectivityManager.TYPE_ETHERNET: try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr .hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (inetAddress instanceof Inet4Address && !inetAddress.getHostAddress().equals("127.0.0.1")) { en0Ip = inetAddress.getHostAddress(); break; } } } } catch (SocketException e) { Log.e("DConnectUtil", "Get Ethernet IP Error", e); } } } if (en0Ip != null) { return en0Ip; } else { int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); return String.format(Locale.getDefault(), "%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)); } }
From source file:com.mobilyzer.util.PhoneUtils.java
public String getWifiBSSID() { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo != null) { return wifiInfo.getBSSID(); }/* w ww .j a v a 2 s . c om*/ return null; }
From source file:com.mobilyzer.util.PhoneUtils.java
public String getWifiSSID() { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo != null) { return wifiInfo.getSSID(); }/* w w w . java 2 s . com*/ return null; }
From source file:com.mobilyzer.util.PhoneUtils.java
public int getWifiRSSI() { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo != null) { return wifiInfo.getRssi(); }//from w w w . j a va 2 s.co m return -1; }
From source file:riddimon.android.asianetautologin.HttpUtils.java
/** * Uses TelephonyManager and WifiManager to check for network connectivity. * Also incorporates CONNECTING state for retry scenarios. * @param context//from w ww. j av a 2 s . com * @return ConnectionStatus */ public ConnectionStatus isConnectedOLD(Context context) { boolean data = false, wifi = false; boolean data_connecting = false, wifi_connecting = false; TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); int ds = tm.getDataState(); int ws = wm.getWifiState(); switch (ds) { case TelephonyManager.DATA_CONNECTED: data = true; break; case TelephonyManager.DATA_CONNECTING: data_connecting = true; default: data = false; data_connecting = false; } switch (ws) { case WifiManager.WIFI_STATE_ENABLING: wifi_connecting = true; case WifiManager.WIFI_STATE_DISABLING: case WifiManager.WIFI_STATE_DISABLED: case WifiManager.WIFI_STATE_UNKNOWN: wifi = false; break; case WifiManager.WIFI_STATE_ENABLED: WifiInfo wi = wm.getConnectionInfo(); if (wi != null) wifi = true; break; } if (wifi && data) return ConnectionStatus.BOTH_CONNECTED; else if (wifi && data_connecting) return ConnectionStatus.WIFI_CONNECTED; else if (data && wifi_connecting) return ConnectionStatus.DATA_CONNECTED; else if (wifi_connecting || data_connecting) return ConnectionStatus.CONNECTING; return ConnectionStatus.NO_CONNECTION; }
From source file:com.mobilyzer.util.PhoneUtils.java
/** Returns current Wi-Fi SSID, or null if Wi-Fi is not connected. */ private String getWifiCarrierName() { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo != null) { return wifiInfo.getSSID(); }//from w w w . ja va 2 s . c om return null; }
From source file:org.sipdroid.sipua.ui.Receiver.java
@Override public void onReceive(Context context, Intent intent) { String intentAction = intent.getAction(); if (!Sipdroid.on(context)) return;/*ww w. j a v a2 s. c om*/ if (!Sipdroid.release) Log.i("SipUA:", intentAction); if (mContext == null) mContext = context; if (intentAction.equals(Intent.ACTION_BOOT_COMPLETED)) { on_vpn(false); engine(context).register(); } else if (intentAction.equals(ConnectivityManager.CONNECTIVITY_ACTION) || intentAction.equals(ACTION_EXTERNAL_APPLICATIONS_AVAILABLE) || intentAction.equals(ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE) || intentAction.equals(Intent.ACTION_PACKAGE_REPLACED)) { engine(context).register(); } else if (intentAction.equals(ACTION_VPN_CONNECTIVITY) && intent.hasExtra("connection_state")) { String state = intent.getSerializableExtra("connection_state").toString(); if (state != null && on_vpn() != state.equals("CONNECTED")) { on_vpn(state.equals("CONNECTED")); for (SipProvider sip_provider : engine(context).sip_providers) if (sip_provider != null) sip_provider.haltConnections(); engine(context).register(); } } else if (intentAction.equals(ACTION_DATA_STATE_CHANGED)) { engine(context).registerMore(); } else if (intentAction.equals(ACTION_PHONE_STATE_CHANGED) && !intent.getBooleanExtra(context.getString(R.string.app_name), false)) { stopRingtone(); pstn_state = intent.getStringExtra("state"); pstn_time = SystemClock.elapsedRealtime(); if (pstn_state.equals("IDLE") && call_state != UserAgent.UA_STATE_IDLE) broadcastCallStateChanged(null, null); if (!pstn_state.equals("IDLE") && call_state == UserAgent.UA_STATE_INCALL) mHandler.sendEmptyMessageDelayed(MSG_HOLD, 5000); else if (!pstn_state.equals("IDLE") && (call_state == UserAgent.UA_STATE_INCOMING_CALL || call_state == UserAgent.UA_STATE_OUTGOING_CALL)) mHandler.sendEmptyMessageDelayed(MSG_HANGUP, 5000); else if (pstn_state.equals("IDLE")) { mHandler.removeMessages(MSG_HOLD); mHandler.removeMessages(MSG_HANGUP); if (call_state == UserAgent.UA_STATE_HOLD) mHandler.sendEmptyMessageDelayed(MSG_HOLD, 1000); } } else if (intentAction.equals(ACTION_DOCK_EVENT)) { docked = intent.getIntExtra(EXTRA_DOCK_STATE, -1) & 7; if (call_state == UserAgent.UA_STATE_INCALL) engine(mContext).speaker(speakermode()); } else if (intentAction.equals(ACTION_SCO_AUDIO_STATE_CHANGED)) { bluetooth = intent.getIntExtra(EXTRA_SCO_AUDIO_STATE, -1); progress(); RtpStreamSender.changed = true; } else if (intentAction.equals(Intent.ACTION_HEADSET_PLUG)) { headset = intent.getIntExtra("state", -1); if (call_state == UserAgent.UA_STATE_INCALL) engine(mContext).speaker(speakermode()); } else if (intentAction.equals(Intent.ACTION_SCREEN_ON)) { if (!PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean( org.sipdroid.sipua.ui.Settings.PREF_OWNWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_OWNWIFI)) alarm(0, OwnWifi.class); } else if (intentAction.equals(Intent.ACTION_USER_PRESENT)) { mHandler.sendEmptyMessageDelayed(MSG_ENABLE, 3000); } else if (intentAction.equals(Intent.ACTION_SCREEN_OFF)) { if (PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean( org.sipdroid.sipua.ui.Settings.PREF_OWNWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_OWNWIFI)) { WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); WifiInfo wi = wm.getConnectionInfo(); if (wm.getWifiState() != WifiManager.WIFI_STATE_ENABLED || wi == null || wi.getSupplicantState() != SupplicantState.COMPLETED || wi.getIpAddress() == 0) alarm(2 * 60, OwnWifi.class); else alarm(15 * 60, OwnWifi.class); } if (SipdroidEngine.pwl != null) for (PowerManager.WakeLock pwl : SipdroidEngine.pwl) if (pwl != null && pwl.isHeld()) { pwl.release(); pwl.acquire(); } } else if (intentAction.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) { if (PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean( org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI)) mHandler.sendEmptyMessageDelayed(MSG_SCAN, 3000); } else if (intentAction.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { if (SystemClock.uptimeMillis() > lastscan + 45000 && PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean( org.sipdroid.sipua.ui.Settings.PREF_SELECTWIFI, org.sipdroid.sipua.ui.Settings.DEFAULT_SELECTWIFI)) { WifiManager wm = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); WifiInfo wi = wm.getConnectionInfo(); String activeSSID = null; if (wi != null) activeSSID = wi.getSSID(); if (activeSSID != null && (activeSSID.length() == 0 || activeSSID.equals("0x"))) activeSSID = null; List<ScanResult> mScanResults = wm.getScanResults(); List<WifiConfiguration> configurations = wm.getConfiguredNetworks(); if (configurations != null) { WifiConfiguration bestconfig = null, maxconfig = null, activeconfig = null; for (final WifiConfiguration config : configurations) { if (maxconfig == null || config.priority > maxconfig.priority) { maxconfig = config; } if (config.SSID != null && (config.SSID.equals("\"" + activeSSID + "\"") || config.SSID.equals(activeSSID))) activeconfig = config; } ScanResult bestscan = null, activescan = null; if (mScanResults != null) for (final ScanResult scan : mScanResults) { for (final WifiConfiguration config : configurations) { if (config.SSID != null && config.SSID.equals("\"" + scan.SSID + "\"")) { if (bestscan == null || scan.level > bestscan.level) { bestscan = scan; bestconfig = config; } if (config == activeconfig) activescan = scan; } } } if (activescan != null) System.out.println("debug wifi asu(active)" + asu(activescan)); if (bestconfig != null && (activeconfig == null || bestconfig.priority != activeconfig.priority) && asu(bestscan) > asu(activescan) * 1.5 && /* (activeSSID == null || activescan != null) && */ asu(bestscan) > 22) { if (!Sipdroid.release) Log.i("SipUA:", "changing to " + bestconfig.SSID); if (activeSSID == null || !activeSSID.equals(bestscan.SSID)) wm.disconnect(); bestconfig.priority = maxconfig.priority + 1; wm.updateNetwork(bestconfig); wm.enableNetwork(bestconfig.networkId, true); wm.saveConfiguration(); if (activeSSID == null || !activeSSID.equals(bestscan.SSID)) wm.reconnect(); lastscan = SystemClock.uptimeMillis(); } else if (activescan != null && asu(activescan) < 15) { wm.disconnect(); wm.disableNetwork(activeconfig.networkId); wm.saveConfiguration(); } } } } }