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:com.mobicage.rogerthat.ServiceBoundActivity.java

protected boolean checkConnectivity() {
    NetworkInfo activeNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}

From source file:am.roadpolice.roadpolice.alarm.AlarmReceiver.java

@Override
public void onReceive(Context context, Intent intent) {

    if (context == null || intent == null) {
        Logger.error("AlarmReceiver", "onReceive(Context " + (context == null ? "null," : ",") + " Intent "
                + (intent == null ? "null)" : ")"));
        return;//  w  w  w .j  a  va 2  s .  c o  m
    }

    // Set Context
    mContext = context;

    // Get shared preferences.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    // Check internet availability and only in that case start actions.
    final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    final String action = intent.getAction();
    // Catch Network change state.
    if (!TextUtils.isEmpty(action) && action.equals("android.net.conn.CONNECTIVITY_CHANGE")) {
        // If internet connection established
        if (isConnected) {
            // If didn't missed last update of data due to network issues do nothing,
            // otherwise proceed with data updating.
            final boolean missUpdateDueToNetworkIssue = sp
                    .getBoolean(MainActivity.MISS_UPDATE_DUE_TO_NETWORK_ISSUE, false);
            if (!missUpdateDueToNetworkIssue)
                return;
        }
        // If user switch off Internet connection do not proceed.
        else
            return;
    }
    // Check Boot state.
    else if (!TextUtils.isEmpty(action) && action.equals("android.intent.action.BOOT_COMPLETED")) {
        // Get stored alarm time.
        final long nextAlarmTime = PreferenceUtils.getDataLong(context,
                PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, -1);
        if (nextAlarmTime != -1) {
            // Set new alarm, as after reboot alarm was switched off.
            if (mAlarmManager == null)
                mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

            Intent alarmIntent = new Intent(context, AlarmReceiver.class);
            if (mAlarmIntent == null)
                mAlarmIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

            // Enable boot receiver
            ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
            PackageManager pm = context.getPackageManager();
            pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);

            final int ui = DialogSettings.getUpdateInterval(context);
            AlarmType type = ui == DialogSettings.DAILY ? AlarmType.DAILY
                    : ui == DialogSettings.WEEKLY ? AlarmType.WEEKLY : AlarmType.MONTHLY;

            mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, nextAlarmTime, type.getValue(),
                    mAlarmIntent);
        }
        return;
    }
    // When alarm rise we appears in the block below.
    else {
        Logger.beep();
        Logger.beep();
        Logger.beep();
        // Calculating next alarm time.
        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        final int updateInterval = DialogSettings.getUpdateInterval(context);
        if (updateInterval == DialogSettings.DAILY)
            calendar.add(Calendar.DATE, 1);
        else if (updateInterval == DialogSettings.WEEKLY)
            calendar.add(Calendar.DATE, 7);
        else if (updateInterval == DialogSettings.MONTHLY)
            calendar.add(Calendar.MONTH, 1);
        else
            Logger.error("AlarmReceiver", "Unknown Update Interval.");

        // Next alarm time.
        final long nextAlarmTimeInMillis = calendar.getTimeInMillis();
        // Store next alarm time for further use.
        PreferenceUtils.storeDataLong(context, PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, nextAlarmTimeInMillis);
    }

    if (!isConnected) {
        Logger.debug("AlarmReceiver", "No Internet connection, while receiving Alarm message");
        // If no internet connecting schedule data update, as soon
        // as internet connection will be available.
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean(MainActivity.MISS_UPDATE_DUE_TO_NETWORK_ISSUE, true);
        ed.apply();
        return;
    }

    final String cerNum = sp.getString(MainActivity.CER_NUMBER, MainActivity.EMPTY_STRING);
    final String regNum = sp.getString(MainActivity.REG_NUMBER, MainActivity.EMPTY_STRING);
    final boolean login = sp.getBoolean(MainActivity.AUTO_LOGIN, false);
    if (!login) { // If no auto login user detected.
        Logger.debug("AlarmReceiver", "Why we enter this case if no auto login users detected?");
        // Remove alarm.
        AlarmReceiver.createAlarm(context, AlarmReceiver.AlarmType.NONE);
        return;
    }

    if (TextUtils.isEmpty(cerNum) || TextUtils.isEmpty(regNum)) {
        Logger.debug("AlarmReceiver", "Why we enter this case if both data are null or empty?");
        // Remove alarm.
        AlarmReceiver.createAlarm(context, AlarmReceiver.AlarmType.NONE);
        // Remove auto login.
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean(MainActivity.AUTO_LOGIN, false);
        ed.apply();
        return;
    }

    // Start downloading data from internet.
    Submitter submitter = new Submitter(cerNum, regNum, this);
    submitter.executeOnExecutor(Executors.newSingleThreadExecutor());
}

From source file:fm.feed.android.SampleApp.fragment.TestFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mBtnTune.setOnClickListener(tune);//from w  ww .  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);

    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");
        }
    });

    resetTrackInfo();

    if (mPlayer.hasPlay()) {
        updateTrackInfo(mPlayer.getPlay());
    }
    if (mPlayer.hasStationList()) {
        updateStations(mPlayer.getStationList());
    }
}

From source file:com.google.transporttracker.TrackerService.java

/**
 * Pushes a new status to Firebase when location changes.
 *//*from www.ja  v a  2 s. c o  m*/
@Override
public void onLocationChanged(Location location) {

    fetchRemoteConfig();

    long hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    int startupSeconds = (int) (mFirebaseRemoteConfig.getDouble("SLEEP_HOURS_DURATION") * 3600);
    if (hour == mFirebaseRemoteConfig.getLong("SLEEP_HOUR_OF_DAY")) {
        shutdownAndScheduleStartup(startupSeconds);
        return;
    }

    Map<String, Object> transportStatus = new HashMap<>();
    transportStatus.put("lat", location.getLatitude());
    transportStatus.put("lng", location.getLongitude());
    transportStatus.put("time", new Date().getTime());
    transportStatus.put("power", getBatteryLevel());

    if (locationIsAtStatus(location, 1) && locationIsAtStatus(location, 0)) {
        // If the most recent two statuses are approximately at the same
        // location as the new current location, rather than adding the new
        // location, we update the latest status with the current. Two statuses
        // are kept when the locations are the same, the earlier representing
        // the time the location was arrived at, and the latest representing the
        // current time.
        mTransportStatuses.set(0, transportStatus);
        // Only need to update 0th status, so we can save bandwidth.
        mFirebaseTransportRef.child("0").setValue(transportStatus);
    } else {
        // Maintain a fixed number of previous statuses.
        while (mTransportStatuses.size() >= mFirebaseRemoteConfig.getLong("MAX_STATUSES")) {
            mTransportStatuses.removeLast();
        }
        mTransportStatuses.addFirst(transportStatus);
        // We push the entire list at once since each key/index changes, to
        // minimize network requests.
        mFirebaseTransportRef.setValue(mTransportStatuses);
    }

    if (BuildConfig.DEBUG) {
        logStatusToStorage(transportStatus);
    }

    NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
            .getActiveNetworkInfo();
    boolean connected = info != null && info.isConnectedOrConnecting();
    setStatusMessage(connected ? R.string.tracking : R.string.not_tracking);
}

From source file:com.marianhello.bgloc.LocationService.java

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

From source file:com.jahirfiquitiva.paperboard.activities.Main.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    context = this;
    mPrefs = new Preferences(Main.this);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//  w  w w.  j  a va 2 s  .  c o  m
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    thaApp = getResources().getString(R.string.app_name);
    thaHome = getResources().getString(R.string.section_one);
    thaPreviews = getResources().getString(R.string.section_two);
    thaApply = getResources().getString(R.string.section_three);
    thaWalls = getResources().getString(R.string.section_four);
    thaRequest = getResources().getString(R.string.section_five);
    thaCredits = getResources().getString(R.string.section_seven);

    drawerVersion = "v " + getResources().getString(R.string.current_version);

    currentItem = 1;

    headerResult = new AccountHeader().withActivity(this).withHeaderBackground(R.drawable.header)
            .withSelectionFirstLine(getResources().getString(R.string.app_long_name))
            .withSelectionSecondLine(drawerVersion).withSavedInstance(savedInstanceState).build();

    enable_features = mPrefs.isFeaturesEnabled();
    firstrun = mPrefs.isFirstRun();

    result = new Drawer().withActivity(this).withToolbar(toolbar).withAccountHeader(headerResult)
            .addDrawerItems(
                    new PrimaryDrawerItem().withName(thaHome).withIcon(GoogleMaterial.Icon.gmd_home)
                            .withIdentifier(1),
                    new PrimaryDrawerItem().withName(thaPreviews).withIcon(GoogleMaterial.Icon.gmd_palette)
                            .withIdentifier(2),
                    new PrimaryDrawerItem().withName(thaApply).withIcon(GoogleMaterial.Icon.gmd_loyalty)
                            .withIdentifier(3),
                    new DividerDrawerItem(), new SecondaryDrawerItem().withName(thaCredits).withIdentifier(6))
            .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id,
                        IDrawerItem drawerItem) {

                    if (drawerItem != null) {

                        switch (drawerItem.getIdentifier()) {
                        case 1:
                            switchFragment(1, thaApp, "Home");
                            break;
                        case 2:
                            switchFragment(2, thaPreviews, "Previews");
                            break;
                        case 3:
                            switchFragment(3, thaApply, "Apply");
                            break;
                        case 4:
                            ConnectivityManager cm = (ConnectivityManager) context
                                    .getSystemService(Context.CONNECTIVITY_SERVICE);
                            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                            boolean isConnected = activeNetwork != null
                                    && activeNetwork.isConnectedOrConnecting();

                            if (isConnected) {
                                switchFragment(4, thaWalls, "Wallpapers");
                            } else {
                                showNotConnectedDialog();
                            }
                            break;
                        case 5:
                            switchFragment(5, thaRequest, "Request");
                            break;
                        case 6:
                            switchFragment(6, thaCredits, "Credits");
                            break;
                        }
                    }
                }
            }).withSavedInstance(savedInstanceState).build();

    result.getListView().setVerticalScrollBarEnabled(false);

    runLicenseChecker();

    if (savedInstanceState == null) {
        result.setSelectionByIdentifier(1);
    }

}

From source file:net.willwebberley.gowertides.ui.DaysActivity.java

/******
 *
 * UTILITY METHODS//from w w w.j a  v  a  2  s. co m
 */

/*
 * Check for network connection. If Internet connection return true. Else, return false.
 */
public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(
            getApplicationContext().CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

From source file:com.kafilicious.popularmovies.ui.activity.MainActivity.java

public boolean isNetworkAvailable() {
    boolean status;
    try {// w w  w.ja va  2s.  c o m
        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        status = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return status;

}

From source file:com.knightlabs.orion_base.activities.Main.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    context = this;
    mPrefs = new Preferences(Main.this);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//www  . j  ava 2 s .co  m
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    thaApp = getResources().getString(R.string.app_name);
    thaHome = getResources().getString(R.string.section_one);
    //thaPreviews = getResources().getString(R.string.section_two); //uncomment this to add previews screen
    thaApply = getResources().getString(R.string.section_three);
    thaWalls = getResources().getString(R.string.section_four);
    thaRequest = getResources().getString(R.string.section_five);
    thaCredits = getResources().getString(R.string.section_seven);

    drawerVersion = "v " + getResources().getString(R.string.current_version);

    currentItem = 1;

    headerResult = new AccountHeader().withActivity(this).withHeaderBackground(R.drawable.header)
            .withSelectionFirstLine(getResources().getString(R.string.app_long_name))
            .withSelectionSecondLine(drawerVersion).withSavedInstance(savedInstanceState).build();

    enable_features = mPrefs.isFeaturesEnabled();
    firstrun = mPrefs.isFirstRun();

    result = new Drawer().withActivity(this).withToolbar(toolbar).withAccountHeader(headerResult)
            .withHeaderDivider(false).addDrawerItems(
                    /* new PrimaryDrawerItem().withName(thaHome).withIcon(GoogleMaterial.Icon.gmd_home).withIdentifier(1),
                     new PrimaryDrawerItem().withName(thaPreviews).withIcon(GoogleMaterial.Icon.gmd_palette).withIdentifier(2),
                     new PrimaryDrawerItem().withName(thaApply).withIcon(GoogleMaterial.Icon.gmd_loyalty).withIdentifier(3),
                     new DividerDrawerItem(),
                     new SecondaryDrawerItem().withName(thaCredits).withIdentifier(6)*/
                    //added
                    new PrimaryDrawerItem().withName(thaHome).withIcon(GoogleMaterial.Icon.gmd_home)
                            .withIdentifier(1),
                    new PrimaryDrawerItem().withName(thaApply).withIcon(GoogleMaterial.Icon.gmd_loyalty)
                            .withIdentifier(2),
                    new DividerDrawerItem(), new SecondaryDrawerItem().withName(thaCredits).withIdentifier(5)

            ).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id,
                        IDrawerItem drawerItem) {

                    if (drawerItem != null) {

                        switch (drawerItem.getIdentifier()) {
                        /*case 1: switchFragment(1, thaApp, "Home"); break;
                        case 2: switchFragment(2, thaPreviews, "Previews"); break;
                        case 3: switchFragment(3, thaApply, "Apply"); break;
                        case 4:
                            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                            boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
                                
                            if (isConnected) {
                                switchFragment(4, thaWalls, "Wallpapers");
                            } else {
                                showNotConnectedDialog();
                            }
                            break;
                        case 5: switchFragment(5, thaRequest, "Request"); break;
                        case 6: switchFragment(6, thaCredits, "Credits"); break;
                        */
                        case 1:
                            switchFragment(1, thaApp, "Home");
                            break;
                        case 2:
                            switchFragment(2, thaApply, "Apply");
                            break;
                        case 3:
                            ConnectivityManager cm = (ConnectivityManager) context
                                    .getSystemService(Context.CONNECTIVITY_SERVICE);
                            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                            boolean isConnected = activeNetwork != null
                                    && activeNetwork.isConnectedOrConnecting();

                            if (isConnected) {
                                switchFragment(3, thaWalls, "Wallpapers");
                            } else {
                                showNotConnectedDialog();
                            }
                            break;
                        case 4:
                            switchFragment(4, thaRequest, "Request");
                            break;
                        case 5:
                            switchFragment(5, thaCredits, "Credits");
                            break;
                        }
                    }
                }
            }).withSavedInstance(savedInstanceState).build();

    result.getListView().setVerticalScrollBarEnabled(false);

    runLicenseChecker();

    if (savedInstanceState == null) {
        result.setSelectionByIdentifier(1);
    }

}

From source file:azad.hallaji.farzad.com.masirezendegi.ExplainMoshaver.java

private boolean isOnline() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
        return true;
    }/*from ww  w. j  a  v  a  2 s.c o  m*/
    return false;
}