List of usage examples for android.net NetworkInfo isConnectedOrConnecting
@Deprecated public boolean isConnectedOrConnecting()
From source file:fr.openbike.android.service.SyncService.java
@SuppressWarnings("unchecked") @Override//from ww w .ja v a 2 s . c om protected void onHandleIntent(Intent intent) { NetworkInfo activeNetwork = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)) .getActiveNetworkInfo(); final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER); Bundle bundle = new Bundle(); int status = STATUS_ERROR; if (activeNetwork == null || !activeNetwork.isConnectedOrConnecting()) { bundle = new Bundle(); bundle.putString(Intent.EXTRA_TEXT, "No network connectivity"); receiver.send(STATUS_ERROR, bundle); return; } String action = intent.getAction(); try { if (ACTION_SYNC.equals(action)) { if (receiver != null) { receiver.send(STATUS_SYNC_STATIONS, Bundle.EMPTY); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); Object result = mRemoteExecutor.executeGet( mPreferences.getString(AbstractPreferencesActivity.UPDATE_SERVER_URL, "") + "/v2/stations", new RemoteStationsSyncHandler( prefs.getLong(AbstractPreferencesActivity.STATIONS_VERSION, 0)), this); if (result == null) { // Need stations update action = ACTION_UPDATE; } else { String message = (String) result; status = STATUS_SYNC_STATIONS_FINISHED; if (!"".equals(message)) { bundle.putString(EXTRA_RESULT, message); } prefs.edit().putLong(AbstractPreferencesActivity.LAST_UPDATE, System.currentTimeMillis()) .commit(); } } if (ACTION_UPDATE.equals(action)) { if (receiver != null) { receiver.send(STATUS_UPDATE_STATIONS, Bundle.EMPTY); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); Object result = mRemoteExecutor .executeGet(mPreferences.getString(AbstractPreferencesActivity.UPDATE_SERVER_URL, "") + "/v2/stations/list", new RemoteStationsUpdateHandler(), this); status = STATUS_UPDATE_STATIONS_FINISHED; if (result != null) { bundle.putString(EXTRA_RESULT, (String) result); } prefs.edit().putLong(AbstractPreferencesActivity.LAST_UPDATE, System.currentTimeMillis()).commit(); } if (ACTION_CHOOSE_NETWORK.equals(action)) { if (receiver != null) { receiver.send(STATUS_SYNC_NETWORKS, Bundle.EMPTY); bundle = new Bundle(); bundle.putParcelableArrayList(EXTRA_RESULT, (ArrayList<Network>) mRemoteExecutor .executeGet(NETWORKS_URL, new RemoteNetworksHandler(), this)); status = STATUS_SYNC_NETWORKS_FINISHED; } } if (receiver != null) { receiver.send(status, bundle); } } catch (HandlerException e) { if (receiver != null) { // Pass back error to surface listener bundle = new Bundle(); bundle.putString(Intent.EXTRA_TEXT, e.toString()); receiver.send(STATUS_ERROR, bundle); } } catch (Exception e) { if (receiver != null) { // Pass back error to surface listener e.printStackTrace(); bundle = new Bundle(); bundle.putString(Intent.EXTRA_TEXT, "Une erreur est survenue. Veuillez ressayer."); receiver.send(STATUS_ERROR, bundle); } } }
From source file:edu.utexas.quietplaces.services.PlacesUpdateService.java
/** * {@inheritDoc}/* ww w . ja v a 2 s . co m*/ * Checks the battery and connectivity state before removing stale venues * and initiating a server poll for new venues around the specified * location within the given radius. */ @Override protected void onHandleIntent(Intent intent) { // Check if we're running in the foreground, if not, check if // we have permission to do background updates. //noinspection deprecation boolean backgroundAllowed = cm.getBackgroundDataSetting(); boolean inBackground = prefs.getBoolean(PlacesConstants.EXTRA_KEY_IN_BACKGROUND, true); if (!backgroundAllowed && inBackground) return; // Extract the location and radius around which to conduct our search. Location location = new Location(PlacesConstants.CONSTRUCTED_LOCATION_PROVIDER); int radius = PlacesConstants.PLACES_SEARCH_RADIUS; Bundle extras = intent.getExtras(); if (intent.hasExtra(PlacesConstants.EXTRA_KEY_LOCATION)) { location = (Location) (extras.get(PlacesConstants.EXTRA_KEY_LOCATION)); radius = extras.getInt(PlacesConstants.EXTRA_KEY_RADIUS, PlacesConstants.PLACES_SEARCH_RADIUS); } // Check if we're in a low battery situation. IntentFilter batIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent battery = registerReceiver(null, batIntentFilter); lowBattery = getIsLowBattery(battery); // Check if we're connected to a data network, and if so - if it's a mobile network. NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); mobileData = activeNetwork != null && activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE; // If we're not connected, enable the connectivity receiver and disable the location receiver. // There's no point trying to poll the server for updates if we're not connected, and the // connectivity receiver will turn the location-based updates back on once we have a connection. if (!isConnected) { Log.w(TAG, "Not connected!"); } else { // If we are connected check to see if this is a forced update (typically triggered // when the location has changed). boolean doUpdate = intent.getBooleanExtra(PlacesConstants.EXTRA_KEY_FORCEREFRESH, false); // If it's not a forced update (for example from the Activity being restarted) then // check to see if we've moved far enough, or there's been a long enough delay since // the last update and if so, enforce a new update. if (!doUpdate) { // Retrieve the last update time and place. long lastTime = prefs.getLong(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_TIME, Long.MIN_VALUE); float lastLat; try { lastLat = prefs.getFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LAT, Float.MIN_VALUE); } catch (ClassCastException e) { // handle legacy version lastLat = Float.MIN_VALUE; } float lastLng; try { lastLng = prefs.getFloat(PlacesConstants.SP_KEY_LAST_LIST_UPDATE_LNG, Float.MIN_VALUE); } catch (ClassCastException e) { lastLng = Float.MIN_VALUE; } Location lastLocation = new Location(PlacesConstants.CONSTRUCTED_LOCATION_PROVIDER); lastLocation.setLatitude(lastLat); lastLocation.setLongitude(lastLng); long currentTime = System.currentTimeMillis(); float distanceMovedSinceLast = lastLocation.distanceTo(location); long elapsedTime = currentTime - lastTime; Log.i(TAG, "Last Location in places update service: " + lastLocation + " distance to current: " + distanceMovedSinceLast + " - current: " + location); if (location == null) { Log.w(TAG, "Location is null..."); } // If update time and distance bounds have been passed, do an update. else if (lastTime < currentTime - PlacesConstants.MAX_TIME_BETWEEN_PLACES_UPDATE) { Log.i(TAG, "Time bounds passed on places update, " + elapsedTime / 1000 + "s elapsed"); doUpdate = true; } else if (distanceMovedSinceLast > PlacesConstants.MIN_DISTANCE_TRIGGER_PLACES_UPDATE) { Log.i(TAG, "Distance bounds passed on places update, moved: " + distanceMovedSinceLast + " meters, time elapsed: " + elapsedTime / 1000 + "s"); doUpdate = true; } else { Log.d(TAG, "Time/distance bounds not passed on places update. Moved: " + distanceMovedSinceLast + " meters, time elapsed: " + elapsedTime / 1000 + "s"); } } if (location == null) { Log.e(TAG, "null location in onHandleIntent"); } else if (doUpdate) { // Refresh the prefetch count for each new location. prefetchCount = 0; // Remove the old locations - TODO: we flush old locations, but if the next request // fails we are left high and dry removeOldLocations(location, radius); // Hit the server for new venues for the current location. refreshPlaces(location, radius, null); // Tell the main activity about the new results. Intent placesUpdatedIntent = new Intent(Config.ACTION_PLACES_UPDATED); LocalBroadcastManager.getInstance(this).sendBroadcast(placesUpdatedIntent); } else { Log.i(TAG, "Place List is fresh: Not refreshing"); } // Retry any queued checkins. /* Intent checkinServiceIntent = new Intent(this, PlaceCheckinService.class); startService(checkinServiceIntent); */ } Log.d(TAG, "Place List Download Service Complete"); }
From source file:fm.feed.android.testapp.fragment.TestFragment.java
@Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mBtnTune.setOnClickListener(tune);/*from w w w . j a v a 2s . c o m*/ mBtnPlay.setOnClickListener(play); mBtnPause.setOnClickListener(pause); mBtnSkip.setOnClickListener(skip); mBtnLike.setOnClickListener(like); mBtnUnlike.setOnClickListener(unlike); mBtnDislike.setOnClickListener(dislike); mBtnHistory.setOnClickListener(history); mPlacementsView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); mStationsView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE); mBtnToggleWifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ConnectivityManager cm = (ConnectivityManager) getActivity() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(!isConnected); // true or false to activate/deactivate wifi mBtnToggleWifi.setText(!isConnected ? "Wifi ON" : "Wifi OFF"); } }); List<HashMap<String, Integer>> fillMaps = new ArrayList<HashMap<String, Integer>>(); for (Integer p : mPlacements) { HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("Placement", p); fillMaps.add(map); } final SimpleAdapter adapter = new SimpleAdapter(getActivity(), fillMaps, android.R.layout.simple_list_item_1, new String[] { "Placement" }, new int[] { android.R.id.text1 }); mPlacementsView.setAdapter(adapter); mPlacementsView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mSelectedPlacementsIndex = position; HashMap<String, Integer> item = (HashMap<String, Integer>) adapter.getItem(position); Integer placementId = item.get("Placement"); Toast.makeText(getActivity(), placementId.toString(), Toast.LENGTH_LONG).show(); mPlayer.setPlacementId(placementId); } }); resetTrackInfo(); if (mPlayer.hasPlay()) { updateTrackInfo(mPlayer.getPlay()); } if (mPlayer.hasStationList()) { updateStations(mPlayer.getStationList()); } }
From source file:com.ideateam.plugin.Version.java
public boolean isOnline() { if (this.activity == null) this.activity = (TSVB) this.cordova.getActivity(); ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; }//from w ww . j a va2s. co m return false; }
From source file:com.tarsoft.openlibra.ollista.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // prevent the default title-bar from being displayed requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.ollista);/* www. ja v a2 s .c o m*/ //Create BBDD object DAO = new DBOpenLibra(this); //ActionBar mActionBar = (ActionBar) findViewById(R.id.actionBar); mActionBar.setTitle(R.string.app_name); // set home icon that does nothing when the user clicks on it mActionBar.setHomeLogo(R.drawable.icon); mActionBar.addActionIcon(R.drawable.refresh, new OnClickListener() { @Override public void onClick(View v) { //load data on activity adapters loadData(true); } }); mActionBar.addActionIcon(R.drawable.change, new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(ollista.this, "Clicked on an Icon Change", Toast.LENGTH_SHORT).show(); } }); // sets an action icon that displays a Toast upon clicking mActionBar.addActionIcon(R.drawable.search, new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(ollista.this, "Clicked on an Icon Search", Toast.LENGTH_SHORT).show(); } }); //Data listerMost = (ListView) findViewById(R.id.list2); if (adapterLast == null) { adapterLast = new listaOLIconArrayAdapter(ollista.this, listaLast); } //Covers gallery Gallery gallery = (Gallery) findViewById(R.id.gallery); gallery.setAdapter(adapterLast); /* gallery.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { Toast.makeText(ollista.this, "" + position, Toast.LENGTH_SHORT).show(); } }); */ //Most viewed list if (adapterMost == null) { adapterMost = new listaOLArrayAdapter(ollista.this, listaMost); } listerMost.setTextFilterEnabled(true); listerMost.setItemsCanFocus(true); listerMost.setChoiceMode(ListView.CHOICE_MODE_SINGLE); listerMost.setAdapter(adapterMost); //Evaluate Internet available try { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo checkInternet = cm.getActiveNetworkInfo(); if (checkInternet != null && checkInternet.isConnectedOrConnecting()) { checkConexion = true; } else { checkConexion = false; } } catch (Exception e) { e.printStackTrace(); Log.d(TAG, "Error when check if internet available: " + e.toString()); } //load data on activity adapters loadData(false); }
From source file:org.zywx.wbpalmstar.platform.push.PushService.java
private void onReceive() { final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"; IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(CONNECTIVITY_CHANGE_ACTION); registerReceiver(new BroadcastReceiver() { @Override// w w w .j a v a2s.c om public void onReceive(Context context, Intent intent) { if ("android.intent.action.SCREEN_OFF".equals(intent.getAction())) { if (isTemporary) { sleepTime = 1000 * 60 * 2; } else { sleepTime = 1000 * 60 * 15; } notifiTimer(); } else if ("android.intent.action.SCREEN_ON".equals(intent.getAction())) { if (isTemporary) { sleepTime = 1000 * 30; } else { sleepTime = 1000 * 60 * 2; } notifiTimer(); } if (TextUtils.equals(intent.getAction(), CONNECTIVITY_CHANGE_ACTION)) { ConnectivityManager mConnMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (mConnMgr != null) { NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo(); // ?? if (aActiveInfo != null && aActiveInfo.isConnectedOrConnecting()) { if (!isSend && aActiveInfo.getType() == ConnectivityManager.TYPE_WIFI) { // udpReg(); // notifiUDPTimer(); isSend = true; } } else { isSend = false; } } else { isSend = false; } } } }, filter); }
From source file:com.ideateam.plugin.Version.java
public boolean isOnline() { if (this.activity == null) this.activity = (UAR2015) this.cordova.getActivity(); ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; }/*from w w w. j a v a 2s . c o m*/ return false; }
From source file:com.gtx.cooliris.imagecache.ImageFetcher.java
/** * Simple network connection check.// w ww.j av a2 s . co m * * @param context */ private void checkConnection(Context context) { final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) { Toast.makeText(context, R.string.toast_no_network_connection_toast, Toast.LENGTH_LONG).show(); LogUtil.e(TAG, "checkConnection - no connection found"); } }
From source file:org.gots.ui.TabSeedActivity.java
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { String cameraFilename = savedInstanceState.getString("CAMERA_FILENAME"); if (cameraFilename != null) cameraPicture = new File(cameraFilename); }/*from w w w.jav a 2 s . c o m*/ gotsPurchase = new GotsPurchaseItem(this); GotsAnalytics.getInstance(getApplication()).incrementActivityCount(); GoogleAnalyticsTracker.getInstance().trackPageView(getClass().getSimpleName()); setContentView(R.layout.seed_tab); ActionBar bar = getSupportActionBar(); bar.setDisplayHomeAsUpEnabled(true); // bar.setDisplayShowTitleEnabled(false); getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // ********************** ********************** if (getIntent().getExtras() == null) { Log.e("SeedActivity", "You must provide a org.gots.seed.id as an Extra Int"); finish(); return; } if (getIntent().getExtras().getInt(GOTS_GROWINGSEED_ID) != 0) { int seedId = getIntent().getExtras().getInt(GOTS_GROWINGSEED_ID); mSeed = GotsGrowingSeedManager.getInstance().initIfNew(this).getGrowingSeedById(seedId); } else if (getIntent().getExtras().getInt(GOTS_VENDORSEED_ID) != 0) { int seedId = getIntent().getExtras().getInt(GOTS_VENDORSEED_ID); GotsSeedProvider helper = new LocalSeedProvider(getApplicationContext()); mSeed = (GrowingSeedInterface) helper.getSeedById(seedId); } else mSeed = new GrowingSeed(); // DEFAULT SEED // if (getIntent().getSerializableExtra(GOTS_TASKWORKFLOW_ID) != null) // taskWorkflow = (TaskInfo) getIntent().getSerializableExtra(GOTS_TASKWORKFLOW_ID); pictureGallery = (Gallery) findViewById(R.id.idPictureGallery); displayPictureGallery(); pictureGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { File f = (File) arg0.getItemAtPosition(position); File dest = new File(gotsPrefs.getGotsExternalFileDir(), f.getName()); try { FileUtilities.copy(f, dest); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(dest), "image/*"); startActivity(intent); } catch (IOException e) { Log.w(TAG, e.getMessage()); } } }); bar.setTitle(mSeed.getSpecie()); SeedWidgetLong seedWidget = (SeedWidgetLong) findViewById(R.id.IdSeedWidgetLong); seedWidget.setSeed(mSeed); if (mSeed.getDateSowing() != null) { TextView textDateSowing = (TextView) findViewById(R.id.idTextSowingDate); textDateSowing.setText(new SimpleDateFormat().format(mSeed.getDateSowing())); TextView textDateHarvest = (TextView) findViewById(R.id.idTextHarvestDate); if (mSeed.getDateHarvest().getTime() > 0) textDateHarvest.setText(new SimpleDateFormat().format(mSeed.getDateHarvest())); else { Calendar plannedHarvest = Calendar.getInstance(); plannedHarvest.setTime(mSeed.getDateSowing()); plannedHarvest.add(Calendar.DAY_OF_YEAR, mSeed.getDurationMin()); textDateHarvest.setText(new SimpleDateFormat().format(plannedHarvest.getTime())); textDateHarvest.setAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.tween)); } } else findViewById(R.id.idLayoutCulturePeriod).setVisibility(View.GONE); mViewPager = (ViewPager) findViewById(R.id.pager); TabsAdapter mTabsAdapter = new TabsAdapter(this, mViewPager); // ********************** Tab actions ********************** if (mSeed.getGrowingSeedId() > 0) { mTabsAdapter.addTab( bar.newTab().setTag("event_list").setText(getString(R.string.seed_description_tabmenu_actions)), ListActionActivity.class, null); } // // ********************** Tab description ********************** mTabsAdapter.addTab( bar.newTab().setTag("event_list").setText(getString(R.string.seed_description_tabmenu_detail)), SeedActivity.class, null); // ********************** Tab Wikipedia********************** ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { mTabsAdapter.addTab(bar.newTab().setTag("event_list") .setText(getString(R.string.seed_description_tabmenu_wikipedia)), WebViewActivity.class, null); urlDescription = "http://" + Locale.getDefault().getLanguage() + ".wikipedia.org/wiki/" + mSeed.getSpecie(); } if (!gotsPurchase.isPremium()) { GotsAdvertisement ads = new GotsAdvertisement(this); LinearLayout layout = (LinearLayout) findViewById(R.id.idAdsTop); layout.addView(ads.getAdsLayout()); } Fragment fragment = new WorkflowTaskFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.frame_workflow, fragment).commit(); }
From source file:com.appnexus.opensdk.AdRequest.java
private boolean hasNetwork(Context context) { if (context != null) { NetworkInfo ninfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)) .getActiveNetworkInfo(); if (ninfo != null && ninfo.isConnectedOrConnecting()) { return true; }/*from ww w . j a v a2 s.co m*/ } return false; }