Example usage for android.net ConnectivityManager getNetworkInfo

List of usage examples for android.net ConnectivityManager getNetworkInfo

Introduction

In this page you can find the example usage for android.net ConnectivityManager getNetworkInfo.

Prototype

@Deprecated
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
@Nullable
public NetworkInfo getNetworkInfo(@Nullable Network network) 

Source Link

Document

Returns connection status information about a particular Network.

Usage

From source file:uk.co.senab.photoview.sample.ViewPagerActivity.java

public static boolean internetIsConnected(final Activity activity) {

    boolean connected = false;

    // Get connect mangaer
    final ConnectivityManager connMgr = (ConnectivityManager) activity
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    // check for wifi
    final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    // check for mobile data
    final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isAvailable()) {

        connected = true;/*from  w ww  . java2s.com*/

    } else if (mobile.isAvailable()) {

        connected = true;

    } else {

        connected = false;
    }

    return connected;

}

From source file:org.dvbviewer.controller.ui.fragments.ChannelList.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = getActivity().getApplicationContext();

    ConnectivityManager connManager = (ConnectivityManager) getActivity()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    mNetworkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    prefs = new DVBViewerPreferences(getActivity());
    showFavs = prefs.getPrefs().getBoolean(DVBViewerPreferences.KEY_CHANNELS_USE_FAVS, false);
    showNowPlaying = prefs.getPrefs().getBoolean(DVBViewerPreferences.KEY_CHANNELS_SHOW_NOW_PLAYING, true);
    showNowPlayingWifi = prefs.getPrefs()
            .getBoolean(DVBViewerPreferences.KEY_CHANNELS_SHOW_NOW_PLAYING_WIFI_ONLY, true);
    mAdapter = new ChannelAdapter(getActivity());
    if (getArguments() != null) {
        if (getArguments().containsKey(ChannelList.KEY_HAS_OPTIONMENU)) {
            hasOptionsMenu = getArguments().getBoolean(KEY_HAS_OPTIONMENU);
        }//from w w  w .j av a2  s . c  o m
    }
    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(KEY_SELECTED_POSITION)) {
            selectedPosition = savedInstanceState.getInt(KEY_SELECTED_POSITION);
        }
    } else {
        selectedPosition = getActivity().getIntent().getIntExtra(KEY_SELECTED_POSITION, selectedPosition);
    }
    setHasOptionsMenu(hasOptionsMenu);
}

From source file:de.jeanpierrehotz.messaging.androidclient.MainActivity.java

/**
 * Diese Methode ermittelt, ob derzeit Internet verfgbar ist.
 *
 * @return ob Internet verfgbar ist//from  w  w  w .  jav  a  2s  .com
 */
private boolean isInternetConnectionAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    Network[] networks = manager.getAllNetworks();
    for (Network net : networks) {
        if (manager.getNetworkInfo(net).isAvailable()) {
            return true;
        }
    }
    return false;
}

From source file:com.dwdesign.tweetings.activity.HomeActivity.java

public void connectToStream() {
    if (mPreferences.getBoolean(PREFERENCE_KEY_STREAMING_ENABLED, false) == true) {
        if (mService != null && twitterStream != null) {
            try {
                // user() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null) {
                    if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
                        hasStreamLoaded = true;
                        twitterStream.user();
                        if (mPreferences.getBoolean(PREFERENCE_KEY_STREAMING_NOTIFICATION, false) == true) {
                            NotificationManager notificationManager = (NotificationManager) getSystemService(
                                    Context.NOTIFICATION_SERVICE);
                            final Intent intent = new Intent(this, HomeActivity.class);
                            final Notification.Builder builder = new Notification.Builder(this);
                            builder.setOngoing(true);
                            builder.setContentIntent(PendingIntent.getActivity(this, 0, intent,
                                    PendingIntent.FLAG_UPDATE_CURRENT));
                            builder.setSmallIcon(R.drawable.ic_launcher);
                            builder.setContentTitle(getString(R.string.app_name));
                            builder.setContentText(getString(R.string.streaming_service_running));
                            builder.setTicker(getString(R.string.streaming_service_running));
                            notificationManager.notify(NOTIFICATION_ID_STREAMING, builder.build());
                        }/*from w ww.  j a v  a  2  s.c o  m*/
                    }
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.uguess.android.sysinfo.NetStateManager.java

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    if (position > 0) {
        int state = Util.getIntOption(getActivity(), PSTORE_NETMANAGER, PREF_KEY_REMOTE_QUERY, ENABLED);

        if (state == DISABLED) {
            return;
        } else if (state == WIFI_ONLY) {
            ConnectivityManager cm = (ConnectivityManager) getActivity()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (info == null || !info.isConnected()) {
                return;
            }// w  w w  .j av  a 2  s.  c o m
        }

        ConnectionItem itm = (ConnectionItem) l.getItemAtPosition(position);

        String ip = getValidIP(itm.remote);

        if (!TextUtils.isEmpty(ip)) {
            queryIPInfo(ip);
        } else {
            Util.shortToast(getActivity(), R.string.no_ip_info);
        }
    }
}

From source file:cx.ring.service.LocalService.java

private void updateConnectivityState() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    Log.w(TAG, "ActiveNetworkInfo (Wifi): " + (ni == null ? "null" : ni.toString()));
    isWifiConn = ni != null && ni.isConnected();

    ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    Log.w(TAG, "ActiveNetworkInfo (mobile): " + (ni == null ? "null" : ni.toString()));
    isMobileConn = ni != null && ni.isConnected();

    try {/*from www .  java2s.c o m*/
        getRemoteService().setAccountsActive(isConnected());
    } catch (RemoteException e) {
        e.printStackTrace();
    }

    // if account list loaded
    if (!ip2ip_account.isEmpty())
        sendBroadcast(new Intent(ACTION_ACCOUNT_UPDATE));
}

From source file:cx.ring.service.LocalService.java

@Override
public void onCreate() {
    Log.e(TAG, "onCreate");
    super.onCreate();

    mediaManager = new MediaManager(this);

    notificationManager = NotificationManagerCompat.from(this);

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<Long, Bitmap>(cacheSize) {
        @Override//from   w  w w.ja v  a 2  s. co m
        protected int sizeOf(Long key, Bitmap bitmap) {
            return bitmap.getByteCount() / 1024;
        }
    };

    historyManager = new HistoryManager(this);
    Intent intent = new Intent(this, DRingService.class);
    startService(intent);
    bindService(intent, mConnection, BIND_AUTO_CREATE | BIND_IMPORTANT | BIND_ABOVE_CLIENT);

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    isWifiConn = ni != null && ni.isConnected();
    ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    isMobileConn = ni != null && ni.isConnected();

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    canUseContacts = sharedPreferences.getBoolean(SettingsFragment.KEY_PREF_CONTACTS, true);
    canUseMobile = sharedPreferences.getBoolean(SettingsFragment.KEY_PREF_MOBILE, true);
    sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}

From source file:fr.univsavoie.ltp.client.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Appliquer le thme LTP a l'ActionBar
    //setTheme(R.style.Theme_ltp);

    // Cration de l'activit principale
    setContentView(R.layout.activity_main);

    // Instancier les classes utiles
    setPopup(new Popup(this));
    setSession(new Session(this));
    setTools(new Tools(this));

    // Afficher la ActionBar
    ActionBar mActionBar = getSupportActionBar();
    mActionBar.setHomeButtonEnabled(true);
    mActionBar.setDisplayShowHomeEnabled(true);

    // MapView settings
    map = (MapView) findViewById(R.id.openmapview);
    map.setTileSource(TileSourceFactory.MAPNIK);
    map.setBuiltInZoomControls(false);/*from   www .  ja v a  2s .  co m*/
    map.setMultiTouchControls(true);

    // MapController settings
    mapController = map.getController();

    //To use MapEventsReceiver methods, we add a MapEventsOverlay:
    overlay = new MapEventsOverlay(this, this);
    map.getOverlays().add(overlay);

    boolean isWifiEnabled = false;
    boolean isGPSEnabled = false;

    // Vrifier si le wifi ou le rseau mobile est activ
    final ConnectivityManager connMgr = (ConnectivityManager) this
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    final NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (wifi.isAvailable() && (wifi.getDetailedState() == DetailedState.CONNECTING
            || wifi.getDetailedState() == DetailedState.CONNECTED)) {
        Toast.makeText(this, R.string.toast_wifi, Toast.LENGTH_LONG).show();
        isWifiEnabled = true;
    } else if (mobile.isAvailable() && (mobile.getDetailedState() == DetailedState.CONNECTING
            || mobile.getDetailedState() == DetailedState.CONNECTED)) {
        Toast.makeText(this, R.string.toast_3G, Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, R.string.toast_aucun_reseau, Toast.LENGTH_LONG).show();
    }

    // Obtenir le service de localisation
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // Verifier si le service de localisation GPS est actif, le cas echeant, tester le rseau
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 250.0f, this);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        isGPSEnabled = true;
    } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30 * 1000, 250.0f, this);
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }

    // Afficher une boite de dialogue et proposer d'activer un ou plusieurs services pas actifs
    if (!isWifiEnabled || !isGPSEnabled) {
        //getTools().showSettingsAlert(this, isWifiEnabled, isGPSEnabled);
    }

    // Si on a une localisation, on dfinit ses coordonnes geopoint
    if (location != null) {
        startPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
    } else {
        // Sinon, on indique des paramtres par dfaut
        location = getTools().getLastKnownLocation(locationManager);
        if (location == null) {
            location = new Location("");
            location.setLatitude(46.227638);
            location.setLongitude(2.213749000000);
        }
        startPoint = new GeoPoint(46.227638, 2.213749000000);
    }

    setLongitude(location.getLongitude());
    setLatitude(location.getLatitude());

    destinationPoint = null;
    viaPoints = new ArrayList<GeoPoint>();

    // On recupre quelques paramtres de la session prcdents si possible
    if (savedInstanceState == null) {
        mapController.setZoom(15);
        mapController.setCenter(startPoint);
    } else {
        mapController.setZoom(savedInstanceState.getInt("zoom_level"));
        mapController.setCenter((GeoPoint) savedInstanceState.getParcelable("map_center"));
    }

    // Crer un overlay sur la carte pour afficher notre point de dpart
    myLocationOverlay = new SimpleLocationOverlay(this, new DefaultResourceProxyImpl(this));
    map.getOverlays().add(myLocationOverlay);
    myLocationOverlay.setLocation(startPoint);

    // Boutton pour zoomer la carte
    ImageButton btZoomIn = (ImageButton) findViewById(R.id.btZoomIn);
    btZoomIn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            map.getController().zoomIn();
        }
    });

    // Boutton pour dezoomer la carte
    ImageButton btZoomOut = (ImageButton) findViewById(R.id.btZoomOut);
    btZoomOut.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            map.getController().zoomOut();
        }
    });

    // Pointeurs d'itinrairea:
    final ArrayList<ExtendedOverlayItem> waypointsItems = new ArrayList<ExtendedOverlayItem>();
    itineraryMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, waypointsItems, map,
            new ViaPointInfoWindow(R.layout.itinerary_bubble, map));
    map.getOverlays().add(itineraryMarkers);
    //updateUIWithItineraryMarkers();

    Button searchButton = (Button) findViewById(R.id.buttonSearch);
    searchButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            handleSearchLocationButton();
        }
    });

    //context menu for clicking on the map is registered on this button. 
    registerForContextMenu(searchButton);

    // Routes et Itinraires
    final ArrayList<ExtendedOverlayItem> roadItems = new ArrayList<ExtendedOverlayItem>();
    roadNodeMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, roadItems, map);
    map.getOverlays().add(roadNodeMarkers);

    if (savedInstanceState != null) {
        mRoad = savedInstanceState.getParcelable("road");
        updateUIWithRoad(mRoad);
    }

    //POIs:
    //POI search interface:
    String[] poiTags = getResources().getStringArray(R.array.poi_tags);
    poiTagText = (AutoCompleteTextView) findViewById(R.id.poiTag);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
            poiTags);
    poiTagText.setAdapter(adapter);
    Button setPOITagButton = (Button) findViewById(R.id.buttonSetPOITag);
    setPOITagButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //Hide the soft keyboard:
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(poiTagText.getWindowToken(), 0);
            //Start search:
            getPOIAsync(poiTagText.getText().toString());
        }
    });

    //POI markers:
    final ArrayList<ExtendedOverlayItem> poiItems = new ArrayList<ExtendedOverlayItem>();
    poiMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, poiItems, map,
            new POIInfoWindow(map));
    map.getOverlays().add(poiMarkers);
    if (savedInstanceState != null) {
        mPOIs = savedInstanceState.getParcelableArrayList("poi");
        updateUIWithPOI(mPOIs);
    }

    // Load friends ListView
    lvListeFriends = (ListView) findViewById(R.id.listViewFriends);
    //lvListeFriends.setBackgroundResource(R.drawable.listview_roundcorner_item);
    lvListeFriends.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
            Friends item = (Friends) adapter.getItemAtPosition(position);
            if (item.getLongitude() != 0.0 && item.getLatitude() != 0.0) {
                destinationPoint = new GeoPoint(item.getLongitude(), item.getLatitude());
                markerDestination = putMarkerItem(markerDestination, destinationPoint, DEST_INDEX,
                        R.string.destination, R.drawable.marker_destination, -1);
                getRoadAsync();
                map.getController().setCenter(destinationPoint);
            } else {
                Toast.makeText(MainActivity.this, R.string.toast_friend_statut, Toast.LENGTH_LONG).show();
            }
        }
    });

    viewMapFilters = (ScrollView) this.findViewById(R.id.scrollViewMapFilters);
    viewMapFilters.setVisibility(View.GONE);

    // Initialiser tout ce qui est donnes utilisateur propres  l'activit
    init();

    getTools().relocateUser(mapController, map, myLocationOverlay, location);
}

From source file:com.gpsmobitrack.gpstracker.MenuItems.SettingsPage.java

public final boolean isInternetOn() {
    ConnectivityManager connec = (ConnectivityManager) getActivity()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
            || connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
        return true;
    } else if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
            || connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
        return false;
    }/*  w  w w  .j  ava  2s  . c o m*/
    return false;
}

From source file:dev.ukanth.ufirewall.Api.java

public static boolean isMobileNetworkSupported(final Context ctx) {
    boolean hasMobileData = true;
    ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm != null) {
        if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
            hasMobileData = false;/*from w ww .  j  av  a 2 s  .c  o  m*/
        }
    }
    return hasMobileData;
}