Example usage for android.net.wifi WifiInfo getSSID

List of usage examples for android.net.wifi WifiInfo getSSID

Introduction

In this page you can find the example usage for android.net.wifi WifiInfo getSSID.

Prototype

public String getSSID() 

Source Link

Document

Returns the service set identifier (SSID) of the current 802.11 network.

Usage

From source file:ch.ethz.coss.nervousnet.vm.sensors.ConnectivitySensor.java

public void runConnectivitySensor() {
    Log.d(LOG_TAG, "Inside runConnectivitySensor");
    if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(context,
            android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;/*from   w w  w.  java2 s. c o  m*/
    }
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    int networkType = -1;
    boolean isRoaming = false;
    if (isConnected) {
        networkType = activeNetwork.getType();
        isRoaming = activeNetwork.isRoaming();
    }

    String wifiHashId = "";
    int wifiStrength = Integer.MIN_VALUE;

    if (networkType == ConnectivityManager.TYPE_WIFI) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wi = wm.getConnectionInfo();
        StringBuilder wifiInfoBuilder = new StringBuilder();
        wifiInfoBuilder.append(wi.getBSSID());
        wifiInfoBuilder.append(wi.getSSID());
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(wifiInfoBuilder.toString().getBytes());
            wifiHashId = new String(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
        }
        wifiStrength = wi.getRssi();
    }

    byte[] cdmaHashId = new byte[32];
    byte[] lteHashId = new byte[32];
    byte[] gsmHashId = new byte[32];
    byte[] wcdmaHashId = new byte[32];

    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    List<CellInfo> cis = tm.getAllCellInfo();
    if (cis != null) {
        // New method
        for (CellInfo ci : cis) {
            if (ci.isRegistered()) {
                if (ci instanceof CellInfoCdma) {
                    CellInfoCdma cic = (CellInfoCdma) ci;
                    cdmaHashId = generateMobileDigestId(cic.getCellIdentity().getSystemId(),
                            cic.getCellIdentity().getNetworkId(), cic.getCellIdentity().getBasestationId());
                }
                if (ci instanceof CellInfoGsm) {
                    CellInfoGsm cic = (CellInfoGsm) ci;
                    gsmHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(),
                            cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCid());
                }
                if (ci instanceof CellInfoLte) {
                    CellInfoLte cic = (CellInfoLte) ci;
                    lteHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(),
                            cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCi());
                }
                if (ci instanceof CellInfoWcdma) {
                    CellInfoWcdma cic = (CellInfoWcdma) ci;
                    wcdmaHashId = generateMobileDigestId(cic.getCellIdentity().getMcc(),
                            cic.getCellIdentity().getMnc(), cic.getCellIdentity().getCid());
                }
            }
        }
    } else {
        // Legacy method
        CellLocation cl = tm.getCellLocation();
        if (cl instanceof CdmaCellLocation) {
            CdmaCellLocation cic = (CdmaCellLocation) cl;
            cdmaHashId = generateMobileDigestId(cic.getSystemId(), cic.getNetworkId(), cic.getBaseStationId());
        }
        if (cl instanceof GsmCellLocation) {
            GsmCellLocation cic = (GsmCellLocation) cl;
            gsmHashId = generateMobileDigestId(cic.getLac(), 0, cic.getCid());
        }
    }

    StringBuilder mobileHashBuilder = new StringBuilder();
    mobileHashBuilder.append(new String(cdmaHashId));
    mobileHashBuilder.append(new String(lteHashId));
    mobileHashBuilder.append(new String(gsmHashId));
    mobileHashBuilder.append(new String(wcdmaHashId));

    dataReady(new ConnectivityReading(System.currentTimeMillis(), isConnected, networkType, isRoaming,
            wifiHashId, wifiStrength, mobileHashBuilder.toString()));

}

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

/**
 * Execute a {@link HttpGet} request, passing a valid response through
 * to the specified XML parser.  This common method can then be used to parse
 * various kinds of XML feeds./*from ww  w  . j  av  a2  s  . c  o  m*/
 */
public void executeGet(Uri ctrlUri, DefaultHandler xmlParser) throws HandlerException {

    controllerUri = ctrlUri;
    Cursor cursor = null;

    String username = null;
    String password = null;
    String apexBaseURL = null;
    String apexWANURL = null;
    String apexWiFiURL = null;
    String apexWiFiSID = null;
    String controllerType = null;

    /**
     * Poll the database for facts about this controller
     */
    try {
        cursor = mDbResolver.query(controllerUri, ControllersQuery.PROJECTION, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            username = cursor.getString(ControllersQuery.USER);
            password = cursor.getString(ControllersQuery.PW);
            apexWANURL = cursor.getString(ControllersQuery.WAN_URL);
            apexWiFiURL = cursor.getString(ControllersQuery.LAN_URL);
            apexWiFiSID = cursor.getString(ControllersQuery.WIFI_SSID);
            controllerType = cursor.getString(ControllersQuery.MODEL);
        }
    } catch (SQLException e) {
        throw new HandlerException("Database error getting controller data.");
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    /**
     * Depending on whether or not we are on the 'Home' wifi network we want to use either the
     * WAN or LAN URL.
     * 
     * Uhg, WifiManager stuff below crashes if wifi not enabled so first we have to check if
     * on wifi.
     */
    ConnectivityManager cm = (ConnectivityManager) mActContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo.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(apexWiFiSID)) {
            apexBaseURL = apexWiFiURL;
        } else {
            apexBaseURL = apexWANURL;
        }
    } else {
        apexBaseURL = apexWANURL;
    }

    /**
     * for this function we need to append to the URL.  To be safe we try to catch various
     * forms of URL that might be entered by the user:
     * 
     * check if the "/" was put on the end
     */
    if (!apexBaseURL.endsWith("/")) {
        String tmp = apexBaseURL + "/";
        apexBaseURL = tmp;
    }

    /**
     * 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.

    /**
     * When all cleaned up, add the xml portion of the url to grab the status.
     * 
     * TODO: we tried to make this call handle various xml feeds but this call is hardcoded
     * for the status feed.
     */
    String apexURL = apexBaseURL + "cgi-bin/status.xml";

    final HttpUriRequest request = new HttpGet(apexURL);
    executeWhySeparate(request, xmlParser, username, password);
}

From source file:by.zatta.pilight.connection.ConnectionService.java

private boolean addedToPreferences() {
    String currentNetwork = null;
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (!(info == null)) {
        // Log.d(TAG, "networkInfo: " + info.getExtraInfo());
        currentNetwork = info.getExtraInfo();
    }//  w  w w. ja va 2s .  c  o  m
    WifiManager wifiManager = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    if (!(wifiInfo == null)) {
        // Log.d(TAG, "wifiInfo:" + wifiInfo.getSSID());
        currentNetwork = wifiInfo.getSSID();
    }
    if (currentNetwork == null)
        return false;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(aCtx);
    String previous = prefs.getString("networks_known", "");
    // Log.d(TAG, previous);
    currentNetwork = currentNetwork.replace("\"", "");
    if (previous.contains(currentNetwork)) {
        // Log.d(TAG, previous + " did contain " + currentNetwork);
        return false;
    } else {
        previous = previous + "|&|" + currentNetwork;
        // Log.d(TAG, previous);
        Editor edit = prefs.edit();
        edit.putString("networks_known", previous);
        edit.commit();
        return true;
    }
}

From source file:org.sufficientlysecure.keychain.ui.transfer.presenter.TransferPresenter.java

private String getConnectedWifiSsid() {
    WifiManager wifiManager = (WifiManager) context.getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);
    if (wifiManager == null) {
        return null;
    }/*from w w w.j a v  a  2 s  .com*/
    WifiInfo info = wifiManager.getConnectionInfo();
    if (info == null) {
        return null;
    }
    // getSSID will return the ssid in quotes if it is valid utf-8. we only return it in that case.
    String ssid = info.getSSID();
    if (ssid.charAt(0) != '"') {
        return null;
    }
    return ssid.substring(1, ssid.length() - 1);
}

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

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

    /**//from   w  w w.  j av  a 2s  .co  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:com.heneryh.aquanotes.io.ApexExecutor.java

public void feedCycle(Cursor cursor, int cycleNumber) throws HandlerException {

    /**/*from   w ww  . ja  va 2 s .  c  om*/
     * 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);

    String apexBaseURL;

    // Determine if we are on the LAN or WAN and then use appropriate URL

    // Uhg, WifiManager stuff below crashes 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();

    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;
    }

    // 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 cycleNumberString = Integer.toString(cycleNumber).trim();
    if (cycleNumber < 4) {
        nameValuePairs.add(new BasicNameValuePair("FeedSel", cycleNumberString));
        nameValuePairs.add(new BasicNameValuePair("FeedCycle", "Feed"));
    } else {
        nameValuePairs.add(new BasicNameValuePair("FeedCycle", "Feed Cancel"));
    }

    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:org.eeiiaa.wifi.WifiConnector.java

public ConnectionInfo getConnectionInfo() {
        ConnectionInfo info = new ConnectionInfo();
        WifiInfo winf = mWifiMgr.getConnectionInfo();
        info.winf = winf;//from w  ww .ja  v a 2  s .co m

        if (winf != null) {
            if (winf.getSSID() != null) {
                String winfSsid = unQuote(winf.getSSID());
                if (winfSsid.equals(mNetssid)) {
                    DhcpInfo dhinf = mWifiMgr.getDhcpInfo();
                    info.dhinf = dhinf;
                }
            }
        }
        return info;
    }

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

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override//from   w  ww .  j  a  v  a  2  s.c  o m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initialize text fragment that displays intro text.
    /*SimpleTextFragment introFragment = (SimpleTextFragment)
            getSupportFragmentManager().findFragmentById(R.id.intro_fragment);
    introFragment.setText(R.string.welcome_message);
    introFragment.getTextView().setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16.0f);*/

    // Initialize the logging framework.
    initializeLogging();

    // Initialize the send buttons with a listener that for click events
    mTb = (ToggleButton) findViewById(R.id.tb_gl);
    mTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                throwCmd("gln");
            } else {
                throwCmd("glf");
            }
        }
    });

    mTb = (ToggleButton) findViewById(R.id.tb_dl);
    mTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                throwCmd("dln");
            } else {
                throwCmd("dlf");
            }
        }
    });

    mTb = (ToggleButton) findViewById(R.id.tb_gu);
    mTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                throwCmd("gun");
            } else {
                throwCmd("guf");
            }
        }
    });
    mTb = (ToggleButton) findViewById(R.id.tb_gd);
    mTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                throwCmd("gdn");
            } else {
                throwCmd("gdf");
            }
        }
    });

    mTb = (ToggleButton) findViewById(R.id.tb_du);
    mTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                throwCmd("dun");
            } else {
                throwCmd("duf");
            }
        }
    });
    mTb = (ToggleButton) findViewById(R.id.tb_dd);
    mTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                throwCmd("ddn");
            } else {
                throwCmd("ddf");
            }
        }
    });

    mTb = (ToggleButton) findViewById(R.id.tb_pc);
    mTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                throwCmd("pcn");
            } else {
                throwCmd("pcf");
            }
        }
    });
    mTb = (ToggleButton) findViewById(R.id.tb_tv);
    mTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                throwCmd("tvn");
            } else {
                throwCmd("tvf");
            }
        }
    });

    mTb = (ToggleButton) findViewById(R.id.tb_pl);
    mTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                throwCmd("pln");
            } else {
                throwCmd("plf");
            }
        }
    });
    mTb = (ToggleButton) findViewById(R.id.tb_pk);
    mTb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                throwCmd("pkn");
            } else {
                throwCmd("pkf");
            }
        }
    });

    // piotr
    findViewById(R.id.radioButton0).setEnabled(false);
    findViewById(R.id.radioButton1).setEnabled(false);
    findViewById(R.id.radioButton2).setEnabled(false);
    findViewById(R.id.radioButton3).setEnabled(false);
    findViewById(R.id.radioButton4).setEnabled(false);

    myUrls = new ardUrl[5];
    long nonce = myTime();
    String result = "";
    for (int i = 0; i < 5; i++) {
        myUrls[i] = new ardUrl();
        myUrls[i].stat = false;
    }
    myUrls[0].url = "http://piotrlech.ddns.net:60000/";
    myUrls[1].url = "http://piotrlech.ddns.net:58052/";
    myUrls[2].url = "http://192.168.1.25:84/";
    myUrls[3].url = "http://192.168.1.42:83/";
    myUrls[4].url = "http://192.168.2.42:83/";

    chkArduino asyncTask0, asyncTask1, asyncTask2, asyncTask3, asyncTask4;
    WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    String ap = wifiInfo.getSSID();
    ap = ap.replace("\"", "");
    if (ap.equals("FunBox-1EFF") || ap.equals("U4")) {
        //for (int i = 2; i < 4; i++) {
        //    new chkArduino().execute(myUrls[i].url + "stm" + "/" + nonce + "/" + result);
        //}
        asyncTask2 = new chkArduino();
        //asyncTask2.execute(myUrls[2].url + "stm" + "/" + nonce + "/" + result);
        asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                myUrls[2].url + "stm" + "/" + nonce + "/" + result);
        asyncTask3 = new chkArduino();
        //asyncTask3.execute(myUrls[3].url + "stm" + "/" + nonce + "/" + result);
        asyncTask3.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                myUrls[3].url + "stm" + "/" + nonce + "/" + result);
        //StartAsyncTaskInParallel(asyncTask3);
    }
    if (ap.equals("PENTAGRAM")) {
        //for (int i = 4; i < 5; i++) {
        //    new chkArduino().execute(myUrls[i].url + "stm" + "/" + nonce + "/" + result);
        //}
        asyncTask4 = new chkArduino();
        asyncTask4.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                myUrls[4].url + "stm" + "/" + nonce + "/" + result);
    }
    //for (int i = 0; i < 2; i++) {
    //    new chkArduino().execute(myUrls[i].url + "stm" + "/" + nonce + "/" + result);
    //}
    asyncTask0 = new chkArduino();
    asyncTask0.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
            myUrls[0].url + "stm" + "/" + nonce + "/" + result);
    asyncTask1 = new chkArduino();
    asyncTask1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
            myUrls[1].url + "stm" + "/" + nonce + "/" + result);
}

From source file:org.eeiiaa.wifi.WifiConnector.java

public void connect() {

        mConnected = false;//from  w  w  w. ja v  a2 s  . c o  m
        mWaitingConnection = false;

        transmitted = received = 0;

        // TODO: check if not already connected
        WifiInfo info = mWifiMgr.getConnectionInfo();

        if (info != null) {
            String currssid = unQuote(info.getSSID());
            if (currssid != null) {
                // already connected
                if (currssid.equals(mNetssid)) {
                    mConnected = true;
                    Log.i(TAG, "already successfully connected to: " + currssid);
                    notifyConnectionListener();
                    mContext.registerReceiver(this, filter_);
                    return;
                }
            }
        }

        if (!mConnected) {

            Log.i(TAG, "starting standard scan...");

            // when connection requested than register
            boolean enabled = mWifiMgr.isWifiEnabled();
            if (!enabled) {
                Log.i(TAG, "enabling wifi...");

                mWifiMgr.setWifiEnabled(true);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Log.e(TAG, "interrupt exception when sleeping untill wifi is enabled");
                    e.printStackTrace();
                }
            }
            mConnecting = true;
            mContext.registerReceiver(this, filter_);
            mWifiMgr.startScan();
            Log.i(TAG, "starting scan prior to connection...");

        }
    }

From source file:com.lgallardo.qbittorrentclient.NotifierService.java

protected void getSettings() {
    // Preferences stuff
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);

    builderPrefs = new StringBuilder();

    builderPrefs.append("\n" + sharedPrefs.getString("language", "NULL"));

    // Get values from preferences
    currentServer = Integer.parseInt(sharedPrefs.getString("currentServer", "1"));

    hostname = sharedPrefs.getString("hostname", "");
    subfolder = sharedPrefs.getString("subfolder", "");

    protocol = sharedPrefs.getString("protocol", "NULL");

    // If user leave the field empty, set 8080 port
    try {/*  w  ww .j a v a2  s  . com*/
        port = Integer.parseInt(sharedPrefs.getString("port", "8080"));
    } catch (NumberFormatException e) {
        port = 8080;

    }
    username = sharedPrefs.getString("username", "NULL");
    password = sharedPrefs.getString("password", "NULL");
    https = sharedPrefs.getBoolean("https", false);

    // Check https
    if (https) {
        protocol = "https";

    } else {
        protocol = "http";
    }

    // Get connection and data timeouts
    try {
        connection_timeout = Integer.parseInt(sharedPrefs.getString("connection_timeout", "10"));
    } catch (NumberFormatException e) {
        connection_timeout = 10;
    }

    try {
        data_timeout = Integer.parseInt(sharedPrefs.getString("data_timeout", "20"));
    } catch (NumberFormatException e) {
        data_timeout = 20;
    }

    qb_version = sharedPrefs.getString("qb_version", "3.2.x");

    cookie = sharedPrefs.getString("qbCookie2", null);

    // Get last state
    lastState = sharedPrefs.getString("lastState", null);

    // Notifications
    enable_notifications = sharedPrefs.getBoolean("enable_notifications", false);
    completed_hashes = sharedPrefs.getString("completed_hashes" + currentServer, "");

    // Get local SSID properties
    ssid = sharedPrefs.getString("ssid", "");
    local_hostname = sharedPrefs.getString("local_hostname", null);

    // If user leave the field empty, set 8080 port
    try {
        local_port = Integer.parseInt(sharedPrefs.getString("local_port", "-1"));
    } catch (NumberFormatException e) {
        local_port = -1;

    }

    // Set SSI and local hostname and port
    if (ssid != null && !ssid.equals("")) {

        // Get SSID if WiFi
        WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
        String wifiSSID = wifiInfo.getSSID();

        //            Log.d("Debug", "NotifierService - WiFi SSID: " + wifiSSID);
        //            Log.d("Debug", "NotifierService - SSID: " + ssid);

        if (wifiSSID.equals("\"" + ssid + "\"") && wifiMgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {

            if (local_hostname != null && !local_hostname.equals("")) {
                hostname = local_hostname;
            }

            if (local_port != -1) {
                port = local_port;
            }

            //                Log.d("Debug", "NotifierService - hostname: " + hostname);
            //                Log.d("Debug", "NotifierService - port: " + port);
            //                Log.d("Debug", "NotifierService - local_hostname: " + local_hostname);
            //                Log.d("Debug", "NotifierService -  local_port: " + local_port);

        }
    }

    // Get keystore for self-signed certificate
    keystore_path = sharedPrefs.getString("keystore_path" + currentServer, "");
    keystore_password = sharedPrefs.getString("keystore_password" + currentServer, "");

}