Example usage for android.net ConnectivityManager TYPE_WIFI

List of usage examples for android.net ConnectivityManager TYPE_WIFI

Introduction

In this page you can find the example usage for android.net ConnectivityManager TYPE_WIFI.

Prototype

int TYPE_WIFI

To view the source code for android.net ConnectivityManager TYPE_WIFI.

Click Source Link

Document

A WIFI data connection.

Usage

From source file:com.heneryh.aquanotes.io.ApexExecutor.java

public void updateOutlet(Cursor cursor, String outletName, int position) throws HandlerException {

    /**//w w  w  .  ja va 2 s.  c o  m
     * The cursor contains all of the controller details.
     */
    String lanUri = cursor.getString(ControllersQuery.LAN_URL);
    String wanUri = cursor.getString(ControllersQuery.WAN_URL);
    String user = cursor.getString(ControllersQuery.USER);
    String pw = cursor.getString(ControllersQuery.PW);
    String ssid = cursor.getString(ControllersQuery.WIFI_SSID);
    String model = cursor.getString(ControllersQuery.MODEL);

    // Uhg, WifiManager stuff below crashes in AVD if wifi not enabled so first we have to check if on wifi
    ConnectivityManager cm = (ConnectivityManager) mActContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nInfo = cm.getActiveNetworkInfo();
    String apexBaseURL;

    if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) {
        // Get the currently connected SSID, if it matches the 'Home' one then use the local WiFi URL rather than the public one
        WifiManager wm = (WifiManager) mActContext.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wInfo = wm.getConnectionInfo();

        // somewhere read this was a quoted string but appears not to be
        if (wInfo.getSSID().equalsIgnoreCase(ssid)) { // the ssid will be quoted in the info class
            apexBaseURL = lanUri;
        } else {
            apexBaseURL = wanUri;
        }
    } else {
        apexBaseURL = wanUri;

    }

    // for this function we need to append to the URL.  I should really
    // check if the "/" was put on the end by the user here to avoid 
    // possible errors.
    if (!apexBaseURL.endsWith("/")) {
        String tmp = apexBaseURL + "/";
        apexBaseURL = tmp;
    }

    // oh, we should also check if it starts with an "http://"
    if (!apexBaseURL.toLowerCase().startsWith("http://")) {
        String tmp = "http://" + apexBaseURL;
        apexBaseURL = tmp;
    }

    // oh, we should also check if it ends with an "status.sht" on the end and remove it.

    // This used to be common for both the Apex and ACiii but during
    // the 4.04 beta Apex release it seemed to have broke and forced
    // me to use status.sht for the Apex.  Maybe it was fixed but I 
    // haven't checked it.
    // edit - this was not needed for the longest while but now that we are pushing just one
    // outlet, the different methods seem to be needed again.  Really not sure why.
    String apexURL;
    if (model.equalsIgnoreCase("AC4")) {
        apexURL = apexBaseURL + "status.sht";
    } else {
        apexURL = apexBaseURL + "cgi-bin/status.cgi";
    }

    //Create credentials for basic auth
    // create a basic credentials provider and pass the credentials
    // Set credentials provider for our default http client so it will use those credentials
    UsernamePasswordCredentials c = new UsernamePasswordCredentials(user, pw);
    BasicCredentialsProvider cP = new BasicCredentialsProvider();
    cP.setCredentials(AuthScope.ANY, c);
    ((DefaultHttpClient) mHttpClient).setCredentialsProvider(cP);

    // Build the POST update which looks like this:
    // form="status"
    // method="post"
    // action="status.sht"
    //
    // name="T5s_state", value="0"   (0=Auto, 1=Man Off, 2=Man On)
    // submit -> name="Update", value="Update"
    // -- or
    // name="FeedSel", value="0"   (0=A, 1=B)
    // submit -> name="FeedCycle", value="Feed"
    // -- or
    // submit -> name="FeedCycle", value="Feed Cancel"

    HttpPost httppost = new HttpPost(apexURL);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

    // Add your data  
    nameValuePairs.add(new BasicNameValuePair("name", "status"));
    nameValuePairs.add(new BasicNameValuePair("method", "post"));
    if (model.equalsIgnoreCase("AC4")) {
        nameValuePairs.add(new BasicNameValuePair("action", "status.sht"));
    } else {
        nameValuePairs.add(new BasicNameValuePair("action", "/cgi-bin/status.cgi"));
    }

    String pendingStateS = String.valueOf(position);
    nameValuePairs.add(new BasicNameValuePair(outletName + "_state", pendingStateS));

    nameValuePairs.add(new BasicNameValuePair("Update", "Update"));
    try {

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse resp = mHttpClient.execute(httppost);
        final int status = resp.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) {
            throw new HandlerException(
                    "Unexpected server response " + resp.getStatusLine() + " for " + httppost.getRequestLine());
        }
    } catch (HandlerException e) {
        throw e;
    } catch (ClientProtocolException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    } catch (IOException e) {
        throw new HandlerException("Problem reading remote response for " + httppost.getRequestLine(), e);
    }

}

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

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

    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:fr.univsavoie.ltp.client.MainActivity.java

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

    // Appliquer le thme LTP a l'ActionBar
    //setTheme(R.style.Theme_ltp);

    // Cration de l'activit principale
    setContentView(R.layout.activity_main);

    // Instancier les classes utiles
    setPopup(new Popup(this));
    setSession(new Session(this));
    setTools(new Tools(this));

    // Afficher la ActionBar
    ActionBar mActionBar = getSupportActionBar();
    mActionBar.setHomeButtonEnabled(true);
    mActionBar.setDisplayShowHomeEnabled(true);

    // MapView settings
    map = (MapView) findViewById(R.id.openmapview);
    map.setTileSource(TileSourceFactory.MAPNIK);
    map.setBuiltInZoomControls(false);//from  w  w w  . j a  va 2s. co  m
    map.setMultiTouchControls(true);

    // MapController settings
    mapController = map.getController();

    //To use MapEventsReceiver methods, we add a MapEventsOverlay:
    overlay = new MapEventsOverlay(this, this);
    map.getOverlays().add(overlay);

    boolean isWifiEnabled = false;
    boolean isGPSEnabled = false;

    // Vrifier si le wifi ou le rseau mobile est activ
    final ConnectivityManager connMgr = (ConnectivityManager) this
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    final NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (wifi.isAvailable() && (wifi.getDetailedState() == DetailedState.CONNECTING
            || wifi.getDetailedState() == DetailedState.CONNECTED)) {
        Toast.makeText(this, R.string.toast_wifi, Toast.LENGTH_LONG).show();
        isWifiEnabled = true;
    } else if (mobile.isAvailable() && (mobile.getDetailedState() == DetailedState.CONNECTING
            || mobile.getDetailedState() == DetailedState.CONNECTED)) {
        Toast.makeText(this, R.string.toast_3G, Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, R.string.toast_aucun_reseau, Toast.LENGTH_LONG).show();
    }

    // Obtenir le service de localisation
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // Verifier si le service de localisation GPS est actif, le cas echeant, tester le rseau
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30 * 1000, 250.0f, this);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        isGPSEnabled = true;
    } else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30 * 1000, 250.0f, this);
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    }

    // Afficher une boite de dialogue et proposer d'activer un ou plusieurs services pas actifs
    if (!isWifiEnabled || !isGPSEnabled) {
        //getTools().showSettingsAlert(this, isWifiEnabled, isGPSEnabled);
    }

    // Si on a une localisation, on dfinit ses coordonnes geopoint
    if (location != null) {
        startPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
    } else {
        // Sinon, on indique des paramtres par dfaut
        location = getTools().getLastKnownLocation(locationManager);
        if (location == null) {
            location = new Location("");
            location.setLatitude(46.227638);
            location.setLongitude(2.213749000000);
        }
        startPoint = new GeoPoint(46.227638, 2.213749000000);
    }

    setLongitude(location.getLongitude());
    setLatitude(location.getLatitude());

    destinationPoint = null;
    viaPoints = new ArrayList<GeoPoint>();

    // On recupre quelques paramtres de la session prcdents si possible
    if (savedInstanceState == null) {
        mapController.setZoom(15);
        mapController.setCenter(startPoint);
    } else {
        mapController.setZoom(savedInstanceState.getInt("zoom_level"));
        mapController.setCenter((GeoPoint) savedInstanceState.getParcelable("map_center"));
    }

    // Crer un overlay sur la carte pour afficher notre point de dpart
    myLocationOverlay = new SimpleLocationOverlay(this, new DefaultResourceProxyImpl(this));
    map.getOverlays().add(myLocationOverlay);
    myLocationOverlay.setLocation(startPoint);

    // Boutton pour zoomer la carte
    ImageButton btZoomIn = (ImageButton) findViewById(R.id.btZoomIn);
    btZoomIn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            map.getController().zoomIn();
        }
    });

    // Boutton pour dezoomer la carte
    ImageButton btZoomOut = (ImageButton) findViewById(R.id.btZoomOut);
    btZoomOut.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            map.getController().zoomOut();
        }
    });

    // Pointeurs d'itinrairea:
    final ArrayList<ExtendedOverlayItem> waypointsItems = new ArrayList<ExtendedOverlayItem>();
    itineraryMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, waypointsItems, map,
            new ViaPointInfoWindow(R.layout.itinerary_bubble, map));
    map.getOverlays().add(itineraryMarkers);
    //updateUIWithItineraryMarkers();

    Button searchButton = (Button) findViewById(R.id.buttonSearch);
    searchButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            handleSearchLocationButton();
        }
    });

    //context menu for clicking on the map is registered on this button. 
    registerForContextMenu(searchButton);

    // Routes et Itinraires
    final ArrayList<ExtendedOverlayItem> roadItems = new ArrayList<ExtendedOverlayItem>();
    roadNodeMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, roadItems, map);
    map.getOverlays().add(roadNodeMarkers);

    if (savedInstanceState != null) {
        mRoad = savedInstanceState.getParcelable("road");
        updateUIWithRoad(mRoad);
    }

    //POIs:
    //POI search interface:
    String[] poiTags = getResources().getStringArray(R.array.poi_tags);
    poiTagText = (AutoCompleteTextView) findViewById(R.id.poiTag);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,
            poiTags);
    poiTagText.setAdapter(adapter);
    Button setPOITagButton = (Button) findViewById(R.id.buttonSetPOITag);
    setPOITagButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //Hide the soft keyboard:
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(poiTagText.getWindowToken(), 0);
            //Start search:
            getPOIAsync(poiTagText.getText().toString());
        }
    });

    //POI markers:
    final ArrayList<ExtendedOverlayItem> poiItems = new ArrayList<ExtendedOverlayItem>();
    poiMarkers = new ItemizedOverlayWithBubble<ExtendedOverlayItem>(this, poiItems, map,
            new POIInfoWindow(map));
    map.getOverlays().add(poiMarkers);
    if (savedInstanceState != null) {
        mPOIs = savedInstanceState.getParcelableArrayList("poi");
        updateUIWithPOI(mPOIs);
    }

    // Load friends ListView
    lvListeFriends = (ListView) findViewById(R.id.listViewFriends);
    //lvListeFriends.setBackgroundResource(R.drawable.listview_roundcorner_item);
    lvListeFriends.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
            Friends item = (Friends) adapter.getItemAtPosition(position);
            if (item.getLongitude() != 0.0 && item.getLatitude() != 0.0) {
                destinationPoint = new GeoPoint(item.getLongitude(), item.getLatitude());
                markerDestination = putMarkerItem(markerDestination, destinationPoint, DEST_INDEX,
                        R.string.destination, R.drawable.marker_destination, -1);
                getRoadAsync();
                map.getController().setCenter(destinationPoint);
            } else {
                Toast.makeText(MainActivity.this, R.string.toast_friend_statut, Toast.LENGTH_LONG).show();
            }
        }
    });

    viewMapFilters = (ScrollView) this.findViewById(R.id.scrollViewMapFilters);
    viewMapFilters.setVisibility(View.GONE);

    // Initialiser tout ce qui est donnes utilisateur propres  l'activit
    init();

    getTools().relocateUser(mapController, map, myLocationOverlay, location);
}

From source file:com.playhaven.android.req.PlayHavenRequest.java

protected static PlayHaven.ConnectionType getConnectionType(Context context) {
    try {//w  ww. j a v  a 2  s  . c  o m
        ConnectivityManager manager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (manager == null)
            return PlayHaven.ConnectionType.NO_NETWORK; // happens during tests

        NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiInfo != null) {
            NetworkInfo.State wifi = wifiInfo.getState();
            if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING)
                return PlayHaven.ConnectionType.WIFI;
        }

        NetworkInfo mobileInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobileInfo != null) {
            NetworkInfo.State mobile = mobileInfo.getState();
            if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING)
                return PlayHaven.ConnectionType.MOBILE;
        }
    } catch (SecurityException e) {
        // ACCESS_NETWORK_STATE permission not granted in the manifest
        return PlayHaven.ConnectionType.NO_PERMISSION;
    }

    return PlayHaven.ConnectionType.NO_NETWORK;
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    //Sets up activity layout
    super.onCreate(savedInstanceState);
    setTheme(android.R.style.Theme_Holo);
    setContentView(R.layout.aliquot_select);

    RelativeLayout aliquotMenuLayout = (RelativeLayout) findViewById(R.id.aliquotSelectBackground);

    //Places background image on layout after theme overriding
    aliquotMenuLayout.setBackground(getResources().getDrawable(R.drawable.background));

    Button aliquotFileSelectButton = (Button) findViewById(R.id.aliquotFileSelectButton);
    aliquotFileSelectButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Opens file picker activity to main menu
            Intent openFilePicker = new Intent("android.intent.action.FILEPICKER");
            openFilePicker.putExtra("Default_Directory", "From_Aliquot_Directory");
            startActivityForResult(openFilePicker, 1); // Opens FilePicker and waits for it to return an Extra (SEE onActivityResult())
        }//from   ww  w . j  av a 2  s  .  c  o m
    });

    aliquotSelectedFileText = (EditText) findViewById(R.id.aliquotFileSelectText); // Contains selected aliquot file name

    // sets the Aliquot file when one has already been selected (through "View Files" menu)
    if (getIntent().hasExtra("AliquotXMLFileName")) {
        String aliquotPath = getIntent().getStringExtra("AliquotXMLFileName");
        aliquotSelectedFileText.setText(splitReportSettingsName(aliquotPath));
    }

    Button aliquotFileSubmitButton = (Button) findViewById(R.id.aliquotFileSubmitButton);
    aliquotFileSubmitButton.setOnClickListener(new View.OnClickListener() {
        // Submits aliquot file to display activity for parsing and displaying in table
        public void onClick(View v) {

            if (aliquotSelectedFileText.getText().length() != 0) {

                // if coming from a previously created table, change the aliquot
                if (getIntent().hasExtra("From_Table")) {
                    if (getIntent().getStringExtra("From_Table").equals("true")) {

                        // if the Aliquot selected is valid, return to the new table
                        if (validateFile(getIntent().getStringExtra("AliquotXMLFileName"))) {
                            Toast.makeText(AliquotMenuActivity.this, "Changing Aliquot...", Toast.LENGTH_LONG)
                                    .show(); // lets user know table is opening
                            Intent returnAliquot = new Intent("android.intent.action.DISPLAY");
                            returnAliquot.putExtra("newAliquot", "true"); // tells if a new Aliquot has been chosen

                            // tells Intent that it is from a previous table that was opened via the History table
                            if (getIntent().hasExtra("fromHistory")) {
                                returnAliquot.putExtra("fromHistory",
                                        getIntent().getStringExtra("fromHistory"));
                                returnAliquot.putExtra("historyAliquot",
                                        getIntent().getStringExtra("AliquotXMLFileName"));

                                if (!getIntent().getStringExtra("fromHistory").equals("true"))
                                    saveCurrentAliquot(); // saves Aliquot if Intent was NOT originally from the History table
                            }

                            else // saves Aliquot if Intent was NOT originally from the History table (and doesn't have extra)
                                saveCurrentAliquot();

                            setResult(RESULT_OK, returnAliquot);
                            finish();

                        } else // if it is not valid, display a message
                            Toast.makeText(AliquotMenuActivity.this, "ERROR: Invalid Aliquot XML file.",
                                    Toast.LENGTH_LONG).show();

                    }

                } else {

                    // if the Aliquot selected is valid, return to the new table
                    if (validateFile(getIntent().getStringExtra("AliquotXMLFileName"))) {
                        // Makes sure there is a file selected
                        Toast.makeText(AliquotMenuActivity.this, "Opening table...", Toast.LENGTH_LONG).show(); // lets user know table is opening
                        Intent openDisplayTable = new Intent("android.intent.action.DISPLAY"); // Opens display table
                        openDisplayTable.putExtra("fromHistory", "false"); // tells Intent that it is not from History table

                        saveCurrentAliquot();

                        startActivity(openDisplayTable); // Starts display activity

                    } else // if it is not valid, display a message
                        Toast.makeText(AliquotMenuActivity.this, "ERROR: Invalid Aliquot XML file.",
                                Toast.LENGTH_LONG).show();

                }

            } else
                // Tells user to select a file for viewing
                Toast.makeText(AliquotMenuActivity.this, "Please select an aliquot file to view.",
                        Toast.LENGTH_LONG).show(); // lets user know table is opening

        }
    });

    igsnText = (EditText) findViewById(R.id.aliquotIGSNText);
    // Checks to see if user profile information has been authenticated for private file access
    // Sets appropriate hint based on if credentials are stored or not
    retrieveCredentials();
    if (!getGeochronUsername().contentEquals("None") && !getGeochronPassword().contentEquals("None"))
        igsnText.setHint("Profile information stored. Private files enabled!");
    else
        igsnText.setHint("No profile information stored. Private files disabled.");

    Button igsnDownloadButton = (Button) findViewById(R.id.aliquotIGSNSubmitButton);
    igsnDownloadButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            // Hides SoftKeyboard When Download Button is Pressed
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(igsnText.getWindowToken(), 0);

            // Checks internet connection before downloading files
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                    Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobileWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (mobileWifi.isConnected()) {
                if (igsnText.getText().length() != 0) {
                    downloadAliquot();
                    igsnText.setText("");
                }
            } else {//Handles lack of wifi connection
                new AlertDialog.Builder(AliquotMenuActivity.this)
                        .setMessage("You are not connected to WiFi, mobile data rates may apply. "
                                + "Do you wish to continue?")
                        // if user selects yes, continue with validation
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                downloadAliquot();
                                igsnText.setText("");
                            }
                        })
                        // if user selects no, just go back
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).show();
            }
        }

    });

    // displays the current Report Settings
    TextView currentReportSettingsLabel = (TextView) findViewById(R.id.aliquotCurrentReportSettingsLabel);
    currentReportSettingsLabel
            .setText("Current Report Settings:\n" + splitReportSettingsName(retrieveReportSettingsFileName()));

    // if no file permissions, asks for them
    if (ContextCompat.checkSelfPermission(this,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this,
                new String[] { android.Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);
    }
}

From source file:org.restcomm.app.utillib.DataObjects.PhoneState.java

public static boolean isNetworkWifi(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null) {
            int wifiState = networkInfo.getType();
            return (wifiState == ConnectivityManager.TYPE_WIFI);
        }/*  w  w  w. j  a  va  2 s  .co  m*/
    }
    return false;
}

From source file:net.peterkuterna.android.apps.devoxxsched.service.SyncService.java

/**
 * Are we connected to a WiFi network?/*from  w  w  w . j a  v  a 2 s  . c om*/
 */
private static boolean isWifiConnected(Context context) {
    final ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager != null) {
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return (networkInfo != null && networkInfo.getState().equals(State.CONNECTED));
    }

    return false;
}

From source file:org.uguess.android.sysinfo.NetStateManager.java

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    if (position > 0) {
        int state = Util.getIntOption(getActivity(), PSTORE_NETMANAGER, PREF_KEY_REMOTE_QUERY, ENABLED);

        if (state == DISABLED) {
            return;
        } else if (state == WIFI_ONLY) {
            ConnectivityManager cm = (ConnectivityManager) getActivity()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (info == null || !info.isConnected()) {
                return;
            }//from ww w  .  j  av  a 2 s .  c  o  m
        }

        ConnectionItem itm = (ConnectionItem) l.getItemAtPosition(position);

        String ip = getValidIP(itm.remote);

        if (!TextUtils.isEmpty(ip)) {
            queryIPInfo(ip);
        } else {
            Util.shortToast(getActivity(), R.string.no_ip_info);
        }
    }
}

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 www.  j  a  v a2 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:com.mobeelizer.mobile.android.MobeelizerRealConnectionManager.java

private boolean isConnecting(final ConnectivityManager connectivityManager) {
    if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) {
        return connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
    }//ww  w .  j av  a2s  .  co m
    return connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting()
            || connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
}