List of usage examples for android.net NetworkInfo isRoaming
@Deprecated public boolean isRoaming()
From source file:com.master.metehan.filtereagle.Util.java
public static String getNetworkInfo(Context context) { StringBuilder sb = new StringBuilder(); ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ani = cm.getActiveNetworkInfo(); List<NetworkInfo> listNI = new ArrayList<>(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) listNI.addAll(Arrays.asList(cm.getAllNetworkInfo())); else//from ww w . ja va 2 s . com for (Network network : cm.getAllNetworks()) { NetworkInfo ni = cm.getNetworkInfo(network); if (ni != null) listNI.add(ni); } for (NetworkInfo ni : listNI) { sb.append(ni.getTypeName()).append('/').append(ni.getSubtypeName()).append(' ') .append(ni.getDetailedState()) .append(TextUtils.isEmpty(ni.getExtraInfo()) ? "" : " " + ni.getExtraInfo()) .append(ni.getType() == ConnectivityManager.TYPE_MOBILE ? " " + Util.getNetworkGeneration(ni.getSubtype()) : "") .append(ni.isRoaming() ? " R" : "") .append(ani != null && ni.getType() == ani.getType() && ni.getSubtype() == ani.getSubtype() ? " *" : "") .append("\r\n"); } try { Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces(); if (nis != null) { sb.append("\r\n"); while (nis.hasMoreElements()) { NetworkInterface ni = nis.nextElement(); if (ni != null) { List<InterfaceAddress> ias = ni.getInterfaceAddresses(); if (ias != null) for (InterfaceAddress ia : ias) sb.append(ni.getName()).append(' ').append(ia.getAddress().getHostAddress()) .append('/').append(ia.getNetworkPrefixLength()).append(' ') .append(ni.getMTU()).append("\r\n"); } } } } catch (Throwable ex) { sb.append(ex.toString()).append("\r\n"); } if (sb.length() > 2) sb.setLength(sb.length() - 2); return sb.toString(); }
From source file:com.ruesga.rview.fragments.DownloadDialogFragment.java
@SuppressWarnings("ConstantConditions") private Observable<Request> doRequestDownload(Integer requestCode) { return SafeObservable.fromNullCallable(() -> { if (getActivity() != null) { Request request = new Request(); request.mRequestCode = requestCode; ConnectivityManager cm = (ConnectivityManager) getActivity() .getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni == null) { request.mStatus = 1;/*w w w. j a v a2 s .c o m*/ return request; } if (ConnectivityManagerCompat.isActiveNetworkMetered(cm) || ni.isRoaming()) { request.mStatus = 2; return request; } return request; } throw new IllegalStateException(); }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()); }
From source file:ch.ethz.coss.nervousnet.vm.sensors.ConnectivitySensor.java
public void runConnectivitySensor() { Log.d(LOG_TAG, "Inside runConnectivitySensor"); if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return;/*from w ww . j a v a 2 s . c o m*/ } ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); int networkType = -1; boolean isRoaming = false; if (isConnected) { networkType = activeNetwork.getType(); isRoaming = activeNetwork.isRoaming(); } String wifiHashId = ""; int wifiStrength = Integer.MIN_VALUE; if (networkType == ConnectivityManager.TYPE_WIFI) { WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wi = wm.getConnectionInfo(); StringBuilder wifiInfoBuilder = new StringBuilder(); wifiInfoBuilder.append(wi.getBSSID()); wifiInfoBuilder.append(wi.getSSID()); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(wifiInfoBuilder.toString().getBytes()); wifiHashId = new String(messageDigest.digest()); } catch (NoSuchAlgorithmException e) { } wifiStrength = wi.getRssi(); } byte[] cdmaHashId = new byte[32]; byte[] lteHashId = new byte[32]; byte[] gsmHashId = new byte[32]; byte[] wcdmaHashId = new byte[32]; TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); List<CellInfo> cis = tm.getAllCellInfo(); if (cis != null) { // New method for (CellInfo ci : cis) { if (ci.isRegistered()) { if (ci instanceof CellInfoCdma) { CellInfoCdma cic = (CellInfoCdma) ci; cdmaHashId = generateMobileDigestId(cic.getCellIdentity().getSystemId(), cic.getCellIdentity().getNetworkId(), cic.getCellIdentity().getBasestationId()); } if (ci instanceof CellInfoGsm) { CellInfoGsm cic = (CellInfoGsm) ci; gsmHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(), cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCid()); } if (ci instanceof CellInfoLte) { CellInfoLte cic = (CellInfoLte) ci; lteHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(), cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCi()); } if (ci instanceof CellInfoWcdma) { CellInfoWcdma cic = (CellInfoWcdma) ci; wcdmaHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(), cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCid()); } } } } else { // Legacy method CellLocation cl = tm.getCellLocation(); if (cl instanceof CdmaCellLocation) { CdmaCellLocation cic = (CdmaCellLocation) cl; cdmaHashId = generateMobileDigestId(cic.getSystemId(), cic.getNetworkId(), cic.getBaseStationId()); } if (cl instanceof GsmCellLocation) { GsmCellLocation cic = (GsmCellLocation) cl; gsmHashId = generateMobileDigestId(cic.getLac(), 0, cic.getCid()); } } StringBuilder mobileHashBuilder = new StringBuilder(); mobileHashBuilder.append(new String(cdmaHashId)); mobileHashBuilder.append(new String(lteHashId)); mobileHashBuilder.append(new String(gsmHashId)); mobileHashBuilder.append(new String(wcdmaHashId)); dataReady(new ConnectivityReading(System.currentTimeMillis(), isConnected, networkType, isRoaming, wifiHashId, wifiStrength, mobileHashBuilder.toString())); }
From source file:com.acc.android.network.operator.base.BaseHttpOperator.java
public static boolean hasInternet(Context context) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info == null || !info.isConnected()) { return false; }//w w w . j av a 2 s .c om if (info.isRoaming()) { return true; } return true; }
From source file:org.openchaos.android.fooping.service.PingService.java
@Override protected void onHandleIntent(Intent intent) { String clientID = prefs.getString("ClientID", "unknown"); long ts = System.currentTimeMillis(); Log.d(tag, "onHandleIntent()"); // always send ping if (true) {// ww w . jav a 2 s. c om try { JSONObject json = new JSONObject(); json.put("client", clientID); json.put("type", "ping"); json.put("ts", ts); sendMessage(json); } catch (Exception e) { Log.e(tag, e.toString()); e.printStackTrace(); } } // http://developer.android.com/training/monitoring-device-state/battery-monitoring.html // http://developer.android.com/reference/android/os/BatteryManager.html if (prefs.getBoolean("UseBattery", false)) { try { JSONObject json = new JSONObject(); json.put("client", clientID); json.put("type", "battery"); json.put("ts", ts); Intent batteryStatus = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); if (batteryStatus != null) { JSONObject bat_data = new JSONObject(); int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); if (level >= 0 && scale > 0) { bat_data.put("pct", roundValue(((double) level / (double) scale) * 100, 2)); } else { Log.w(tag, "Battery level unknown"); bat_data.put("pct", -1); } bat_data.put("health", batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, -1)); bat_data.put("status", batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1)); bat_data.put("plug", batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)); bat_data.put("volt", batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1)); bat_data.put("temp", batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1)); bat_data.put("tech", batteryStatus.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY)); // bat_data.put("present", batteryStatus.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false)); json.put("battery", bat_data); } sendMessage(json); } catch (Exception e) { Log.e(tag, e.toString()); e.printStackTrace(); } } // http://developer.android.com/guide/topics/location/strategies.html // http://developer.android.com/reference/android/location/LocationManager.html if (prefs.getBoolean("UseGPS", false)) { try { JSONObject json = new JSONObject(); json.put("client", clientID); json.put("type", "loc_gps"); json.put("ts", ts); if (lm == null) { lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); } Location last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (last_loc != null) { JSONObject loc_data = new JSONObject(); loc_data.put("ts", last_loc.getTime()); loc_data.put("lat", last_loc.getLatitude()); loc_data.put("lon", last_loc.getLongitude()); if (last_loc.hasAltitude()) loc_data.put("alt", roundValue(last_loc.getAltitude(), 4)); if (last_loc.hasAccuracy()) loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4)); if (last_loc.hasSpeed()) loc_data.put("speed", roundValue(last_loc.getSpeed(), 4)); if (last_loc.hasBearing()) loc_data.put("bearing", roundValue(last_loc.getBearing(), 4)); json.put("loc_gps", loc_data); } sendMessage(json); } catch (Exception e) { Log.e(tag, e.toString()); e.printStackTrace(); } } if (prefs.getBoolean("UseNetwork", false)) { try { JSONObject json = new JSONObject(); json.put("client", clientID); json.put("type", "loc_net"); json.put("ts", ts); if (lm == null) { lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); } Location last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (last_loc != null) { JSONObject loc_data = new JSONObject(); loc_data.put("ts", last_loc.getTime()); loc_data.put("lat", last_loc.getLatitude()); loc_data.put("lon", last_loc.getLongitude()); if (last_loc.hasAltitude()) loc_data.put("alt", roundValue(last_loc.getAltitude(), 4)); if (last_loc.hasAccuracy()) loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4)); if (last_loc.hasSpeed()) loc_data.put("speed", roundValue(last_loc.getSpeed(), 4)); if (last_loc.hasBearing()) loc_data.put("bearing", roundValue(last_loc.getBearing(), 4)); json.put("loc_net", loc_data); } sendMessage(json); } catch (Exception e) { Log.e(tag, e.toString()); e.printStackTrace(); } } // http://developer.android.com/reference/android/net/wifi/WifiManager.html if (prefs.getBoolean("UseWIFI", false)) { try { JSONObject json = new JSONObject(); json.put("client", clientID); json.put("type", "wifi"); json.put("ts", ts); if (wm == null) { wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); } List<ScanResult> wifiScan = wm.getScanResults(); if (wifiScan != null) { JSONArray wifi_list = new JSONArray(); for (ScanResult wifi : wifiScan) { JSONObject wifi_data = new JSONObject(); wifi_data.put("BSSID", wifi.BSSID); wifi_data.put("SSID", wifi.SSID); wifi_data.put("freq", wifi.frequency); wifi_data.put("level", wifi.level); // wifi_data.put("cap", wifi.capabilities); // wifi_data.put("ts", wifi.timestamp); wifi_list.put(wifi_data); } json.put("wifi", wifi_list); } sendMessage(json); } catch (Exception e) { Log.e(tag, e.toString()); e.printStackTrace(); } } // TODO: cannot poll sensors. register receiver to cache sensor data // http://developer.android.com/guide/topics/sensors/sensors_overview.html // http://developer.android.com/reference/android/hardware/SensorManager.html if (prefs.getBoolean("UseSensors", false)) { try { JSONObject json = new JSONObject(); json.put("client", clientID); json.put("type", "sensors"); json.put("ts", ts); if (sm == null) { sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE); } List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ALL); if (sensors != null) { JSONArray sensor_list = new JSONArray(); for (Sensor sensor : sensors) { JSONObject sensor_info = new JSONObject(); sensor_info.put("name", sensor.getName()); sensor_info.put("type", sensor.getType()); sensor_info.put("vendor", sensor.getVendor()); sensor_info.put("version", sensor.getVersion()); sensor_info.put("power", roundValue(sensor.getPower(), 4)); sensor_info.put("resolution", roundValue(sensor.getResolution(), 4)); sensor_info.put("range", roundValue(sensor.getMaximumRange(), 4)); sensor_list.put(sensor_info); } json.put("sensors", sensor_list); } sendMessage(json); } catch (Exception e) { Log.e(tag, e.toString()); e.printStackTrace(); } } // http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html // http://developer.android.com/reference/android/net/ConnectivityManager.html if (prefs.getBoolean("UseConn", false)) { try { JSONObject json = new JSONObject(); json.put("client", clientID); json.put("type", "conn"); json.put("ts", ts); if (cm == null) { cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); } // TODO: add active/all preferences below UseConn if (prefs.getBoolean("UseConnActive", true)) { NetworkInfo net = cm.getActiveNetworkInfo(); if (net != null) { JSONObject net_data = new JSONObject(); net_data.put("type", net.getTypeName()); net_data.put("subtype", net.getSubtypeName()); net_data.put("connected", net.isConnected()); net_data.put("available", net.isAvailable()); net_data.put("roaming", net.isRoaming()); net_data.put("failover", net.isFailover()); if (net.getReason() != null) net_data.put("reason", net.getReason()); if (net.getExtraInfo() != null) net_data.put("extra", net.getExtraInfo()); json.put("conn_active", net_data); } } if (prefs.getBoolean("UseConnAll", false)) { NetworkInfo[] nets = cm.getAllNetworkInfo(); if (nets != null) { JSONArray net_list = new JSONArray(); for (NetworkInfo net : nets) { JSONObject net_data = new JSONObject(); net_data.put("type", net.getTypeName()); net_data.put("subtype", net.getSubtypeName()); net_data.put("connected", net.isConnected()); net_data.put("available", net.isAvailable()); net_data.put("roaming", net.isRoaming()); net_data.put("failover", net.isFailover()); if (net.getReason() != null) net_data.put("reason", net.getReason()); if (net.getExtraInfo() != null) net_data.put("extra", net.getExtraInfo()); net_list.put(net_data); } json.put("conn_all", net_list); } } sendMessage(json); } catch (Exception e) { Log.e(tag, e.toString()); e.printStackTrace(); } } if (!PingServiceReceiver.completeWakefulIntent(intent)) { Log.w(tag, "completeWakefulIntent() failed. no active wake lock?"); } }
From source file:com.appsimobile.appsii.module.weather.WeatherLoadingService.java
void doSync(String defaultUnit, String extraWoeid, SyncResult result) { if (defaultUnit == null) throw new IllegalArgumentException("defaultUnit == null"); NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo(); boolean online = netInfo != null && netInfo.isConnected(); if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "Handling sync"); if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "Checking online"); if (!online) { bailOut("No network connection"); result.stats.numIoExceptions++;//from w w w. j ava2 s . co m return; } boolean syncWhenRoaming = mPreferenceHelper.getSyncWhenRoaming(); if (netInfo.isRoaming() && !syncWhenRoaming) { bailOut("Not syncing because of roaming connection"); result.stats.numIoExceptions++; return; } if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "- Checking online"); if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "get woeids"); String[] woeids = mConfigurationHelper.getWeatherWidgetWoeids(WeatherFragment.PREFERENCE_WEATHER_WOEID); if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "- get woeids"); if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "extra woeids"); if (extraWoeid != null) { int length = woeids.length; String[] temp = new String[length + 1]; System.arraycopy(woeids, 0, temp, 0, length); temp[length] = extraWoeid; woeids = temp; } if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "- extra woeids"); if (woeids.length == 0) { bailOut("Not syncing because there are no woeids"); // tell the service to reschedule normally result.stats.numUpdates++; return; } if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "find timezones"); int N = woeids.length; SimpleArrayMap<String, String> woeidTimezones = new SimpleArrayMap<>(N); for (int i = 0; i < N; i++) { String woeid = woeids[i]; long cellId = mConfigurationHelper.findCellWithPropertyValue(WeatherFragment.PREFERENCE_WEATHER_WOEID, woeid); if (cellId != -1) { String timezone = mConfigurationHelper.getProperty(cellId, WeatherFragment.PREFERENCE_WEATHER_TIMEZONE, null); if (BuildConfig.DEBUG) { Log.d("WeatherLoadingService", "woeid -> timezone: " + woeid + " -> " + timezone); } woeidTimezones.put(woeid, timezone); } } if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "- find timezones"); try { if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "request location"); Location location; if (mPermissionUtils.holdsPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION)) { location = requestLocationInfoBlocking(); } else { woeids = addFallbackWoeid(woeids, woeidTimezones); location = null; } if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "- request location"); SimpleArrayMap<String, WeatherData> previousData = new SimpleArrayMap<>(woeids.length); for (String woeid : woeids) { WeatherData data = mWeatherUtils.getWeatherData(mContext, woeid); previousData.put(woeid, data); } if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "load data"); WeatherDataLoader loader = new WeatherDataLoader(location, woeids, defaultUnit); CircularArray<WeatherData> data = loader.queryWeather(); result.stats.numUpdates++; if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "- load data"); if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "sync images"); int size = data.size(); for (int i = 0; i < size; i++) { WeatherData weatherData = data.get(i); try { syncImages(result, mConnectivityManager, mPreferenceHelper, woeidTimezones, previousData, weatherData); } catch (VolleyError e) { Log.w("WeatherLoadingService", "error getting images", e); } } if (BuildConfig.DEBUG) Log.d("WeatherLoadingService", "- sync images"); } catch (InterruptedException ignore) { // we have been requested to stop, so simply stop result.stats.numIoExceptions++; } catch (CantGetWeatherException e) { Log.e("WeatherLoadingService", "error loading weather. Waiting for next retry", e); result.stats.numIoExceptions++; } }
From source file:at.alladin.rmbt.android.util.InformationCollector.java
private void getClientInfo() { final String tmpuuid = ConfigHelper.getUUID(context); if (tmpuuid == null || tmpuuid.length() == 0) fullInfo.setProperty("UUID", ""); else/*from ww w. j a v a2s. c om*/ fullInfo.setProperty("UUID", tmpuuid); fullInfo.setProperty("PLATTFORM", PLATTFORM_NAME); fullInfo.setProperty("OS_VERSION", android.os.Build.VERSION.RELEASE + "(" + android.os.Build.VERSION.INCREMENTAL + ")"); fullInfo.setProperty("API_LEVEL", String.valueOf(android.os.Build.VERSION.SDK_INT)); fullInfo.setProperty("DEVICE", android.os.Build.DEVICE); fullInfo.setProperty("MODEL", android.os.Build.MODEL); fullInfo.setProperty("PRODUCT", android.os.Build.PRODUCT); fullInfo.setProperty("NETWORK_TYPE", String.valueOf(getNetwork())); if (connManager != null) { final NetworkInfo activeNetworkInfo = connManager.getActiveNetworkInfo(); if (activeNetworkInfo != null) fullInfo.setProperty("TELEPHONY_NETWORK_IS_ROAMING", String.valueOf(activeNetworkInfo.isRoaming())); } PackageInfo pInfo; String clientVersion = ""; try { pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); clientVersion = pInfo.versionName; } catch (final NameNotFoundException e) { // e1.printStackTrace(); Log.e(DEBUG_TAG, "version of the application cannot be found", e); } fullInfo.setProperty("CLIENT_NAME", Config.RMBT_CLIENT_NAME); fullInfo.setProperty("CLIENT_SOFTWARE_VERSION", clientVersion); }
From source file:com.appsimobile.appsii.module.weather.WeatherLoadingService.java
private void syncImages(SyncResult result, ConnectivityManager cm, PreferenceHelper preferenceHelper, SimpleArrayMap<String, String> woeidTimezones, SimpleArrayMap<String, WeatherData> previousData, WeatherData weatherData) throws VolleyError { NetworkInfo netInfo; String woeid = weatherData.woeid; WeatherData previous = previousData.get(woeid); File[] photos = mWeatherUtils.getCityPhotos(mContext, woeid); boolean changed = photos == null || previous == null || previous.nowConditionCode != weatherData.nowConditionCode; if (changed) { boolean downloadEnabled = preferenceHelper.getUseFlickrImages(); boolean downloadOnWifiOnly = preferenceHelper.getDownloadImagesOnWifiOnly(); boolean downloadWhenRoaming = preferenceHelper.getDownloadWhenRoaming(); netInfo = cm.getActiveNetworkInfo(); if (netInfo == null) return; boolean wifi = netInfo.getType() == ConnectivityManager.TYPE_WIFI; boolean roaming = netInfo.isRoaming(); // tell the sync we got an io exception // so it knows we would like to try again later if (roaming && !downloadWhenRoaming) { result.stats.numIoExceptions++; return; }// w ww. j a v a 2 s . co m // well, we are not on wifi, and the user // only wants to sync this when wifi // is enabled. if (!wifi && downloadOnWifiOnly) { result.stats.numIoExceptions++; return; } // only download when the user has the option // to download flickr images enabled in // settings if (downloadEnabled) { String timezone = woeidTimezones.get(woeid); downloadWeatherImages(mContext, mBitmapUtils, woeid, weatherData, timezone); result.stats.numInserts++; } } }
From source file:com.landenlabs.all_devtool.NetFragment.java
public void updateList() { // Time today = new Time(Time.getCurrentTimezone()); // today.setToNow(); // today.format(" %H:%M:%S") Date dt = new Date(); m_titleTime.setText(m_timeFormat.format(dt)); boolean expandAll = m_list.isEmpty(); m_list.clear();// w ww.j av a 2s.c o m // Swap colors int color = m_rowColor1; m_rowColor1 = m_rowColor2; m_rowColor2 = color; ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE); try { String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(), Settings.Secure.ANDROID_ID); addBuild("Android ID", androidIDStr); try { AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext()); final String adIdStr = adInfo.getId(); final boolean isLAT = adInfo.isLimitAdTrackingEnabled(); addBuild("Ad ID", adIdStr); } catch (IOException e) { // Unrecoverable error connecting to Google Play services (e.g., // the old version of the service doesn't support getting AdvertisingId). } catch (GooglePlayServicesNotAvailableException e) { // Google Play services is not available entirely. } /* try { InstanceID instanceID = InstanceID.getInstance(getContext()); if (instanceID != null) { // Requires a Google Developer project ID. String authorizedEntity = "<need to make this on google developer site>"; instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); addBuild("Instance ID", instanceID.getId()); } } catch (Exception ex) { } */ ConfigurationInfo info = actMgr.getDeviceConfigurationInfo(); addBuild("OpenGL", info.getGlEsVersion()); } catch (Exception ex) { m_log.e(ex.getMessage()); } // --------------- Connection Services ------------- try { ConnectivityManager connMgr = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo netInfo = connMgr.getActiveNetworkInfo(); if (netInfo != null) { Map<String, String> netListStr = new LinkedHashMap<String, String>(); putIf(netListStr, "Available", "Yes", netInfo.isAvailable()); putIf(netListStr, "Connected", "Yes", netInfo.isConnected()); putIf(netListStr, "Connecting", "Yes", !netInfo.isConnected() && netInfo.isConnectedOrConnecting()); putIf(netListStr, "Roaming", "Yes", netInfo.isRoaming()); putIf(netListStr, "Extra", netInfo.getExtraInfo(), !TextUtils.isEmpty(netInfo.getExtraInfo())); putIf(netListStr, "WhyFailed", netInfo.getReason(), !TextUtils.isEmpty(netInfo.getReason())); if (Build.VERSION.SDK_INT >= 16) { putIf(netListStr, "Metered", "Avoid heavy use", connMgr.isActiveNetworkMetered()); } netListStr.put("NetworkType", netInfo.getTypeName()); if (connMgr.getAllNetworkInfo().length > 1) { netListStr.put("Available Networks:", " "); for (NetworkInfo netI : connMgr.getAllNetworkInfo()) { if (netI.isAvailable()) { netListStr.put(" " + netI.getTypeName(), netI.isAvailable() ? "Yes" : "No"); } } } if (netInfo.isConnected()) { 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.isLoopbackAddress()) { if (inetAddress.getHostAddress() != null) { String ipType = (inetAddress instanceof Inet4Address) ? "IPv4" : "IPv6"; netListStr.put(intf.getName() + " " + ipType, inetAddress.getHostAddress()); } // if (!TextUtils.isEmpty(inetAddress.getHostName())) // listStr.put( "HostName", inetAddress.getHostName()); } } } } catch (Exception ex) { m_log.e("Network %s", ex.getMessage()); } } addBuild("Network...", netListStr); } } catch (Exception ex) { m_log.e("Network %s", ex.getMessage()); } // --------------- Telephony Services ------------- TelephonyManager telephonyManager = (TelephonyManager) getActivity() .getSystemService(Context.TELEPHONY_SERVICE); if (telephonyManager != null) { Map<String, String> cellListStr = new LinkedHashMap<String, String>(); try { cellListStr.put("Version", telephonyManager.getDeviceSoftwareVersion()); cellListStr.put("Number", telephonyManager.getLine1Number()); cellListStr.put("Service", telephonyManager.getNetworkOperatorName()); cellListStr.put("Roaming", telephonyManager.isNetworkRoaming() ? "Yes" : "No"); cellListStr.put("Type", getNetworkTypeName(telephonyManager.getNetworkType())); if (Build.VERSION.SDK_INT >= 17) { if (telephonyManager.getAllCellInfo() != null) { for (CellInfo cellInfo : telephonyManager.getAllCellInfo()) { String cellName = cellInfo.getClass().getSimpleName(); int level = 0; if (cellInfo instanceof CellInfoCdma) { level = ((CellInfoCdma) cellInfo).getCellSignalStrength().getLevel(); } else if (cellInfo instanceof CellInfoGsm) { level = ((CellInfoGsm) cellInfo).getCellSignalStrength().getLevel(); } else if (cellInfo instanceof CellInfoLte) { level = ((CellInfoLte) cellInfo).getCellSignalStrength().getLevel(); } else if (cellInfo instanceof CellInfoWcdma) { if (Build.VERSION.SDK_INT >= 18) { level = ((CellInfoWcdma) cellInfo).getCellSignalStrength().getLevel(); } } cellListStr.put(cellName, "Level% " + String.valueOf(100 * level / 4)); } } } for (NeighboringCellInfo cellInfo : telephonyManager.getNeighboringCellInfo()) { int level = cellInfo.getRssi(); cellListStr.put("Cell level%", String.valueOf(100 * level / 31)); } } catch (Exception ex) { m_log.e("Cell %s", ex.getMessage()); } if (!cellListStr.isEmpty()) { addBuild("Cell...", cellListStr); } } // --------------- Bluetooth Services (API18) ------------- if (Build.VERSION.SDK_INT >= 18) { try { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter != null) { Map<String, String> btListStr = new LinkedHashMap<String, String>(); btListStr.put("Enabled", bluetoothAdapter.isEnabled() ? "yes" : "no"); btListStr.put("Name", bluetoothAdapter.getName()); btListStr.put("ScanMode", String.valueOf(bluetoothAdapter.getScanMode())); btListStr.put("State", String.valueOf(bluetoothAdapter.getState())); Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); // If there are paired devices if (pairedDevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : pairedDevices) { // Add the name and address to an array adapter to show in a ListView btListStr.put("Paired:" + device.getName(), device.getAddress()); } } BluetoothManager btMgr = (BluetoothManager) getActivity() .getSystemService(Context.BLUETOOTH_SERVICE); if (btMgr != null) { // btMgr.getAdapter(). } addBuild("Bluetooth", btListStr); } } catch (Exception ex) { } } // --------------- Wifi Services ------------- final WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext() .getSystemService(Context.WIFI_SERVICE); if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) { if (mSystemBroadcastReceiver == null) { mSystemBroadcastReceiver = new SystemBroadcastReceiver(wifiMgr); getActivity().registerReceiver(mSystemBroadcastReceiver, INTENT_FILTER_SCAN_AVAILABLE); } if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (wifiMgr.getScanResults() == null || wifiMgr.getScanResults().size() != mLastScanSize) { mLastScanSize = wifiMgr.getScanResults().size(); wifiMgr.startScan(); } } Map<String, String> wifiListStr = new LinkedHashMap<String, String>(); try { DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo(); wifiListStr.put("DNS1", Formatter.formatIpAddress(dhcpInfo.dns1)); wifiListStr.put("DNS2", Formatter.formatIpAddress(dhcpInfo.dns2)); wifiListStr.put("Default Gateway", Formatter.formatIpAddress(dhcpInfo.gateway)); wifiListStr.put("IP Address", Formatter.formatIpAddress(dhcpInfo.ipAddress)); wifiListStr.put("Subnet Mask", Formatter.formatIpAddress(dhcpInfo.netmask)); wifiListStr.put("Server IP", Formatter.formatIpAddress(dhcpInfo.serverAddress)); wifiListStr.put("Lease Time(sec)", String.valueOf(dhcpInfo.leaseDuration)); WifiInfo wifiInfo = wifiMgr.getConnectionInfo(); if (wifiInfo != null) { wifiListStr.put("LinkSpeed Mbps", String.valueOf(wifiInfo.getLinkSpeed())); int numberOfLevels = 10; int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1); wifiListStr.put("Signal%", String.valueOf(100 * level / numberOfLevels)); if (Build.VERSION.SDK_INT >= 23) { wifiListStr.put("MAC", getMacAddr()); } else { wifiListStr.put("MAC", wifiInfo.getMacAddress()); } } } catch (Exception ex) { m_log.e("Wifi %s", ex.getMessage()); } if (!wifiListStr.isEmpty()) { addBuild("WiFi...", wifiListStr); } try { if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { List<ScanResult> listWifi = wifiMgr.getScanResults(); if (listWifi != null && !listWifi.isEmpty()) { int idx = 0; for (ScanResult scanResult : listWifi) { Map<String, String> wifiScanListStr = new LinkedHashMap<String, String>(); wifiScanListStr.put("SSID", scanResult.SSID); if (Build.VERSION.SDK_INT >= 23) { wifiScanListStr.put(" Name", scanResult.operatorFriendlyName.toString()); wifiScanListStr.put(" Venue", scanResult.venueName.toString()); } // wifiScanListStr.put(" BSSID ",scanResult.BSSID); wifiScanListStr.put(" Capabilities", scanResult.capabilities); // wifiScanListStr.put(" Center Freq", String.valueOf(scanResult.centerFreq0)); // wifiScanListStr.put(" Freq width", String.valueOf(scanResult.channelWidth)); wifiScanListStr.put(" Level, Freq", String.format("%d, %d", scanResult.level, scanResult.frequency)); if (Build.VERSION.SDK_INT >= 17) { Date wifiTime = new Date(scanResult.timestamp); wifiScanListStr.put(" Time", wifiTime.toLocaleString()); } addBuild(String.format("WiFiScan #%d", ++idx), wifiScanListStr); } } } } catch (Exception ex) { m_log.e("WifiList %s", ex.getMessage()); } try { List<WifiConfiguration> listWifiCfg = wifiMgr.getConfiguredNetworks(); for (WifiConfiguration wifiCfg : listWifiCfg) { Map<String, String> wifiCfgListStr = new LinkedHashMap<String, String>(); if (Build.VERSION.SDK_INT >= 23) { wifiCfgListStr.put("Name", wifiCfg.providerFriendlyName); } wifiCfgListStr.put("SSID", wifiCfg.SSID); String netStatus = ""; switch (wifiCfg.status) { case WifiConfiguration.Status.CURRENT: netStatus = "Connected"; break; case WifiConfiguration.Status.DISABLED: netStatus = "Disabled"; break; case WifiConfiguration.Status.ENABLED: netStatus = "Enabled"; break; } wifiCfgListStr.put(" Status", netStatus); wifiCfgListStr.put(" Priority", String.valueOf(wifiCfg.priority)); if (null != wifiCfg.wepKeys) { // wifiCfgListStr.put(" wepKeys", TextUtils.join(",", wifiCfg.wepKeys)); } String protocols = ""; if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.RSN)) protocols = "RSN "; if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.WPA)) protocols = protocols + "WPA "; wifiCfgListStr.put(" Protocols", protocols); String keyProt = ""; if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) keyProt = "none"; if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)) keyProt = "WPA+EAP "; if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) keyProt = "WPA+PSK "; wifiCfgListStr.put(" Keys", keyProt); if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) { // Remove network connections with no Password. // wifiMgr.removeNetwork(wifiCfg.networkId); } addBuild("WiFiCfg #" + wifiCfg.networkId, wifiCfgListStr); } } catch (Exception ex) { m_log.e("Wifi Cfg List %s", ex.getMessage()); } } if (expandAll) { // updateList(); int count = m_list.size(); for (int position = 0; position < count; position++) m_listView.expandGroup(position); } m_adapter.notifyDataSetChanged(); }
From source file:com.chen.emailsync.SyncManager.java
/** * Determine whether the account is allowed to sync automatically, as opposed to manually, based * on whether the "require manual sync when roaming" policy is in force and applicable * @param account the account/*from w w w . ja v a2 s . c om*/ * @return whether or not the account can sync automatically */ /*package*/ public static boolean canAutoSync(Account account) { SyncManager ssm = INSTANCE; if (ssm == null) { return false; } NetworkInfo networkInfo = ssm.mNetworkInfo; // Enforce manual sync only while roaming here long policyKey = account.mPolicyKey; // Quick exit from this check if ((policyKey != 0) && (networkInfo != null) && isNetworkTypeMobile(networkInfo.getType())) { // We'll cache the Policy data here Policy policy = account.mPolicy; if (policy == null) { policy = Policy.restorePolicyWithId(INSTANCE, policyKey); account.mPolicy = policy; if (!PolicyServiceProxy.isActive(ssm, policy)) { PolicyServiceProxy.setAccountHoldFlag(ssm, account, true); log("canAutoSync; policies not active, set hold flag"); return false; } } if (policy != null && policy.mRequireManualSyncWhenRoaming && networkInfo.isRoaming()) { return false; } } return true; }