List of usage examples for android.net NetworkInfo isConnected
@Deprecated public boolean isConnected()
From source file:com.github.notizklotz.derbunddownloader.download.IssueDownloadService.java
@ServiceAction public void downloadIssue(int day, int month, int year) { Log.i(LOG_TAG, "Handling download intent"); try {//from www. ja v a 2 s .co m boolean connected; final boolean wifiOnly = Settings.isWifiOnly(getApplicationContext()); if (wifiOnly) { connected = waitForWifiConnection(); if (!connected) { notifyUser(getText(R.string.download_wifi_connection_failed), getText(R.string.download_wifi_connection_failed_text), R.drawable.ic_stat_newspaper); } } else { NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); connected = activeNetworkInfo != null && activeNetworkInfo.isConnected(); if (!connected) { notifyUser(getText(R.string.download_connection_failed), getText(R.string.download_connection_failed_text), R.drawable.ic_stat_newspaper); } } if (connected) { if (!checkUserAccount()) { notifyUser(getText(R.string.download_login_failed), getText(R.string.download_login_failed_text), R.drawable.ic_stat_newspaper); } else { final LocalDate issueDate = new LocalDate(day, month, year); fetchThumbnail(issueDate); final CountDownLatch downloadDoneSignal = new CountDownLatch(1); receiver = new DownloadCompletedBroadcastReceiver(downloadDoneSignal); registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); try { String title = startDownload(issueDate, wifiOnly); downloadDoneSignal.await(); notifyUser(title, getString(R.string.download_completed), R.drawable.ic_stat_newspaper); } catch (InterruptedException e) { Log.wtf(LOG_TAG, "Interrupted while waiting for the downloadDoneSignal"); } } } } catch (Exception e) { notifyUser(getText(R.string.download_service_error), getText(R.string.download_service_error_text) + " " + e.getMessage(), R.drawable.ic_stat_newspaper); } finally { cleanup(); } }
From source file:com.coinomi.wallet.ExchangeRatesProvider.java
@Nullable private JSONObject requestExchangeRatesJson(final URL url) { // Return null if no connection final NetworkInfo activeInfo = connManager.getActiveNetworkInfo(); if (activeInfo == null || !activeInfo.isConnected()) return null; final long start = System.currentTimeMillis(); OkHttpClient client = NetworkUtils.getHttpClient(getContext().getApplicationContext()); Request request = new Request.Builder().url(url).build(); try {//from w ww . j a va 2 s .c o m Response response = client.newCall(request).execute(); if (response.isSuccessful()) { log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, System.currentTimeMillis() - start); return new JSONObject(response.body().string()); } else { log.warn("Error HTTP code '{}' when fetching exchange rates from {}", response.code(), url); } } catch (IOException e) { log.warn("Error '{}' when fetching exchange rates from {}", e.getMessage(), url); } catch (JSONException e) { log.warn("Could not parse exchange rates JSON: {}", e.getMessage()); } return null; }
From source file:be.artoria.belfortapp.fragments.MapFragment.java
public void calculateRoute() { final ConnectivityManager cm = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo info = cm.getActiveNetworkInfo(); if (info != null) { if (info.isConnected()) { new RouteCalcTask().execute(); } else {// w w w .j a va 2s . c o m Toast.makeText(getActivity(), "Please check your wireless connection and try again.", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(getActivity(), "Please check your wireless connection and try again.", Toast.LENGTH_SHORT).show(); } }
From source file:com.calebgomer.roadkill_reporter.AsyncReporter.java
public boolean isOnline(Context mainContext) { ConnectivityManager cm = (ConnectivityManager) mainContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); return (info != null && info.isConnected()); }
From source file:com.github.notizklotz.derbunddownloader.download.IssueDownloadService.java
private boolean waitForWifiConnection() { boolean connected = false; if (wifiManager != null) { //WIFI_MODE_FULL was not enough on Xperia Tablet Z Android 4.2 to reconnect to the AP if Wifi was enabled but connection //was lost myWifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "IssueDownloadWifilock"); myWifiLock.setReferenceCounted(false); myWifiLock.acquire();//from www . ja v a 2 s.c o m //Wait for Wifi coming up long firstCheckMillis = System.currentTimeMillis(); if (!wifiManager.isWifiEnabled()) { notifyUser(getText(R.string.download_connection_failed), getText(R.string.download_connection_failed_no_wifi_text), R.drawable.ic_stat_newspaper); } else { do { NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); assert networkInfo != null; connected = networkInfo.isConnected(); if (!connected) { Log.d(LOG_TAG, "Wifi connection is not yet ready. Wait and recheck"); if (System.currentTimeMillis() - firstCheckMillis > WIFI_CHECK_MAX_MILLIS) { break; } try { Thread.sleep(WIFI_RECHECK_WAIT_MILLIS); } catch (InterruptedException e) { Log.wtf(LOG_TAG, "Interrupted while waiting for Wifi connection", e); } } } while (!connected); } } return connected; }
From source file:org.appcelerator.titanium.analytics.TiAnalyticsService.java
private boolean canSend() { boolean result = false; //int type = netInfo.getType(); //int subType = netInfo.getSubType(); // TODO change defaults based on implied speed of network NetworkInfo netInfo = null; try {/* w w w. ja v a 2 s.c o m*/ netInfo = connectivityManager.getActiveNetworkInfo(); } catch (SecurityException e) { Log.w(TAG, "Connectivity permissions have been removed from AndroidManifest.xml: " + e.getMessage()); } if (netInfo != null && netInfo.isConnected() && !netInfo.isRoaming()) { result = true; } return result; }
From source file:com.jaredrummler.android.device.DeviceName.java
/** Get the device name from the generated JSON files created from Google's device list. */ private static DeviceInfo getDeviceInfo(Context context, String codename, String model) { SharedPreferences prefs = context.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); String key = String.format("%s:%s", codename, model); String savedJson = prefs.getString(key, null); if (savedJson != null) { try {/*from w ww . j a v a2 s .c o m*/ return new DeviceInfo(new JSONObject(savedJson)); } catch (JSONException e) { e.printStackTrace(); } } // check if we have an internet connection int ret = context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE); boolean isConnectedToNetwork = false; if (ret == PackageManager.PERMISSION_GRANTED) { ConnectivityManager connMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { isConnectedToNetwork = true; } } else { // assume we are connected. isConnectedToNetwork = true; } if (isConnectedToNetwork) { try { String url = String.format(DEVICE_JSON_URL, codename.toLowerCase(Locale.ENGLISH)); String jsonString = downloadJson(url); JSONArray jsonArray = new JSONArray(jsonString); for (int i = 0, len = jsonArray.length(); i < len; i++) { JSONObject json = jsonArray.getJSONObject(i); DeviceInfo info = new DeviceInfo(json); if ((codename.equalsIgnoreCase(info.codename) && model == null) || codename.equalsIgnoreCase(info.codename) && model.equalsIgnoreCase(info.model)) { // Save to SharedPreferences so we don't need to make another request. SharedPreferences.Editor editor = prefs.edit(); editor.putString(key, json.toString()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { editor.apply(); } else { editor.commit(); } return info; } } } catch (Exception e) { e.printStackTrace(); } } if (codename.equals(Build.DEVICE) && model.equals(Build.MODEL)) { return new DeviceInfo(Build.MANUFACTURER, getDeviceName(), codename, model); // current device } return new DeviceInfo(null, null, codename, model); // unknown device }
From source file:com.cyanogenmod.settings.device.LtoDownloadService.java
private boolean shouldDownload(boolean forceDownload) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); boolean hasConnection = false; if (info == null || !info.isConnected()) { if (ALOGV) Log.v(TAG, "No network connection is available for LTO download"); } else if (forceDownload) { if (ALOGV) Log.v(TAG, "Download was forced, overriding network type check"); hasConnection = true;/*from w w w. ja va 2 s .c om*/ } else { boolean wifiOnly = prefs.getBoolean(KEY_WIFI_ONLY, WIFI_ONLY_DEFAULT); if (wifiOnly && info.getType() != ConnectivityManager.TYPE_WIFI) { if (ALOGV) { Log.v(TAG, "Active network is of type " + info.getTypeName() + ", but Wifi only was selected"); } } else { hasConnection = true; } } if (!hasConnection) { return false; } if (forceDownload) { return true; } if (!prefs.getBoolean(KEY_ENABLED, false)) { return false; } long now = System.currentTimeMillis(); long lastDownload = LtoDownloadUtils.getLastDownload(this); long due = lastDownload + LtoDownloadUtils.getDownloadInterval(this); if (ALOGV) { Log.v(TAG, "Now " + now + " due " + due + "(" + new Date(due) + ")"); } if (lastDownload != 0 && now < due) { if (ALOGV) Log.v(TAG, "LTO download is not due yet"); return false; } return true; }
From source file:devbox.com.br.minercompanion.ProfileActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (networkInfo.isConnected()) { final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); final WifiInfo connectionInfo = wifiManager.getConnectionInfo(); if (connectionInfo != null && !(connectionInfo.getSSID().equals(""))) { //if (connectionInfo != null && !StringUtil.isBlank(connectionInfo.getSSID())) { routerName = connectionInfo.getSSID(); }//w w w .j av a2 s . c om } sensorCounter = new SensorCounter(3000, 3000); sensorCounter.start(); Intent intent = getIntent(); if(intent != null) { matricula = intent.getStringExtra("MATRICULA"); TextView textView = (TextView) findViewById(R.id.textView); textView.setText("Matrcula: " + matricula); sensors = new Sensors(matricula, routerName.replace("\"","")); } /* Get a SensorManager instance */ sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); ListView listView = (ListView) findViewById(R.id.listView); profileListAdapter = new ProfileListAdapter(this, strings); listView.setAdapter(profileListAdapter); profileListAdapter.addItem("Conectado ao servidor!"); }
From source file:com.andrada.sitracker.ui.fragment.AuthorsFragment.java
@OptionsItem(R.id.action_refresh) void menuRefreshSelected() { if (!mIsUpdating && adapter.getCount() > 0) { final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); if (activeNetwork != null && activeNetwork.isConnected()) { Intent updateIntent = new Intent(getActivity(), UpdateAuthorsTask_.class); updateIntent.putExtra(Constants.UPDATE_IGNORES_NETWORK, true); getActivity().startService(updateIntent); AnalyticsHelper.getInstance().sendEvent(Constants.GA_READ_CATEGORY, Constants.GA_EVENT_AUTHORS_MANUAL_REFRESH, Constants.GA_EVENT_AUTHORS_MANUAL_REFRESH); toggleUpdatingState();//from w ww . ja v a 2 s . com } else { //Surface crouton that network is unavailable showNoNetworkCroutonMessage(); } } }