Example usage for android.net NetworkInfo isConnectedOrConnecting

List of usage examples for android.net NetworkInfo isConnectedOrConnecting

Introduction

In this page you can find the example usage for android.net NetworkInfo isConnectedOrConnecting.

Prototype

@Deprecated
public boolean isConnectedOrConnecting() 

Source Link

Document

Indicates whether network connectivity exists or is in the process of being established.

Usage

From source file:org.exobel.routerkeygen.ui.Preferences.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    getActionBar().setDisplayHomeAsUpEnabled(true);

    findPreference("download").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            if (isDictionaryServiceRunning()) {
                Toast.makeText(getBaseContext(), getString(R.string.pref_msg_download_running),
                        Toast.LENGTH_SHORT).show();
                return true;
            }/*from   ww w  .j  a  va 2  s. c om*/
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo == null || !netInfo.isConnectedOrConnecting()) {
                Toast.makeText(getBaseContext(), getString(R.string.pref_msg_no_network), Toast.LENGTH_SHORT)
                        .show();
                return true;
            }

            // Don't complain about dictionary size if user is on a
            // wifi connection
            if ((((WifiManager) getBaseContext().getSystemService(Context.WIFI_SERVICE))).getConnectionInfo()
                    .getSSID() != null) {
                try {
                    checkCurrentDictionary();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            } else
                showDialog(DIALOG_ASK_DOWNLOAD);
            return true;
        }
    });

    //        boolean app_installed = AdsUtils.checkDonation(this);
    final PreferenceCategory mCategory = (PreferenceCategory) findPreference("2section");
    //        if (!app_installed) {
    //            mCategory.removePreference(findPreference("analytics_enabled"));
    //            // If you haven't the donate app installed remove the paypal donate
    //            // link.
    //            mCategory.removePreference(findPreference("donate_paypal"));
    //            findPreference("donate_playstore").setOnPreferenceClickListener(
    //                    new OnPreferenceClickListener() {
    //                        public boolean onPreferenceClick(Preference preference) {
    //                            try {
    //                                startActivity(new Intent(Intent.ACTION_VIEW,
    //                                        Uri.parse("market://details?id="
    //                                                + GOOGLE_PLAY_DOWNLOADER)));
    //                            } catch (android.content.ActivityNotFoundException anfe) {
    //                                startActivity(new Intent(
    //                                        Intent.ACTION_VIEW,
    //                                        Uri.parse("http://play.google.com/store/apps/details?id="
    //                                                + GOOGLE_PLAY_DOWNLOADER)));
    //                            }
    //                            Toast.makeText(getApplicationContext(),
    //                                    R.string.msg_donation, Toast.LENGTH_LONG)
    //                                    .show();
    //                            return true;
    //                        }
    //                    });
    //        } else {
    //            // If you have the donate app installed no need to link to it.
    //            mCategory.removePreference(findPreference("donate_playstore"));
    //            if (BuildConfig.APPLICATION_ID.equals("io.github.routerkeygen")) {
    //                //Play Store is quite restrictive nowadays
    //                mCategory.removePreference(findPreference("donate_paypal"));
    //            } else {
    //                findPreference("donate_paypal").setOnPreferenceClickListener(
    //                        new OnPreferenceClickListener() {
    //                            public boolean onPreferenceClick(Preference preference) {
    //                                final String donateLink = "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=V3FFBTRTTV5DN";
    //                                Uri uri = Uri.parse(donateLink);
    //                                startActivity(new Intent(Intent.ACTION_VIEW, uri));
    //
    //                                return true;
    //                            }
    //                        });
    //            }
    //        }
    if (BuildConfig.APPLICATION_ID.equals("io.github.routerkeygen")) {
        mCategory.removePreference(findPreference("update"));
    } else {
        findPreference("update").setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                    protected void onPreExecute() {
                        showDialog(DIALOG_WAIT);
                    }

                    protected Void doInBackground(Void... params) {
                        lastVersion = UpdateCheckerService.getLatestVersion();
                        return null;
                    }

                    protected void onPostExecute(Void result) {
                        removeDialog(DIALOG_WAIT);
                        if (isFinishing())
                            return;
                        if (lastVersion == null) {
                            showDialog(DIALOG_ERROR);
                            return;
                        }
                        if (!Preferences.VERSION.equals(lastVersion.version)) {
                            showDialog(DIALOG_UPDATE_NEEDED);
                        } else {
                            Toast.makeText(Preferences.this, R.string.msg_app_updated, Toast.LENGTH_SHORT)
                                    .show();
                        }

                    }
                };
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
                    task.execute();
                } else {
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
                // Checking for updates every week
                startService(new Intent(getApplicationContext(), UpdateCheckerService.class));
                return true;
            }
        });
    }
    findPreference("changelog").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            showDialog(DIALOG_CHANGELOG);
            return true;
        }
    });
    findPreference("about").setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            showDialog(DIALOG_ABOUT);
            return true;
        }
    });
    findPreference(dicLocalPref).setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            startActivityForResult(new Intent(getApplicationContext(), FileChooserActivity.class), 0);
            return true;
        }
    });
    final CheckBoxPreference autoScan = (CheckBoxPreference) findPreference("autoScan");
    autoScan.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        public boolean onPreferenceClick(Preference preference) {
            findPreference("autoScanInterval").setEnabled(autoScan.isChecked());
            return true;

        }
    });
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    findPreference("autoScanInterval").setEnabled(
            prefs.getBoolean(Preferences.autoScanPref, getResources().getBoolean(R.bool.autoScanDefault)));
}

From source file:com.fine47.http.ActivityHttpClient.java

/**
 * Checks whether the system is online (connected to a network) or not.
 *
 * @return TRUE if the system is online, FALSE otherwise
 *///  www .ja va  2s.  c  o m
public boolean isOnline() {
    try {
        ConnectivityManager cm = (ConnectivityManager) getContext().getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (null != netInfo) {
            // Check for availability and if it's really connected.
            isConnected = netInfo.isAvailable() && netInfo.isConnectedOrConnecting();

            // Get available networks' info.
            NetworkInfo[] netsInfo = cm.getAllNetworkInfo();

            // What kind of networks are available.
            for (NetworkInfo ni : netsInfo) {
                if (ni.isConnected()) {
                    String niType = ni.getTypeName();
                    if ("WIFI".equalsIgnoreCase(niType)) {
                        isWifiConnected = true;
                    } else if ("MOBILE".equalsIgnoreCase(niType)) {
                        isMobileConnected = true;
                    }
                }
            }
        } else {
            isConnected = false;
        }

        return isConnected;
    } catch (Throwable error) {
        if (isDebugging()) {
            Log.e(LOG_TAG, "Error while detecting network status.", error);
        }
    }

    return isConnected;
}

From source file:com.shafiq.mytwittle.App.java

public boolean isOnline() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
        return true;
    }/*  w w w  .j  ava2s. c o  m*/

    return false;
}

From source file:ee.ria.DigiDoc.fragment.ContainerDetailsFragment.java

private boolean isInternetAccessAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

From source file:fr.inria.ucn.collectors.NetworkStateCollector.java

/**
 * //from  w  w  w .j av a 2 s.  c  o  m
 * @param c
 * @param ts
 * @param change
 */
@SuppressWarnings("deprecation")
@SuppressLint({ "DefaultLocale", "NewApi" })
public void run(Context c, long ts, boolean change) {
    try {
        // current active interface (wifi or mobile) and config
        ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        TelephonyManager tm = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();

        JSONObject data = new JSONObject();
        data.put("on_network_state_change", change); // this collection run was triggered by network change
        data.put("is_connected", (ni != null && ni.isConnectedOrConnecting()));
        data.put("is_roaming", tm.isNetworkRoaming());

        // airplane mode ?
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            data.put("is_airplane_mode",
                    (Settings.System.getInt(c.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0));
        } else {
            data.put("is_airplane_mode",
                    (Settings.Global.getInt(c.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0));
        }

        if (ni != null) {
            JSONObject active = new JSONObject();
            active.put("type", ni.getType());
            active.put("subtype", ni.getSubtype());
            active.put("type_name", ni.getTypeName());
            active.put("subtype_name", ni.getSubtypeName());
            active.put("state", ni.getState().toString());
            active.put("detailed_state", ni.getDetailedState().toString());
            active.put("is_wifi", (ni.getType() == ConnectivityManager.TYPE_WIFI));
            data.put("active_network", active);

            if (ni.getType() == ConnectivityManager.TYPE_WIFI) {
                data.put("wifi_network", getWifi(c));
            }
        }

        // mobile network details
        data.put("mobile_network", getMobile(tm));

        // kernel network statistics
        data.put("netstat", getNetstat());

        // interfaces config
        Map<String, JSONObject> stats = networkStats();
        data.put("ifconfig", getIfconfig(stats));

        // double check interfaces
        data.put("ip_addr_show", getIpAddr(stats));

        Helpers.sendResultObj(c, "network_state", ts, data);

    } catch (JSONException jex) {
        Log.w(Constants.LOGTAG, "failed to create json object", jex);
    }
}

From source file:com.tweetlanes.android.core.App.java

boolean isOnline() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnectedOrConnecting();

}

From source file:org.artoolkit.ar.samples.ARMovie.ARMovieActivity.java

@SuppressWarnings("deprecation") // FILL_PARENT still required for API level 7 (Android 2.1)
@Override/*from www. j  a v  a 2 s  . co  m*/
public void onResume() {
    Log.i(TAG, "onResume()");
    super.onResume();

    // Update info on whether we have an Internet connection.
    ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    nativeSetInternetState(isConnected ? 1 : 0);

    // In order to ensure that the GL surface covers the camera preview each time onStart
    // is called, remove and add both back into the FrameLayout.
    // Removing GLSurfaceView also appears to cause the GL surface to be disposed of.
    // To work around this, we also recreate GLSurfaceView. This is not a lot of extra
    // work, since Android has already destroyed the OpenGL context too, requiring us to
    // recreate that and reload textures etc.

    // Create the camera view.
    camSurface = new CameraSurface(this);
    camSurface.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                focusOnTouch(event);
            }
            return true;
        }
    });

    // Create/recreate the GL view.
    glView = new GLSurfaceView(this);
    //glView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); // Do we actually need a transparent surface? I think not, (default is RGB888 with depth=16) and anyway, Android 2.2 barfs on this.
    Renderer r = new Renderer();
    r.setMovieController(movieController);
    glView.setRenderer(r);
    glView.setZOrderMediaOverlay(true); // Request that GL view's SurfaceView be on top of other SurfaceViews (including CameraPreview's SurfaceView).

    mainLayout.addView(camSurface, new LayoutParams(128, 128));
    mainLayout.addView(glView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    if (glView != null)
        glView.onResume();

    // Resume movieController after resuming glView.
    if (movieController != null)
        movieController.onResume(glView);
}

From source file:metrocasas.projectsgt.MainActivity.java

public boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) this.getApplicationContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
    return activeNetwork.isConnectedOrConnecting();
}

From source file:com.flexvdi.androidlauncher.LoginActivity.java

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

    mContext = this;

    try {//www .  j  av a2  s . com
        GStreamer.init(mContext);
    } catch (Exception e) {
        Log.e(TAG, "Can't initialize GStreamer" + e.getMessage());
        finish();
    }

    settings = getSharedPreferences("flexVDI", MODE_PRIVATE);
    settingsEditor = settings.edit();
    /* Uncomment this for clearing preferences (useful when debugging) */
    //settingsEditor.clear();
    //settingsEditor.apply();
    //settingsEditor.commit();

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.activity_login);

    textUser = (EditText) findViewById(R.id.textUser);
    textServer = (EditText) findViewById(R.id.textServer);
    textPassword = (EditText) findViewById(R.id.textPassword);

    goButton = (Button) findViewById(R.id.buttonGO);
    goButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ConnectivityManager cm = (ConnectivityManager) mContext
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

            if (!isConnected) {
                Toast.makeText(view.getContext(), getResources().getString(R.string.no_network),
                        Toast.LENGTH_LONG).show();
                return;
            }

            if (checkBoxGenericSpice.isChecked()) {
                String userField = textUser.getText().toString();
                if (userField.length() == 0 || !userField.contains(":")) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.invalid_spice_server),
                            Toast.LENGTH_LONG).show();
                    return;
                }

                String spiceAddress = userField.substring(0, userField.indexOf(":"));
                String spicePort = userField.substring(userField.indexOf(":") + 1);

                if (spiceAddress.length() == 0 || spicePort.length() == 0) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.invalid_spice_server),
                            Toast.LENGTH_LONG).show();
                    return;
                }

                String spicePassword = textPassword.getText().toString();

                settingsEditor.putBoolean("enableSound", checkBoxEnableSound.isChecked());
                settingsEditor.putBoolean("staticResolution", checkBoxStaticResolution.isChecked());
                settingsEditor.putBoolean("genericSpice", checkBoxGenericSpice.isChecked());
                settingsEditor.putString("flexServerName", textServer.getText().toString());

                settingsEditor.putString("spice_address", spiceAddress);
                settingsEditor.putString("spice_port", spicePort);
                settingsEditor.putString("spice_password", spicePassword);
                settingsEditor.putBoolean("use_ws", false);

                settingsEditor.apply();
                settingsEditor.commit();

                startMainActivity();
            } else {
                if (textServer.getText().length() == 0) {
                    Toast.makeText(view.getContext(), getResources().getString(R.string.empty_flexvdi_server),
                            Toast.LENGTH_LONG).show();
                } else {
                    if (textUser.getText().length() != 0 && textPassword.getText().length() != 0) {
                        new RequestTask().execute("authmode", textServer.getText().toString(),
                                textUser.getText().toString(), textPassword.getText().toString(), "");
                    } else
                        Toast.makeText(view.getContext(), getResources().getString(R.string.empty_credentials),
                                Toast.LENGTH_LONG).show();
                }
            }
        }
    });

    // The advanced settings button.
    checkBoxAdvancedOptions = (CheckBox) findViewById(R.id.checkBoxAdvancedSettings);
    layoutAdvancedOptions = (LinearLayout) findViewById(R.id.layoutAdvancedOptions2);
    checkBoxAdvancedOptions.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            if (checked)
                layoutAdvancedOptions.setVisibility(View.VISIBLE);
            else
                layoutAdvancedOptions.setVisibility(View.GONE);
        }
    });

    textServer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View field, boolean hasFocus) {
            if (!hasFocus && checkBoxGenericSpice.isChecked()) {
                if (textUser.getText().toString().length() == 0) {
                    textUser.setText(textServer.getText());
                }
            }
        }
    });

    checkBoxEnableSound = (CheckBox) findViewById(R.id.checkBoxEnableSound);
    if (settings.getBoolean("enableSound", true)) {
        checkBoxEnableSound.setChecked(true);
    } else {
        checkBoxEnableSound.setChecked(false);
    }

    if (!settings.contains("staticResolution")) {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        if ((size.x + size.y) > 2340) {
            /* 2340 = 1440+900 */
            settingsEditor.putBoolean("staticResolution", true);
        } else {
            settingsEditor.putBoolean("staticResolution", false);
        }
        settingsEditor.apply();
        settingsEditor.commit();
    }

    checkBoxStaticResolution = (CheckBox) findViewById(R.id.checkBoxStaticResolution);
    if (settings.getBoolean("staticResolution", true)) {
        checkBoxStaticResolution.setChecked(true);
    } else {
        checkBoxStaticResolution.setChecked(false);
    }

    checkBoxGenericSpice = (CheckBox) findViewById(R.id.checkBoxGenericSpice);
    if (settings.getBoolean("genericSpice", false)) {
        checkBoxGenericSpice.setChecked(true);
        checkBoxAdvancedOptions.setChecked(true);
        layoutAdvancedOptions.setVisibility(View.VISIBLE);

        if (settings.contains("flexServerName")) {
            textServer.setText(settings.getString("flexServerName", ""));
            textUser.setText(settings.getString("flexServerName", ""));
            textServer.setHint(getResources().getString(R.string.spice_server));
            textUser.setHint(getResources().getString(R.string.spice_server_port));
        }
    } else {
        checkBoxGenericSpice.setChecked(false);
        if (settings.contains("flexServerName")) {
            textServer.setText(settings.getString("flexServerName", ""));
            layoutAdvancedOptions.setVisibility(View.GONE);
        } else {
            textServer.setText("manager.flexvdi.com");
            checkBoxAdvancedOptions.setChecked(true);
        }
    }

    checkBoxGenericSpice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean checked) {
            if (checked) {
                textServer.setHint(getResources().getString(R.string.spice_server));
                textUser.setHint(getResources().getString(R.string.spice_server_port));
                String server = textServer.getText().toString();
                if (server.length() != 0) {
                    if (server.contains(":")) {
                        textUser.setText(server);
                    } else {
                        textUser.setText(server + ":5900");
                        textServer.setText(server + ":5900");
                    }
                }
            } else {
                textServer.setHint(getResources().getString(R.string.flexvdi_server));
                String server = textServer.getText().toString();
                if (server.length() != 0 && server.contains(":")) {
                    textServer.setText(server.substring(0, server.indexOf(":")));
                }
                textUser.setText("");
                textUser.setHint(getResources().getString(R.string.user));
            }
        }
    });

    deviceID = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);

    textViewDeviceID = (TextView) findViewById(R.id.textViewDeviceID);
    textViewDeviceID.setText("ID: " + deviceID + " (" + BuildConfig.VERSION_NAME + ")");

    try {
        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[] { new NullX509TrustManager() }, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    } catch (NoSuchAlgorithmException nsae) {
        Log.e(TAG, nsae.getMessage());
    } catch (KeyManagementException kme) {
        Log.e(TAG, kme.getMessage());
    }
}

From source file:org.wso2.emm.system.service.EMMSystemService.java

private boolean checkNetworkOnline() {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = connectivityManager.getActiveNetworkInfo();
    boolean status = false;
    if (info != null && info.isConnectedOrConnecting()) {
        status = true;/*from   ww  w  .  j  a  va2s  . c  om*/
    }

    return status;
}