Example usage for android.net NetworkInfo getState

List of usage examples for android.net NetworkInfo getState

Introduction

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

Prototype

@Deprecated
public State getState() 

Source Link

Document

Reports the current coarse-grained state of the network.

Usage

From source file:org.smap.smapTask.android.receivers.NetworkReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    // make sure sd card is ready, if not don't try to send
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return;/*from  w  ww  .j av  a 2s.  com*/
    }

    String action = intent.getAction();
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo currentNetworkInfo = manager.getActiveNetworkInfo();

    if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
        if (currentNetworkInfo != null && currentNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
            if (interfaceIsEnabled(context, currentNetworkInfo)) {
                //uploadForms(context);
                refreshTasks(context);
            }
        }
    } else if (action.equals("org.odk.collect.android.FormSaved")) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = connectivityManager.getActiveNetworkInfo();

        if (ni == null || !ni.isConnected()) {
            // not connected, do nothing
        } else {
            if (interfaceIsEnabled(context, ni)) {
                refreshTasks(context);
            }
        }
    }
}

From source file:edu.tjhsst.ion.gcmFrame.MainActivity.java

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

    this.setContentView(R.layout.activity_main);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.navbar_color));

    }//  ww  w .  j  a  va2 s. c om
    // requestWindowFeature(Window.FEATURE_NO_TITLE);

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
            if (sentToken) {
                Log.i(TAG, "Google token sent");

            } else {
                Toast.makeText(getApplicationContext(), getString(R.string.token_error_message),
                        Toast.LENGTH_LONG).show();
            }
        }

    };

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
        if (ni != null) {
            NetworkInfo.State state = ni.getState();
            if (state == null || state != NetworkInfo.State.CONNECTED) {
                // record the fact that there is no connection
                isConnected = false;
            }
        }
    }

    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.ION_SETUP, false);

    webView = (WebView) findViewById(R.id.webview);

    webView.setInitialScale(1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);

    webView.getSettings().setUseWideViewPort(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }
    StringBuilder uaString = new StringBuilder(webView.getSettings().getUserAgentString());
    uaString.append(" - IonAndroid: gcmFrame (");
    if (sentToken) {
        uaString.append("appRegistered:True");
    } else {
        uaString.append("appRegistered:False");
    }
    uaString.append(" osVersion:").append(System.getProperty("os.version"));
    uaString.append(" apiLevel:").append(android.os.Build.VERSION.SDK_INT);
    uaString.append(" Device:").append(android.os.Build.DEVICE);
    uaString.append(" Model:").append(android.os.Build.MODEL);
    uaString.append(" Product:").append(android.os.Build.PRODUCT);
    uaString.append(")");
    webView.getSettings().setUserAgentString(uaString.toString());

    webView.setNetworkAvailable(isConnected);

    webView.addJavascriptInterface(new WebAppInterface(this), "IonAndroidInterface");

    webView.loadUrl(MainActivity.ION_HOST);

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, "Loading " + url);
            if (!isConnected) {
                String html = getHtml("offline.html");
                html = html.replaceAll("\\[url\\]", url);
                view.loadData(html, "text/html", "utf-8");
                return true;
            } else if (url.contains(ION_HOST)) {
                // keep in WebView
                webView.loadUrl(url);
                return true;
            } else {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // if (errorCode == ERROR_TIMEOUT)
            view.stopLoading(); // may not be needed
            String html = getHtml("timeout.html");
            html = html.replaceAll("\\[url\\]", failingUrl);
            html = html.replaceAll("\\[desc\\]", description);
            view.loadData(html, "text/html", "utf-8");
        }
    });

}

From source file:com.odo.kcl.mobileminer.miner.MinerService.java

private void connectivityChanged() {
    String name = "None";
    ConnectivityManager manager = (ConnectivityManager) getApplicationContext()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = manager.getActiveNetworkInfo();
    if (netInfo != null) {
        if (netInfo.getState() == NetworkInfo.State.CONNECTED) {
            switch (netInfo.getType()) {
            case ConnectivityManager.TYPE_WIFI:
                wifiData = true;//from w w w . j  a v a  2  s. c  o m
                mobileData = false;
                if (!updating)
                    startUpdating();
                WifiManager wifiMgr = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
                name = wifiInfo.getSSID();
                if (!networkName.equals(name)) {
                    wirelessData = new WifiData(wifiInfo);
                    MinerData helper = new MinerData(context);
                    helper.putWifiNetwork(helper.getWritableDatabase(), wirelessData, new Date());
                    helper.close();
                    networkName = name;
                    networkBroadcast();
                }
                startScan(); // Always scan when we've got WIFI.
                //Log.i("MinerService","CONNECTED: WIFI");
                break;
            case ConnectivityManager.TYPE_MOBILE:
                wifiData = false;
                mobileData = true;
                if ("goldfish".equals(Build.HARDWARE)) {
                    if (!updating)
                        startUpdating();
                } else {
                    updating = false;
                }

                // https://code.google.com/p/android/issues/detail?id=24227
                //String name; Cursor c;
                //c = this.getContentResolver().query(Uri.parse("content://telephony/carriers/preferapn"), null, null, null, null);
                //name = c.getString(c.getColumnIndex("name"));
                TelephonyManager telephonyManager = ((TelephonyManager) this
                        .getSystemService(Context.TELEPHONY_SERVICE));
                name = telephonyManager.getNetworkOperatorName();
                if (!networkName.equals(name)) {
                    MinerData helper = new MinerData(context);
                    helper.putMobileNetwork(helper.getWritableDatabase(), telephonyManager, new Date());
                    helper.close();
                    networkName = name;
                    networkBroadcast();
                }
                //startScan();
                //Log.i("MinerService","CONNECTED MOBILE: "+name);
                break;
            default:
                //Log.i("MinerService",netInfo.getTypeName());
                break;
            }
        } else {
            scanning = false;
        }
    } else {
        scanning = false;
        networkName = "null";
    }

}

From source file:jp.takuo.android.mmsreq.Request.java

protected void getConnectivity() throws NoConnectivityException, ConnectTimeoutException, InterruptedException {
    mConnMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (!mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS).isAvailable()) {
        throw new NoConnectivityException(mContext.getString(R.string.not_available));
    }/* ww w  .j  a  va2  s .  com*/
    int count = 0;
    int result = beginMmsConnectivity(mConnMgr);
    if (result != APN_ALREADY_ACTIVE) {
        NetworkInfo info = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
        while (!info.isConnected()) {
            Thread.sleep(1500);
            info = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
            Log.d(LOG_TAG, "Waiting for CONNECTED: state=" + info.getState());
            if (count++ > 5)
                throw new ConnectTimeoutException(mContext.getString(R.string.failed_to_connect));
        }
    }
    Thread.sleep(1500); // wait for adding dns
}

From source file:org.openbmap.soapclient.CheckServerTask.java

/**
 * Gives system some time to initialize network adapter and connections
 *//*from   w  ww  .  j ava 2  s .  c om*/
private void waitForConnect() {
    final ConnectivityManager cm = (ConnectivityManager) mContext
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = null;

    // wait for state change
    for (int i = 0; i < WAIT_FOR_CONNECTING; i++) {
        try {
            networkInfo = cm.getActiveNetworkInfo();
            if ((networkInfo != null) && (networkInfo.getState() == State.CONNECTING
                    || networkInfo.getState() == State.CONNECTED)) {
                break;
            }
            Log.i(TAG, "Network neither connected nor connecting. Wait 1 sec..");
            Thread.sleep(1000);
        } catch (final InterruptedException e) {
            // ignore
        }
    }
    networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null) {
        Log.i(TAG, "Connection status" + networkInfo.toString());
    }

    // once we're in CONNECTING state, wait another couple of seconds
    if (networkInfo != null && networkInfo.getState().equals(State.CONNECTING)) {
        // if in connecting state, wait 1 second for connection
        // this process is repeated multiple times according to retries
        Log.i(TAG, "Hoorray: after all connecting.. Wait for connection ready");
        for (int i = 0; i < WAIT_FOR_CONNECTED; i++) {
            if (isOnline()) {
                return;
            }
            Log.i(TAG, "Connection not yet ready. Waiting 1 sec..");
            try {
                Thread.sleep(1000);
            } catch (final InterruptedException e) {
                // ignore
            }
        }
    }

    networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null) {
        Log.i(TAG, "Waited enough: now " + networkInfo.toString());
    }
}

From source file:com.csipsimple.service.DownloadLibService.java

@Override
public void onCreate() {
    Log.d(THIS_FILE, "Download Lib Service started");

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    // Lock wifi if possible to ensure download will be done
    wifiLock = ((WifiManager) getSystemService(WIFI_SERVICE))
            .createWifiLock("com.csipsimple.service.DownloadLibService");
    connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
    connectionChangeReceiver = new ConnectionChangeReceiver();
    registerReceiver(connectionChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
    if (activeNetwork != null) {
        NetworkInfo.State state = activeNetwork.getState();
        connected = (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.SUSPENDED);
    } else {// ww  w .ja  va2 s . co  m
        connected = false;
    }

}

From source file:org.m2x.rssreader.service.FetcherService.java

@SuppressWarnings("deprecation")
@Override//from ww  w . j  a va2  s .  c o  m
public void onHandleIntent(Intent intent) {
    if (intent == null) {
        return;
    }

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    // Connectivity issue, we quit
    if (networkInfo == null || networkInfo.getState() != NetworkInfo.State.CONNECTED) {
        broadcastNetworkProblem();
        return;
    }

    boolean isFromAutoRefresh = intent.getBooleanExtra(Constants.FROM_AUTO_REFRESH, false);
    boolean skipFetch = isFromAutoRefresh && PrefUtils.getBoolean(PrefUtils.AUTO_REFRESH_ONLY_ON_WIFI, false)
            && networkInfo.getType() != ConnectivityManager.TYPE_WIFI;
    // We need to skip the fetching process, so we quit
    if (skipFetch) {
        return;
    }

    if (ACTION_DOWNLOAD_IMAGES.equals(intent.getAction())) {
        downloadAllImages();
    } else { // == Constants.ACTION_REFRESH_FEEDS
        PrefUtils.putBoolean(PrefUtils.IS_REFRESHING, true);

        if (isFromAutoRefresh) {
            PrefUtils.putLong(PrefUtils.LAST_SCHEDULED_REFRESH, SystemClock.elapsedRealtime());
        }

        String feedId = intent.getStringExtra(Constants.FEED_ID);
        int newCount = (feedId == null ? refreshFeeds() : refreshFeed(feedId));

        if (newCount > 0) {
            if (PrefUtils.getBoolean(PrefUtils.PUSH_NOTIFICATION, true)) {
                Cursor cursor = getContentResolver().query(EntryColumns.CONTENT_URI, new String[] { COUNT },
                        EntryColumns.WHERE_UNREAD, null, null);

                cursor.moveToFirst();
                newCount = cursor.getInt(0); // The number has possibly changed
                cursor.close();

                if (newCount > 0) {
                    String text = getResources().getQuantityString(R.plurals.number_of_new_entries, newCount,
                            newCount);

                    Intent notificationIntent = new Intent(FetcherService.this, MainActivity.class);
                    PendingIntent contentIntent = PendingIntent.getActivity(FetcherService.this, 0,
                            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(
                            MainApplication.getContext()).setContentIntent(contentIntent)
                                    .setSmallIcon(R.drawable.ic_launcher)
                                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                                            R.drawable.ic_launcher)) //
                                    .setTicker(text).setWhen(System.currentTimeMillis()).setAutoCancel(true)
                                    .setContentTitle(getString(R.string.rssreader_feeds)).setContentText(text)
                                    .setLights(0xffffffff, 300, 1000);

                    if (PrefUtils.getBoolean(PrefUtils.NOTIFICATIONS_VIBRATE, false)) {
                        notifBuilder.setVibrate(new long[] { 0, 1000 });
                    }

                    String ringtone = PrefUtils.getString(PrefUtils.NOTIFICATIONS_RINGTONE, null);
                    if (ringtone != null && ringtone.length() > 0) {
                        notifBuilder.setSound(Uri.parse(ringtone));
                    }

                    if (Constants.NOTIF_MGR != null) {
                        Constants.NOTIF_MGR.notify(0, notifBuilder.getNotification());
                    }
                }
            } else if (Constants.NOTIF_MGR != null) {
                Constants.NOTIF_MGR.cancel(0);
            }
        }

        downloadAllImages();

        PrefUtils.putBoolean(PrefUtils.IS_REFRESHING, false);
        broadcastRefreshFinished();
    }
}

From source file:com.app.uafeed.fragment.EntryFragment.java

@Override
public void onClickFullText() {
    final BaseActivity activity = (BaseActivity) getActivity();

    if (activity.getProgressBar().getVisibility() != View.VISIBLE) {
        Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
        final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

        if (alreadyMobilized) {
            activity.runOnUiThread(new Runnable() {
                @Override/*from w w  w  .  j ava 2 s .  c om*/
                public void run() {
                    mPreferFullText = true;
                    mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                }
            });
        } else {
            ConnectivityManager connectivityManager = (ConnectivityManager) activity
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

            // since we have acquired the networkInfo, we use it for basic checks
            if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] });
                activity.startService(new Intent(activity, FetcherService.class)
                        .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        activity.getProgressBar().setVisibility(View.VISIBLE);
                    }
                });
            } else {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, R.string.network_error, Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }
}

From source file:com.viktorrudometkin.burramys.fragment.EntryFragment.java

@Override
public void onClickFullText() {
    final BaseActivity activity = (BaseActivity) getActivity();

    Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
    final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

    if (alreadyMobilized) {
        activity.runOnUiThread(new Runnable() {
            @Override/*  w w w  .  jav  a 2 s  . co  m*/
            public void run() {
                mPreferFullText = true;
                mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
            }
        });
    } else if (!isRefreshing()) {
        ConnectivityManager connectivityManager = (ConnectivityManager) activity
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        // since we have acquired the networkInfo, we use it for basic checks
        if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
            FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] });
            activity.startService(
                    new Intent(activity, FetcherService.class).setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showSwipeProgress();
                }
            });
        } else {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    UiUtils.showMessage(getActivity(), R.string.network_error);
                }
            });
        }
    }
}

From source file:net.fred.feedex.fragment.EntryFragment.java

@Override
public void onClickFullText() {
    final BaseActivity activity = (BaseActivity) getActivity();

    if (!isRefreshing()) {
        Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
        final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

        if (alreadyMobilized) {
            activity.runOnUiThread(new Runnable() {
                @Override//  www.java 2 s .  c  o m
                public void run() {
                    mPreferFullText = true;
                    mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                }
            });
        } else {
            ConnectivityManager connectivityManager = (ConnectivityManager) activity
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

            // since we have acquired the networkInfo, we use it for basic checks
            if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
                FetcherService.addEntriesToMobilize(new long[] { mEntriesIds[mCurrentPagerPos] });
                activity.startService(new Intent(activity, FetcherService.class)
                        .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showSwipeProgress();
                    }
                });
            } else {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, R.string.network_error, Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }
}