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.android.providers.downloads.DownloadInfo.java

/**
 * Translate a ConnectivityManager.TYPE_* constant to the corresponding
 * DownloadManager.Request.NETWORK_* bit flag.
 *//*from   ww w .  j  a va  2  s  .c  o m*/
private int translateNetworkTypeToApiFlag(int networkType) {
    switch (networkType) {
    case ConnectivityManager.TYPE_MOBILE:
        return DownloadManager.Request.NETWORK_MOBILE;

    case ConnectivityManager.TYPE_WIFI:
        return DownloadManager.Request.NETWORK_WIFI;

    case ConnectivityManager.TYPE_BLUETOOTH:
        return DownloadManager.Request.NETWORK_BLUETOOTH;

    default:
        return 0;
    }
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handles menu item selection
    switch (item.getItemId()) {
    case R.id.returnToMenu: // Takes user to main menu by finishing the Activity
        finish();/*from  ww  w .  j av  a2s . c  om*/
        return true;
    case R.id.viewAliquotsMenu: // Takes user to aliquot menu
        Intent openAliquotFiles = new Intent("android.intent.action.FILEPICKER");
        openAliquotFiles.putExtra("Default_Directory", "From_Aliquot_Directory");
        startActivityForResult(openAliquotFiles, 1);
        return true;
    case R.id.viewReportSettingsMenu: // Takes user to report settings menu
        Intent openReportSettingsFiles = new Intent("android.intent.action.FILEPICKER");
        openReportSettingsFiles.putExtra("Default_Directory", "Report_Settings_Directory");
        startActivity(openReportSettingsFiles);
        return true;
    case R.id.importFilesMenu: // Takes user to import files menu
        Intent importFiles = new Intent("android.intent.action.IMPORTFILES");
        startActivity(importFiles);
        return true;
    case R.id.viewRootMenu:
        Intent openRootDirectory = new Intent("android.intent.action.FILEPICKER");
        openRootDirectory.putExtra("Default_Directory", "Root_Directory");
        startActivity(openRootDirectory);
        return true;
    case R.id.aboutScreen: // Takes user to about screen
        Intent openAboutScreen = new Intent("android.intent.action.ABOUT");
        startActivity(openAboutScreen);
        return true;
    case R.id.helpMenu: // Takes user to help blog
        // Checks internet connection before downloading files
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
                Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileWifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mobileWifi.isConnected()) {
            Intent openHelpBlog = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(getString(R.string.chroni_help_address)));
            startActivity(openHelpBlog);

        } else {
            new AlertDialog.Builder(this)
                    .setMessage("You are not connected to WiFi, mobile data rates may apply. "
                            + "Do you wish to continue?")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent openHelpBlog = new Intent(Intent.ACTION_VIEW,
                                    Uri.parse(getString(R.string.chroni_help_address)));
                            startActivity(openHelpBlog);
                        }
                    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

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

/**
 * Checks whether the current network configuration is how it is supposed to
 * be/*from  ww  w . ja va2s  . 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;
        }
    }

}

From source file:org.mozilla.mozstumbler.client.mapview.MapFragment.java

public void mapNetworkConnectionChanged() {

    FragmentActivity activity = getActivity();

    if (activity == null) {
        return;/*from   w  w w .j a  v  a  2s . co m*/
    }

    if (activity.getFilesDir() == null) {
        // Not the ideal spot for this check perhaps, but there is no point in checking
        // the network when storage is not available.
        showMapNotAvailableMessage(NoMapAvailableMessage.eNoMapDueToNoAccessibleStorage);
        return;
    }

    mCoverageSetup.getUrlAndInit();

    final ConnectivityManager cm = (ConnectivityManager) getActivity()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo info = cm.getActiveNetworkInfo();
    final boolean hasNetwork = (info != null) && info.isConnected();
    final boolean hasWifi = (info != null) && (info.getType() == ConnectivityManager.TYPE_WIFI);

    if (!hasNetwork) {
        showMapNotAvailableMessage(NoMapAvailableMessage.eNoMapDueToNoInternet);
        return;
    }

    showMapNotAvailableMessage(NoMapAvailableMessage.eHideNoMapMessage);
    setHighBandwidthMap(hasWifi);
}

From source file:org.mozilla.gecko.updater.UpdateService.java

private File downloadUpdatePackage(UpdateInfo info, boolean overwriteExisting) {
    URL url = null;/*from   www .j  ava 2  s .c om*/
    try {
        url = info.uri.toURL();
    } catch (java.net.MalformedURLException e) {
        Log.e(LOGTAG, "failed to read URL: ", e);
        return null;
    }

    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
    path.mkdirs();
    String fileName = new File(url.getFile()).getName();
    File downloadFile = new File(path, fileName);

    if (!overwriteExisting && info.buildID.equals(getLastBuildID()) && downloadFile.exists()) {
        // The last saved buildID is the same as the one for the current update. We also have a file
        // already downloaded, so it's probably the package we want. Verify it to be sure and just
        // return that if it matches.

        if (verifyDownloadedPackage(downloadFile)) {
            Log.i(LOGTAG, "using existing update package");
            return downloadFile;
        } else {
            // Didn't match, so we're going to download a new one.
            downloadFile.delete();
        }
    }

    if (!info.buildID.equals(getLastBuildID())) {
        // Delete the previous package when a new version becomes available.
        deleteUpdatePackage(getLastFileName());
    }

    Log.i(LOGTAG, "downloading update package");
    sendCheckUpdateResult(CheckUpdateResult.DOWNLOADING);

    OutputStream output = null;
    InputStream input = null;

    mDownloading = true;
    mCancelDownload = false;
    showDownloadNotification(downloadFile);

    try {
        NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected() && netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            mWifiLock.acquire();
        }

        URLConnection conn = openConnectionWithProxy(info.uri);
        int length = conn.getContentLength();

        output = new BufferedOutputStream(new FileOutputStream(downloadFile));
        input = new BufferedInputStream(conn.getInputStream());

        byte[] buf = new byte[BUFSIZE];
        int len = 0;

        int bytesRead = 0;
        int lastNotify = 0;

        while ((len = input.read(buf, 0, BUFSIZE)) > 0 && !mCancelDownload) {
            output.write(buf, 0, len);
            bytesRead += len;
            // Updating the notification takes time so only do it every 1MB
            if (bytesRead - lastNotify > 1048576) {
                mBuilder.setProgress(length, bytesRead, false);
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
                lastNotify = bytesRead;
            }
        }

        mNotificationManager.cancel(NOTIFICATION_ID);

        // if the download was canceled by the user
        // delete the update package
        if (mCancelDownload) {
            Log.i(LOGTAG, "download canceled by user!");
            downloadFile.delete();

            return null;
        } else {
            Log.i(LOGTAG, "completed update download!");
            return downloadFile;
        }
    } catch (Exception e) {
        downloadFile.delete();
        showDownloadFailure();

        Log.e(LOGTAG, "failed to download update: ", e);
        return null;
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (java.io.IOException e) {
        }

        try {
            if (output != null)
                output.close();
        } catch (java.io.IOException e) {
        }

        mDownloading = false;

        if (mWifiLock.isHeld()) {
            mWifiLock.release();
        }
    }
}

From source file:org.pidome.client.services.aidl.service.SystemServiceAidl.java

private void setHome() {
    if (prefs != null) {
        if (prefs.getBoolPreference("wifiConnectHomeEnabled", false)) {
            ConnectivityManager connManager = (ConnectivityManager) getSystemService(
                    Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
                if (connectionInfo != null) {
                    String SSID = connectionInfo.getSSID();
                    String BSSID = connectionInfo.getBSSID();
                    if (SSID != null && BSSID != null) {
                        if (SSID.equals(prefs.getStringPreference("wifiConnectSSID",
                                java.util.UUID.randomUUID().toString()))
                                && BSSID.equals(prefs.getStringPreference("wifiConnectBSSID",
                                        java.util.UUID.randomUUID().toString()))) {
                            singleThreadfPipeExecutor.execute((Runnable) () -> {
                                int i = SystemServiceAidl.this.clientCallBackList.beginBroadcast();
                                while (i > 0) {
                                    i--;
                                    try {
                                        clientCallBackList.beginBroadcast();
                                        clientCallBackList.getBroadcastItem(i).updateUserPresence(1);
                                        clientCallBackList.finishBroadcast();
                                    } catch (RemoteException ex) {
                                        Logger.getLogger(SystemServiceAidl.class.getName()).log(Level.SEVERE,
                                                null, ex);
                                    }/*w ww  .j  a v a 2 s . com*/
                                }
                            });
                            localizationService.setHome(true);
                        } else {
                            localizationService.setHome(false);
                        }
                    }
                }
            } else if (networkInfo.isConnected() && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                localizationService.setHome(false);
            }
        }
    }
}

From source file:com.juick.android.MainActivity.java

private void maybeSendUsageReport() {
    if (usageReportThread != null)
        return;/*from w  w w.j  a  v a2  s  .c o m*/
    String sendStats = sp.getString("usage_statistics", "no");
    if (!sendStats.equals("send") && !sendStats.equals("send_wifi"))
        return;
    long last_usage_sent = sp.getLong("last_usage_sent", 0);
    if (last_usage_sent == 0) {
        sp.edit().putLong("last_usage_sent", System.currentTimeMillis()).commit();
        return;
    }
    if (System.currentTimeMillis() - last_usage_sent > WhatsNew.REPORT_SEND_PERIOD) {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (sendStats.equals("send_wifi") && !wifi.isConnected())
            return;
        usageReportThread = new Thread() {
            @Override
            public void run() {
                new WhatsNew(MainActivity.this).reportUsage();
            }
        };
        usageReportThread.start();
    }
}

From source file:com.roamprocess1.roaming4world.syncadapter.SyncAdapter.java

public static int getConnectivityStatus(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (null != activeNetwork) {
        if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
            return SipHome.TYPE_WIFI;

        if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
            return SipHome.TYPE_MOBILE;
    }//from  w ww .ja va2s .  c om
    return SipHome.TYPE_NOT_CONNECTED;
}

From source file:RhodesService.java

private static boolean hasNetworkEx(boolean checkCell, boolean checkWifi, boolean checkEthernet,
        boolean checkWimax, boolean checkBluetooth, boolean checkAny) {
    if (!Capabilities.NETWORK_STATE_ENABLED) {
        Logger.E(TAG, "HAS_NETWORK: Capability NETWORK_STATE disabled");
        return false;
    }//w  ww  . j  a  v a 2  s.  c o  m

    Context ctx = RhodesService.getContext();
    ConnectivityManager conn = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conn == null) {
        Logger.E(TAG, "HAS_NETWORK: cannot create ConnectivityManager");
        return false;
    }

    NetworkInfo[] info = conn.getAllNetworkInfo();
    if (info == null) {
        Logger.E(TAG, "HAS_NETWORK: cannot issue getAllNetworkInfo");
        return false;
    }

    //{
    //   Utils.platformLog("NETWORK", "$$$$$$$$$$$$$$$$$$$   Networks ; $$$$$$$$$$$$$$$$$$$$$$");
    //   for (int i = 0, lim = info.length; i < lim; ++i) 
    //   {
    //      int type = info[i].getType();
    //      String name = info[i].getTypeName();
    //      boolean is_connected = info[i].getState() == NetworkInfo.State.CONNECTED;
    //      Utils.platformLog("NETWORK", "        - Name ["+name+"],  type ["+String.valueOf(type)+"], connected ["+String.valueOf(is_connected)+"]");
    //   }
    //}

    for (int i = 0, lim = info.length; i < lim; ++i) {
        boolean is_connected = info[i].getState() == NetworkInfo.State.CONNECTED;
        int type = info[i].getType();
        if (is_connected) {
            if ((type == ConnectivityManager.TYPE_MOBILE) && (checkCell))
                return true;
            if ((type == ConnectivityManager.TYPE_WIFI) && (checkWifi))
                return true;
            if ((type == 6) && (checkWimax))
                return true;
            if ((type == 9) && (checkEthernet))
                return true;
            if ((type == 7) && (checkBluetooth))
                return true;
            if (checkAny)
                return true;
        }
    }

    Logger.I(TAG, "HAS_NETWORK: all networks are disconnected");

    return false;
}