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.drinviewer.droiddrinviewer.DrinViewerBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
        NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
        if (networkInfo.isConnected()) {
            /**//from  w  ww. ja  v  a 2  s.c om
             * WiFi is connected, get its broadcast 
             * address and start the discovery process
             * repeated at a fixed time interval
             */
            wifiBroadcastAddress = getWiFiBroadcastAddress(context);
            startAlarmRepeater(context);
        } else {
            wifiBroadcastAddress = null;
        }
    } else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
        NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && !networkInfo.isConnected()) {
            /**
             * WiFi is disconnected, stop the discovery
             * process repeating, it would be a waste of resources
             */
            wifiBroadcastAddress = null;
            stopAlarmRepeater(context);
        }
    } else if (intent.getAction().equals(context.getResources().getString(R.string.broadcast_startdiscovery))
            || intent.getAction()
                    .equals(context.getResources().getString(R.string.broadcast_cleanhostcollection))) {

        boolean startService = true;
        /**
         * Calls the DiscoverServerService asking to do a discovery
         * or a clean host collection by simply forwarding the received action
         */
        Intent service = new Intent(context, DiscoverServerService.class);
        service.setAction(intent.getAction());

        if (intent.getAction().equals(context.getResources().getString(R.string.broadcast_startdiscovery))) {

            ConnectivityManager connManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            wifiBroadcastAddress = (mWifi.isConnected()) ? getWiFiBroadcastAddress(context) : null;
            startService = wifiBroadcastAddress != null;
            service.putExtra("wifiBroadcastAddress", wifiBroadcastAddress);
        }

        if (startService)
            startWakefulService(context, service);

        if (intent.getBooleanExtra("stopservice", false)) {
            context.stopService(service);
        }
    } else if (intent.getAction()
            .equals(context.getResources().getString(R.string.broadcast_startalarmrepeater))) {
        /**
         * start the alarm repeater only if WiFi is connected already
         * used by ServerListFragment.onServiceConnected method to start the discovery
         * if the application is launched being already connected to a WiFi network
         */
        ConnectivityManager connManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mWifi.isConnected()) {
            // if we're called from the activity, try to get a broadcast address
            if (intent.getBooleanExtra("forcegetbroadcast", false))
                wifiBroadcastAddress = getWiFiBroadcastAddress(context);
            startAlarmRepeater(context);
        } else {
            wifiBroadcastAddress = null;
        }
    } else if (intent.getAction()
            .equals(context.getResources().getString(R.string.broadcast_stopalarmrepeater))) {
        /**
         *  stop the alarm repeater. period.
         *  used by DrinViewerApplication.onTerminate method
         */
        wifiBroadcastAddress = null;
        stopAlarmRepeater(context);
    }
}

From source file:biz.shadowservices.DegreesToolbox.DataFetcher.java

public boolean isWifi(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (info == null) {
        return false;
    } else {//from   w w  w.  j a v  a2  s  .c o  m
        return info.isConnected();
    }
}

From source file:com.vinexs.tool.NetworkManager.java

public static boolean isWifiNetwork(Context context) {
    NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE))
            .getActiveNetworkInfo();/*from  w w  w  . ja  va 2  s.  c  om*/
    return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI;
}

From source file:com.secupwn.aimsicd.utils.Helpers.java

/**
 * Checks if Network connectivity is available to download OpenCellID data
 * Requires:        android:name="android.permission.ACCESS_NETWORK_STATE"
 *//*from  w  w w  .  j  a  v a 2 s  .co  m*/
public static Boolean isNetAvailable(Context context) {
    try {
        ConnectivityManager cM = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiInfo = cM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobileInfo = cM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (wifiInfo != null && mobileInfo != null) {
            return wifiInfo.isConnected() || mobileInfo.isConnected();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return false;
}

From source file:com.orangelabs.rcs.platform.network.AndroidNetworkFactory.java

/**
 * Returns the local IP address of a given network interface
 * /*  ww w. j  a  va  2s.c o  m*/
 * @param dnsEntry remote address to find an according local socket address
  * @param type the type of the network interface, should be either
  *        {@link android.net.ConnectivityManager#TYPE_WIFI} or {@link android.net.ConnectivityManager#TYPE_MOBILE}
 * @return Address
 */
// Changed by Deutsche Telekom
public String getLocalIpAddress(DnsResolvedFields dnsEntry, int type) {
    String ipAddress = null;
    try {
        // What kind of remote address (P-CSCF) are we trying to reach?
        boolean isIpv4 = InetAddressUtils.isIPv4Address(dnsEntry.ipAddress);

        // check all available interfaces
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); (en != null)
                && en.hasMoreElements();) {
            NetworkInterface netIntf = (NetworkInterface) en.nextElement();
            for (Enumeration<InetAddress> addr = netIntf.getInetAddresses(); addr.hasMoreElements();) {
                InetAddress inetAddress = addr.nextElement();
                ipAddress = IpAddressUtils.extractHostAddress(inetAddress.getHostAddress());
                // if IP address version doesn't match to remote address
                // version then skip
                if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()
                        && (InetAddressUtils.isIPv4Address(ipAddress) == isIpv4)) {
                    String intfName = netIntf.getDisplayName().toLowerCase();
                    // some devices do list several interfaces though only
                    // one is active
                    if (((type == ConnectivityManager.TYPE_WIFI) && intfName.startsWith("wlan"))
                            || ((type == ConnectivityManager.TYPE_MOBILE) && !intfName.startsWith("wlan"))) {
                        return ipAddress;
                    }
                }
            }
        }
    } catch (Exception e) {
        if (logger.isActivated()) {
            logger.error("getLocalIpAddress failed with ", e);
        }
    }
    return ipAddress;
}

From source file:fr.gcastel.freeboxV6GeekIncDownloader.services.FreeboxDownloaderService.java

public boolean isConnectedViaWifi() {
    boolean result = false;
    if (zeContext != null) {
        ConnectivityManager cm = (ConnectivityManager) zeContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        result = (info != null) && (info.getType() == ConnectivityManager.TYPE_WIFI);
    }/*from  w  w w.  j a v  a  2  s  .co m*/
    return result;
}

From source file:com.frostwire.android.gui.NetworkManager.java

public boolean isDataWIFIUp() {
    ConnectivityManager connectivityManager = getConnectivityManager();
    return isNetworkTypeUp(connectivityManager, ConnectivityManager.TYPE_WIFI);
}

From source file:com.swisscom.safeconnect.fragment.InfoFragment.java

private String getConnectedSSID() {
    String ssid = null;/* ww  w. j a  v a 2  s.co  m*/
    ConnectivityManager connManager = (ConnectivityManager) getActivity()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (networkInfo.isConnected()) {
        final WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
        final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.getSSID())) {
            ssid = connectionInfo.getSSID();
        }
    }
    return ssid;
}

From source file:com.rickendirk.rsgwijzigingen.ZoekService.java

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    boolean clusters_enabled = sp.getBoolean("pref_cluster_enabled", true);
    boolean alleenBijWifi = sp.getBoolean("pref_auto_zoek_wifi", false);
    boolean isAchtergrond = intent.getBooleanExtra("isAchtergrond", false);
    if (alleenBijWifi && isAchtergrond) {
        ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo nwInfo = conManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (!nwInfo.isConnectedOrConnecting()) {
            //Later weer proberen: nu geen wifi
            setAlarmIn20Min();/*from w w  w.j a v a 2 s  .  c  om*/
            return;
        }
    }
    Wijzigingen wijzigingen = checkerNieuw(clusters_enabled);
    //Tracken dat er is gezocht
    OwnApplication application = (OwnApplication) getApplication();
    Tracker tracker = application.getDefaultTracker();

    if (isAchtergrond) {
        tracker.send(
                new HitBuilders.EventBuilder().setCategory("Acties").setAction("Zoeken_achtergrond").build());
        sendNotification(wijzigingen);
    } else {
        tracker.send(
                new HitBuilders.EventBuilder().setCategory("Acties").setAction("Zoeken_voorgrond").build());
        boolean isFoutMelding = wijzigingen.isFoutmelding();
        if (!isFoutMelding)
            wijzigingen.saveToSP(this);
        broadcastResult(wijzigingen, clusters_enabled);
    }
}

From source file:com.iiitd.networking.UDPMessenger.java

/**
 * Sends a broadcast message (TAG EPOCH_TIME message). Opens a new socket in case it's closed.
 * @param message the message to send (multicast). It can't be null or 0-characters long.
 * @return/*from   ww w  .  ja  v a  2s .co  m*/
 * @throws IllegalArgumentException
 */
public boolean sendMessage(String message) throws IllegalArgumentException {
    if (message == null || message.length() == 0)
        throw new IllegalArgumentException();

    // Check for WiFi connectivity
    ConnectivityManager connManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (mWifi == null || !mWifi.isConnected()) {
        Log.d(DEBUG_TAG,
                "Sorry! You need to be in a WiFi network in order to send UDP multicast packets. Aborting.");
        return false;
    }

    // Check for IP address
    WifiManager wim = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    int ip = wim.getConnectionInfo().getIpAddress();

    // Create the send socket
    if (socket == null) {
        try {
            socket = new DatagramSocket();
        } catch (SocketException e) {
            Log.d(DEBUG_TAG, "There was a problem creating the sending socket. Aborting.");
            e.printStackTrace();
            return false;
        }
    }

    // Build the packet
    DatagramPacket packet;
    Message msg = new Message(TAG, message);
    byte data[] = msg.toString().getBytes();

    WifiInfo wifiInfo = wim.getConnectionInfo();
    int ipa = wifiInfo.getIpAddress();
    String ipAddress = Formatter.formatIpAddress(ipa);

    try {
        //         packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipToString(ip, true)), MULTICAST_PORT);
        packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipAddress), MULTICAST_PORT);
    } catch (UnknownHostException e) {
        Log.d(DEBUG_TAG, "It seems that " + ipToString(ip, true) + " is not a valid ip! Aborting.");
        e.printStackTrace();
        return false;
    }

    try {
        socket.send(packet);
    } catch (IOException e) {
        Log.d(DEBUG_TAG, "There was an error sending the UDP packet. Aborted.");
        e.printStackTrace();
        return false;
    }

    return true;
}