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:com.slp.rss_api.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//  www  . java  2  s  .  c  o  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() {
                    Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}

From source file:com.carlrice.reader.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//from  w w w .  ja va 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_SHORT).show();
                    }
                });
            }
        }
    }
}

From source file:hochschuledarmstadt.photostream_tools.PhotoStreamClientImpl.java

private boolean isOnline() {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();

    if (activeNetworkInfo == null) {
        return false;
    } else {//from  ww  w  .ja va2 s  .  c  om
        NetworkInfo.State state = activeNetworkInfo.getState();
        return state == NetworkInfo.State.CONNECTED;
    }
}

From source file:com.example.android.navigationdrawerexample.MainActivity.java

public boolean isNetworkConnected() {
    final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
    return activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED;
}

From source file:net.etuldan.sparss.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        final Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;/*  ww w .j  a v  a  2s.  c  o  m*/

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.ic_star);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.ic_star_border);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        case R.id.menu_open_in_browser: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                    startActivity(browserIntent);
                }
            }
            break;
        }
        case R.id.menu_switch_full_original: {
            isChecked = !item.isChecked();
            item.setChecked(isChecked);
            if (mPreferFullText) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPreferFullText = false;
                        mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                    }
                });
            } else {
                Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
                final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

                if (alreadyMobilized) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        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() {
                                Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
            break;
        }
        default:
            break;
        }
    }

    return super.onOptionsItemSelected(item);
}

From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java

@Override
public void onHandleIntent(Intent intent) {
    if (intent == null) { // No intent, we quit
        return;/*from w  ww.  j  a  va 2s .c om*/
    }

    boolean isFromAutoRefresh = intent.getBooleanExtra(Constants.FROM_AUTO_REFRESH, false);

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    // Connectivity issue, we quit
    if (networkInfo == null || networkInfo.getState() != NetworkInfo.State.CONNECTED) {
        if (ACTION_REFRESH_FEEDS.equals(intent.getAction()) && !isFromAutoRefresh) {
            // Display a toast in that case
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(FetcherService.this, R.string.network_error, Toast.LENGTH_SHORT).show();
                }
            });
        }
        return;
    }

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

    if (ACTION_MOBILIZE_FEEDS.equals(intent.getAction())) {
        mobilizeAllEntries();
        downloadAllImages();
    } else 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());
        }

        /* ModPrivacyVandaag: De defaultwaarde voor het bewaren van artikelen is 30.
        Dus moet de defaultwaarde bij het ophalen ook die waarde hebben, om te voorkomen dat de
        voorkeuren (nog) niet goed ingesteld of gelezen worden.
        In onderstaande dus bij de getString "30" geplaatst. Origineel was "4"
         */
        long keepTime = Long.parseLong(PrefUtils.getString(PrefUtils.KEEP_TIME, "30")) * 86400000l;
        long keepDateBorderTime = keepTime > 0 ? System.currentTimeMillis() - keepTime : 0;

        deleteOldEntries(keepDateBorderTime);

        String feedId = intent.getStringExtra(Constants.FEED_ID);
        int newCount = (feedId == null ? refreshFeeds(keepDateBorderTime)
                : refreshFeed(feedId, keepDateBorderTime)); // number of new articles found after refresh all the feeds

        // notification for new articles.
        if (newCount > 0 && isFromAutoRefresh && PrefUtils.getBoolean(PrefUtils.NOTIFICATIONS_ENABLED, true)) {
            int mNotificationId = 2; // een willekeurige ID, want we doen er nu niks mee
            Intent notificationIntent = new Intent(FetcherService.this, HomeActivity.class);
            // Voorlopig doen we niets met aantallen, want wekt verwarring omdat aantal in de melding kan afwijken van totaal nieuw.
            newCount += PrefUtils.getInt(PrefUtils.NOTIFICATIONS_PREVIOUS_COUNT, 0); // Tel aantal van bestaande melding erbij op
            String text = getResources().getQuantityString(R.plurals.number_of_new_entries, newCount, newCount);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            PendingIntent contentIntent = PendingIntent.getActivity(FetcherService.this, mNotificationId,
                    notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(
                    MainApplication.getContext()) //
                            .setContentIntent(contentIntent) // Wat moet er gebeuren als er op de melding geklikt wordt.
                            .setSmallIcon(R.drawable.ic_statusbar_pv) //
                            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) //
                            .setTicker(text) //
                            .setWhen(System.currentTimeMillis()) // Set het tijdstip van de melding
                            .setAutoCancel(true) // Melding verwijderen als erop geklikt wordt.
                            .setContentTitle(getString(R.string.app_name))
                            .setStyle(new NotificationCompat.BigTextStyle().bigText(text)) // Style: Tekst over meerdere regels
                            .setContentText(text) // Tekst van de melding
                            .setLights(0xffffffff, 0, 0);

            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 (PrefUtils.getBoolean(PrefUtils.NOTIFICATIONS_LIGHT, false)) {
                notifBuilder.setLights(0xffffffff, 300, 1000);
            }

            NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            mNotifyMgr.notify(mNotificationId, notifBuilder.build());

        }

        PrefUtils.putInt(PrefUtils.NOTIFICATIONS_PREVIOUS_COUNT, newCount);
        mobilizeAllEntries();
        downloadAllImages();

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

From source file:com.connectsdk.discovery.DiscoveryManager.java

/**
 * Create a new instance of DiscoveryManager.
 * Direct use of this constructor is not recommended. In most cases,
 * you should use DiscoveryManager.getInstance() instead.
 *//*  www  . java  2  s.c om*/
public DiscoveryManager(Context context, ConnectableDeviceStore connectableDeviceStore) {
    this.context = context;
    this.connectableDeviceStore = connectableDeviceStore;

    allDevices = new ConcurrentHashMap<String, ConnectableDevice>(8, 0.75f, 2);
    compatibleDevices = new ConcurrentHashMap<String, ConnectableDevice>(8, 0.75f, 2);

    deviceClasses = new ConcurrentHashMap<String, Class<? extends DeviceService>>(4, 0.75f, 2);
    discoveryProviders = new CopyOnWriteArrayList<DiscoveryProvider>();

    discoveryListeners = new CopyOnWriteArrayList<DiscoveryManagerListener>();

    WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    multicastLock = wifiMgr.createMulticastLock("Connect SDK");
    multicastLock.setReferenceCounted(true);

    capabilityFilters = new ArrayList<CapabilityFilter>();
    pairingLevel = PairingLevel.OFF;

    receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

                switch (networkInfo.getState()) {
                case CONNECTED:
                    if (mSearching) {
                        for (DiscoveryProvider provider : discoveryProviders) {
                            provider.start();
                        }
                    }

                    break;

                case DISCONNECTED:
                    Log.w("Connect SDK", "Network connection is disconnected");

                    for (DiscoveryProvider provider : discoveryProviders) {
                        provider.reset();
                    }

                    allDevices.clear();

                    for (ConnectableDevice device : compatibleDevices.values()) {
                        handleDeviceLoss(device);
                    }
                    compatibleDevices.clear();

                    for (DiscoveryProvider provider : discoveryProviders) {
                        provider.stop();
                    }

                    break;

                case CONNECTING:
                    break;
                case DISCONNECTING:
                    break;
                case SUSPENDED:
                    break;
                case UNKNOWN:
                    break;
                }
            }
        }
    };

    registerBroadcastReceiver();
}

From source file:net.news.inrss.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        final Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;//from   w w  w  . ja  v a 2s .com

            if (mFavorite) {
                item.setTitle(R.string.menu_unstar).setIcon(R.drawable.ic_star);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.ic_star_border);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    String title = cursor.getString(mTitlePos);
                    startActivity(Intent.createChooser(
                            new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                    .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                            getString(R.string.menu_share)));
                }
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        case R.id.menu_open_in_browser: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            if (cursor != null) {
                String link = cursor.getString(mLinkPos);
                if (link != null) {
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                    startActivity(browserIntent);
                }
            }
            break;
        }
        case R.id.menu_switch_full_original: {
            if (mPreferFullText) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPreferFullText = false;
                        Log.d(TAG, "run: manual call of displayEntry(), fullText=false");
                        mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                    }
                });
            } else {
                Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
                final boolean alreadyMobilized = !cursor.isNull(mMobilizedHtmlPos);

                if (alreadyMobilized) {
                    Log.d(TAG, "onOptionsItemSelected: alreadyMobilized");
                    mPreferFullText = true;
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, "run: manual call of displayEntry(), fullText=true");
                            mEntryPagerAdapter.displayEntry(mCurrentPagerPos, null, true);
                        }
                    });
                } else if (!isRefreshing()) {
                    Log.d(TAG, "onOptionsItemSelected: about to load article...");
                    mPreferFullText = false;
                    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));
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(activity, R.string.network_error, Toast.LENGTH_SHORT).show();
                            }
                        });
                        Log.d(TAG, "onOptionsItemSelected: cannot load article. no internet connection.");
                    }
                } else {
                    Log.d(TAG, "onOptionsItemSelected: refreshing already in progress");
                }
            }
            mShowFullContentItem.setChecked(mPreferFullText);
            break;
        }
        default:
            break;
        }
    }

    return super.onOptionsItemSelected(item);
}

From source file:org.simlar.SimlarService.java

void checkNetworkConnectivityAndRefreshRegisters() {
    final NetworkInfo ni = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
            .getActiveNetworkInfo();/*from   www. j ava  2 s.  c o  m*/

    if (ni == null) {
        Log.e(LOGTAG, "no NetworkInfo found");
        return;
    }

    Log.i(LOGTAG, "NetworkInfo " + ni.getTypeName() + " " + ni.getState());
    if (ni.isConnected()) {
        mLinphoneThread.refreshRegisters();
    }
}

From source file:ch.bfh.instacircle.NetworkActiveActivity.java

/**
 * Checks whether the current network configuration is how it is supposed to
 * be/*w  ww  .j  a va 2s  .c  o m*/
 */
public void checkNetworkState() {
    ConnectivityManager conn = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
    SharedPreferences preferences = getSharedPreferences(PREFS_NAME, 0);
    final String configuredSsid = preferences.getString("SSID", "N/A");
    final String password = preferences.getString("password", "N/A");

    NetworkInfo nInfo = conn.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    String ssid = wifi.getConnectionInfo().getSSID();
    Log.d(TAG, "Currently active SSID: " + ssid);
    // Only check the state if this device is not an access point
    if (!wifiapmanager.isWifiAPEnabled(wifi)) {
        Log.d(TAG, "Configured SSID: " + configuredSsid);
        if (!(nInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED
                && nInfo.getState() == NetworkInfo.State.CONNECTED && ssid.equals(configuredSsid))) {
            if (repairInitiated == false && repairTime + 6000 < System.currentTimeMillis()) {
                repairInitiated = true;
                repairTime = System.currentTimeMillis();
                // create a dialog that ask whether you want to repair the
                // network connection
                AlertDialog alertDialog = new AlertDialog.Builder(this).create();
                alertDialog.setTitle("InstaCircle - Network Connection Lost");
                alertDialog.setMessage(
                        "The connection to the network " + configuredSsid + " has been lost. Try to repair?");
                alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Repair",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                adhoc.connectToNetwork(configuredSsid, password, NetworkActiveActivity.this,
                                        false);
                                repairInitiated = false;
                            }
                        });
                alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Leave",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                WifiManager wifiman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                                new AdhocWifiManager(wifiman).restoreWifiConfiguration(getBaseContext());
                                new WifiAPManager().disableHotspot(wifiman, getBaseContext());
                                NotificationManager notificationManager = (NotificationManager) getSystemService(
                                        Context.NOTIFICATION_SERVICE);
                                notificationManager.cancelAll();
                                Intent stopIntent = new Intent(NetworkActiveActivity.this,
                                        NetworkService.class);
                                stopService(stopIntent);
                                Intent intent = new Intent(NetworkActiveActivity.this, MainActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                            }
                        });
                alertDialog.show();
            }
        } else {
            repairInitiated = false;
        }
    }

}