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:org.sociotech.fishification.ui.MainActivity.java

/**
 * Checks for WiFi connection and if SSID is allowed.
 *
 * @return If Wifi connection check was successful.
 *//*from w ww.jav  a  2s  .  c  o  m*/
private boolean checkWifiConnection() {
    if (!m_wifiCheck) {
        return true;
    }

    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo.State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
    if (wifi == NetworkInfo.State.CONNECTED) {
        if (m_wifiSSIDs.length == 0) {
            return true;
        }

        WifiManager wifiMgr = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();

        String ssid = wifiInfo.getSSID().replace("\"", "").trim();
        for (String s : m_wifiSSIDs) {
            if (ssid.equalsIgnoreCase(s.trim())) {
                return true;
            }
        }

        Toast.makeText(this, "Not connected to allowed WiFi zones.", Toast.LENGTH_LONG);
        return false;
    }

    Toast.makeText(this, "No WiFi connection available.", Toast.LENGTH_LONG);
    return false;
}

From source file:com.example.testapplication.DialogLocation.java

@SuppressLint("InlinedApi")
@Override//from   w w w  .j  a va2 s .  co m
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mProgressBar = new ProgressBar(getActivity(), null, android.R.attr.progressBarStyleLarge);
    mProgressBarInv = new ProgressBar(getActivity(), null, android.R.attr.progressBarStyleLarge);
    mProgressBarInv.setVisibility(ProgressBar.GONE);

    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

    mCriteria = new Criteria();
    int criteria = (mGpsPref) ? Criteria.POWER_HIGH : Criteria.POWER_MEDIUM;
    mCriteria.setPowerRequirement(criteria);

    mProvider = mLocationManager.getBestProvider(mCriteria, true);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
    int telephonyInfo = tm.getNetworkType();

    boolean networkAvailable = true;

    if ((telephonyInfo == TelephonyManager.NETWORK_TYPE_UNKNOWN && !networkInfo.isConnected())
            || !mLocationManager.isProviderEnabled("network")) {
        networkAvailable = false;
    }

    int locationMode = -1;
    int locationType = -1;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        try {
            locationMode = Settings.Secure.getInt(getActivity().getContentResolver(),
                    Settings.Secure.LOCATION_MODE);
        } catch (SettingNotFoundException e) {
            e.printStackTrace();
        }

        if (locationMode == Settings.Secure.LOCATION_MODE_OFF
                || (!networkAvailable && (mProvider.matches("network"))))
            locationType = NO_LOCATION_SERVICES;
        else if (mGpsPref && (locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY
                || locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY))
            locationType = (locationMode == Settings.Secure.LOCATION_MODE_SENSORS_ONLY || !networkAvailable)
                    ? USING_ONLY_GPS_LOCATION
                    : USING_GPS_LOCATION_NETWORK_AVAILABLE;
        else if (mProvider.matches("network") && (locationMode == Settings.Secure.LOCATION_MODE_BATTERY_SAVING
                || locationMode == Settings.Secure.LOCATION_MODE_HIGH_ACCURACY))
            locationType = USING_NETWORK_LOCATION;

    } else {
        if (mProvider.matches("passive") || !networkAvailable
                && (mProvider.matches("network") || (!mGpsPref && mProvider.matches("gps"))))
            locationType = NO_LOCATION_SERVICES;
        else if (mProvider.matches("gps") && mGpsPref)
            locationType = ((mProvider.matches("gps")) || !networkAvailable) ? USING_ONLY_GPS_LOCATION
                    : USING_GPS_LOCATION_NETWORK_AVAILABLE;
        else if (mProvider.matches("network"))
            locationType = USING_NETWORK_LOCATION;
    }

    switch (locationType) {
    case NO_LOCATION_SERVICES:
        builder.setTitle(DIALOG_LOCATION_NO_LOCATION_SERVICES_TITLE);
        builder.setMessage(DIALOG_LOCATION_NO_LOCATION_SERVICES_MESSAGE);
        builder.setNeutralButton(DIALOG_LOCATION_BUTTON_SETTINGS, noNetworkButton);
        mAbortRequest = true;
        break;
    case USING_ONLY_GPS_LOCATION:
        builder.setTitle(DIALOG_LOCATION_UPDATING_GPS_TITLE);
        builder.setMessage(DIALOG_LOCATION_ONLY_GPS_MESSAGE);
        builder.setNeutralButton(DIALOG_LOCATION_BUTTON_SETTINGS, noNetworkButton);
        builder.setView(mProgressBar);
        break;
    case USING_GPS_LOCATION_NETWORK_AVAILABLE:
        builder.setTitle(DIALOG_LOCATION_UPDATING_GPS_TITLE);
        builder.setPositiveButton(DIALOG_LOCATION_USE_NETWORK, null);
        builder.setView(mProgressBar);
        break;
    case USING_NETWORK_LOCATION:
        builder.setView(mProgressBar);
        builder.setTitle(DIALOG_LOCATION_UPDATING_NETWORK_TITLE);
        break;
    }

    builder.setNegativeButton(DIALOG_LOCATION_CANCEL, cancelListener);
    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mCallback.onLocationFound(null, mFragmentId);
                mLocationManager.removeUpdates(DialogLocation.this);
                Toast.makeText(getActivity(), "Location request cancelled", Toast.LENGTH_SHORT).show();
                dialog.cancel();
                return true;
            }
            return false;
        }
    });

    mRealDialog = builder.create();
    mRealDialog.setOnShowListener(usingNetwork);
    mRealDialog.setCanceledOnTouchOutside(false);
    return mRealDialog;
}

From source file:net.net76.lifeiq.TaskiQ.RegisterActivity.java

public boolean isNetworkAvaliable(Context ctx) {
    ConnectivityManager connectivityManager = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if ((connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
            || (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)) {
        return true;
    } else {/*from  w w  w . j  ava2  s .c om*/
        return false;
    }
}

From source file:com.error.hunter.ListenService.java

private StringBuffer getNetworkInfo() {
    StringBuffer info = new StringBuffer();
    StringBuffer backUpInfo = new StringBuffer();

    final ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if (wifi.isConnected()) {
        info.append("\nWiFi network state: CONNECTED");
    } else {/*from   w  ww  . j a v a2  s. co  m*/
        info.append("\nWiFi network state: NOT CONNECTED");
    }
    backUpInfo = new StringBuffer(info);
    try {
        if (!mobile.isConnected()) {
            switch (mobile.getSubtype()) {
            case TelephonyManager.NETWORK_TYPE_GPRS:
                info.append("\nMobile network state: CONNECTED (GPRS)");
                break;
            case TelephonyManager.NETWORK_TYPE_EDGE:
                info.append("\nMobile network state: CONNECTED (EDGE)");
                break;
            case TelephonyManager.NETWORK_TYPE_CDMA:
                info.append("\nMobile network state: CONNECTED (CDMA)");
                break;
            case TelephonyManager.NETWORK_TYPE_HSPA:
                info.append("\nMobile network state: CONNECTED (HSPA)");
                break;
            case TelephonyManager.NETWORK_TYPE_HSPAP:
                info.append("\nMobile network state: CONNECTED (HSPA+)");
                break;
            case TelephonyManager.NETWORK_TYPE_LTE:
                info.append("\nMobile network state: CONNECTED (LTE)");
                break;
            case TelephonyManager.NETWORK_TYPE_UMTS:
                info.append("\nMobile network state: CONNECTED (UMTS)");
                break;
            }
        } else {
            info.append("\nMobile network state: NOT CONNECTED");
        }
    } catch (Exception e) {
        e.printStackTrace();
        return backUpInfo;
    }
    return info;
}

From source file:com.nearnotes.NoteLocation.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    Bundle extras = getArguments();//w ww . ja  va 2s. co  m
    mTypeFrag = extras.getInt("TypeFrag");

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    Boolean gpsPref = sharedPref.getBoolean("pref_key_ignore_gps", false);
    mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    mCriteria = new Criteria();
    if (gpsPref) {
        mCriteria.setPowerRequirement(Criteria.POWER_HIGH);
    } else
        mCriteria.setPowerRequirement(Criteria.POWER_MEDIUM);
    mProvider = mLocationManager.getBestProvider(mCriteria, true);
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    boolean oldApi = false;
    int locationMode = 4;
    Log.e("mProvider", mProvider);

    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    boolean networkAvailable = true;

    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
    boolean networkType = true;
    if (tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_UNKNOWN && !networkInfo.isConnected()) {
        networkType = false;
    }

    Log.d("Phone state before if statement", "Phone State: " + mServiceState);
    Log.e("network isavailable", String.valueOf(networkInfo.isAvailable()));
    if (!networkType || !mLocationManager.isProviderEnabled("network")) {
        networkAvailable = false;
    }

    try {
        Log.e("Location_mode", String.valueOf(
                Settings.Secure.getInt(getActivity().getContentResolver(), Settings.Secure.LOCATION_MODE)));
        locationMode = Settings.Secure.getInt(getActivity().getContentResolver(),
                Settings.Secure.LOCATION_MODE);
    } catch (SettingNotFoundException e) {
        oldApi = true;
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if ((oldApi && mProvider.matches("passive")) || locationMode == LOCATION_MODE_OFF || (!networkAvailable
            && (mProvider.matches("network") || (!gpsPref && mProvider.matches("gps"))))) {
        builder.setTitle(getString(R.string.dialog_location_no_location_services_title));
        builder.setMessage(getString(R.string.dialog_location_no_location_services_message));
        builder.setNeutralButton(R.string.dialog_location_button_settings, noNetworkButton);
        mAbortRequest = true;
    } else if ((oldApi && mProvider.matches("gps") && gpsPref) || (mProvider.matches("gps") && gpsPref
            && (locationMode == LOCATION_MODE_SENSORS_ONLY || locationMode == LOCATION_MODE_HIGH_ACCURACY))) {
        if (mTypeFrag == NOTE_EDIT) {
            builder.setTitle(getString(R.string.dialog_location_finding_note_gps));
        } else if (mTypeFrag == NOTE_LIST) {
            builder.setTitle(getString(R.string.dialog_location_updating_note_gps));
        }
        if (locationMode == LOCATION_MODE_SENSORS_ONLY || (oldApi && mProvider.matches("gps"))
                || !networkAvailable) {
            builder.setMessage(getString(R.string.dialog_location_only_gps_message));
            builder.setNeutralButton(R.string.dialog_location_button_settings, noNetworkButton);

        } else
            builder.setPositiveButton(R.string.dialog_location_use_network, null);

        builder.setView(getActivity().getLayoutInflater().inflate(R.layout.dialogue_location, null));

    } else if ((oldApi && mProvider.matches("network")) || (mProvider.matches("network")
            && (locationMode == LOCATION_MODE_BATTERY_SAVING || locationMode == LOCATION_MODE_HIGH_ACCURACY))) {
        builder.setView(getActivity().getLayoutInflater().inflate(R.layout.dialogue_location, null));
        if (mTypeFrag == NOTE_EDIT) {
            builder.setTitle(getString(R.string.dialog_location_finding_note_network));
        } else if (mTypeFrag == NOTE_LIST) {
            builder.setTitle(getString(R.string.dialog_location_updating_note_network));
        }

    }
    builder.setNegativeButton(R.string.cancel, cancelListener);
    // Create the AlertDialog object and return it

    // builder.create();

    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {

        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mCallback.onLocationFound(null, mTypeFrag);
                mLocationManager.removeUpdates(NoteLocation.this);
                Toast.makeText(getActivity(), "Location request cancelled", Toast.LENGTH_SHORT).show();
                dialog.cancel();
                return true;
            }

            return false;
        }
    });

    mRealDialog = builder.create();
    // final LocationListener getFragment() = this.;

    mRealDialog.setOnShowListener(usingNetwork);
    mRealDialog.setCanceledOnTouchOutside(false);
    // mRealDialog.setCancelable(false);
    return mRealDialog;

}

From source file:org.cirdles.chroni.ImportFilesActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handles menu item selection
    switch (item.getItemId()) {
    case R.id.exitMenu:
        finish();/* w  w w.ja v  a 2 s  . c om*/
        return true;

    case R.id.helpMenu: // Takes user to help blog
        // Checks internet connection before downloading files
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mobileWifi.isConnected()) {
            Intent openHelpBlog = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(getString(R.string.chroni_help_address)));
            startActivity(openHelpBlog);

        } else {
            new AlertDialog.Builder(this)
                    .setMessage("You are not connected to WiFi, mobile data rates may apply. "
                            + "Do you wish to continue?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent openHelpBlog = new Intent(Intent.ACTION_VIEW,
                                    Uri.parse(getString(R.string.chroni_help_address)));
                            startActivity(openHelpBlog);
                        }
                    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).show();
        }
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

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  .  jav  a  2s.co  m
    }

    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:biz.shadowservices.DegreesToolbox.DataFetcher.java

public boolean isWifi(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (info == null) {
        return false;
    } else {/* ww w .  j av a  2  s .c o m*/
        return info.isConnected();
    }
}

From source file:biz.shadowservices.DegreesToolbox.DataFetcher.java

public boolean isRoaming(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (info == null) {
        return false;
    } else {//ww w.  j  a v a2 s.  c o  m
        return info.isRoaming();
    }
}

From source file:de.tu_berlin.snet.probe.FacebookProbe.java

private boolean isAvailable() {
    ConnectivityManager connMgr = (ConnectivityManager) getContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = connMgr.getActiveNetworkInfo();

    if (!wifiOnly && netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else if (wifiOnly) {
        NetworkInfo.State wifiInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        if (NetworkInfo.State.CONNECTED.equals(wifiInfo) || NetworkInfo.State.CONNECTING.equals(wifiInfo))
            return true;
    }//from  w  ww .j  ava 2s  .com
    return false;
}