Example usage for android.content Context WIFI_SERVICE

List of usage examples for android.content Context WIFI_SERVICE

Introduction

In this page you can find the example usage for android.content Context WIFI_SERVICE.

Prototype

String WIFI_SERVICE

To view the source code for android.content Context WIFI_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.net.wifi.WifiManager for handling management of Wi-Fi access.

Usage

From source file:com.yozio.android.YozioHelper.java

private void setMacAddress() {
    try {//w  w  w  .j a v  a  2s.  com
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if (wifiManager != null) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();

            if (wifiInfo != null) {
                macAddress = wifiInfo.getMacAddress();
            }
        }
    } catch (Exception e) {
    }
}

From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java

public boolean setUpNetwork(String sIniFile) {
    boolean bRet = false;
    int lcv = 0;/*from  w w  w .j a  va  2  s. c  o m*/
    int lcv2 = 0;
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiConfiguration wc = new WifiConfiguration();
    DoCommand tmpdc = new DoCommand(getApplication());

    String ssid = tmpdc.GetIniData("Network Settings", "SSID", sIniFile);
    String auth = tmpdc.GetIniData("Network Settings", "AUTH", sIniFile);
    String encr = tmpdc.GetIniData("Network Settings", "ENCR", sIniFile);
    String key = tmpdc.GetIniData("Network Settings", "KEY", sIniFile);
    String eap = tmpdc.GetIniData("Network Settings", "EAP", sIniFile);
    String adhoc = tmpdc.GetIniData("Network Settings", "ADHOC", sIniFile);

    Toast.makeText(getApplication().getApplicationContext(), "Starting and configuring network",
            Toast.LENGTH_LONG).show();
    /*
            ContentResolver cr = getContentResolver();
            int nRet;
            try {
    nRet = Settings.System.getInt(cr, Settings.System.WIFI_USE_STATIC_IP);
    String foo2 = "" + nRet;
            } catch (SettingNotFoundException e1) {
    e1.printStackTrace();
            }
    */
    /*
            wc.SSID = "\"Mozilla-Build\"";
            wc.preSharedKey  = "\"MozillaBuildQA500\"";
            wc.hiddenSSID = true;
            wc.status = WifiConfiguration.Status.ENABLED;
            wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
    */
    wc.SSID = "\"" + ssid + "\"";
    //        wc.SSID = "\"Mozilla-G\"";
    //        wc.SSID = "\"Mozilla\"";

    if (auth.contentEquals("wpa2")) {
        wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
        wc.preSharedKey = null;
    }

    if (encr.contentEquals("aes")) {
        wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
    }

    if (eap.contentEquals("peap")) {
        wc.eap.setValue("PEAP");
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
        wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
    }

    wc.status = WifiConfiguration.Status.ENABLED;

    if (!wifi.isWifiEnabled())
        wifi.setWifiEnabled(true);

    while (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
        Thread.yield();
        if (++lcv > 10000)
            return (bRet);
    }

    wl = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL, "SUTAgent");
    if (wl != null)
        wl.acquire();

    WifiConfiguration foo = null;
    int nNetworkID = -1;

    List<WifiConfiguration> connsLst = wifi.getConfiguredNetworks();
    int nConns = connsLst.size();
    for (int i = 0; i < nConns; i++) {

        foo = connsLst.get(i);
        if (foo.SSID.equalsIgnoreCase(wc.SSID)) {
            nNetworkID = foo.networkId;
            wc.networkId = foo.networkId;
            break;
        }
    }

    int res;

    if (nNetworkID != -1) {
        res = wifi.updateNetwork(wc);
    } else {
        res = wifi.addNetwork(wc);
    }

    Log.d("WifiPreference", "add Network returned " + res);

    boolean b = wifi.enableNetwork(res, true);
    Log.d("WifiPreference", "enableNetwork returned " + b);

    wifi.saveConfiguration();

    WifiInfo wi = wifi.getConnectionInfo();
    SupplicantState ss = wi.getSupplicantState();

    lcv = 0;
    lcv2 = 0;

    while (ss.compareTo(SupplicantState.COMPLETED) != 0) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (wi != null)
            wi = null;
        if (ss != null)
            ss = null;
        wi = wifi.getConnectionInfo();
        ss = wi.getSupplicantState();
        if (++lcv > 60) {
            if (++lcv2 > 5) {
                Toast.makeText(getApplication().getApplicationContext(),
                        "Unable to start and configure network", Toast.LENGTH_LONG).show();
                return (bRet);
            } else {
                Toast.makeText(getApplication().getApplicationContext(), "Resetting wifi interface",
                        Toast.LENGTH_LONG).show();
                if (wl != null)
                    wl.release();
                wifi.setWifiEnabled(false);
                while (wifi.getWifiState() != WifiManager.WIFI_STATE_DISABLED) {
                    Thread.yield();
                }

                wifi.setWifiEnabled(true);
                while (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
                    Thread.yield();
                }
                b = wifi.enableNetwork(res, true);
                Log.d("WifiPreference", "enableNetwork returned " + b);
                if (wl != null)
                    wl.acquire();
                lcv = 0;
            }
        }
    }

    lcv = 0;
    while (getLocalIpAddress() == null) {
        if (++lcv > 10000)
            return (bRet);
    }

    Toast.makeText(getApplication().getApplicationContext(), "Network started and configured",
            Toast.LENGTH_LONG).show();
    bRet = true;

    return (bRet);
}

From source file:com.sentaroh.android.SMBSync2.CommonUtilities.java

public boolean isWifiActive() {
    boolean ret = false;
    WifiManager mWifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
    if (mWifi.isWifiEnabled())
        ret = true;//from  w ww.ja  va 2  s.c o m
    addDebugMsg(2, "I", "isWifiActive WifiEnabled=" + ret);
    return ret;
}

From source file:com.dongfang.dicos.sina.UtilSina.java

/**
 * Get a HttpClient object which is setting correctly .
 * /*w ww.ja v  a2 s . c  om*/
 * @param context
 *            : context of activity
 * @return HttpClient: HttpClient object
 */
public static HttpClient getHttpClient(Context context) {
    BasicHttpParams httpParameters = new BasicHttpParams();
    // Set the default socket timeout (SO_TIMEOUT) // in
    // milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setConnectionTimeout(httpParameters, UtilSina.SET_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, UtilSina.SET_SOCKET_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpParameters);
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()) {
        // ??APN
        Uri uri = Uri.parse("content://telephony/carriers/preferapn");
        Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            // ???
            String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
            if (proxyStr != null && proxyStr.trim().length() > 0) {
                HttpHost proxy = new HttpHost(proxyStr, 80);
                client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
            }
            mCursor.close();
        }
    }
    return client;
}

From source file:com.sentaroh.android.SMBSync2.CommonUtilities.java

public String getConnectedWifiSsid() {
    String ret = "";
    WifiManager mWifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
    String ssid = "";
    if (mWifi.isWifiEnabled()) {
        ssid = mWifi.getConnectionInfo().getSSID();
        if (ssid != null && !ssid.equals("0x") && !ssid.equals("<unknown ssid>") && !ssid.equals(""))
            ret = ssid;/*  w w w .  j  av  a 2  s  . com*/
        //         Log.v("","ssid="+ssid);
    }
    addDebugMsg(2, "I",
            "getConnectedWifiSsid WifiEnabled=" + mWifi.isWifiEnabled() + ", SSID=" + ssid + ", result=" + ret);
    return ret;
}

From source file:com.irccloud.android.NetworkConnection.java

@SuppressWarnings("deprecation")
public NetworkConnection() {
    String version;//from w  ww.  j  a  v a 2s .c  o  m
    String network_type = null;
    try {
        version = "/" + IRCCloudApplication.getInstance().getPackageManager().getPackageInfo(
                IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), 0).versionName;
    } catch (Exception e) {
        version = "";
    }

    try {
        ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null)
            network_type = ni.getTypeName();
    } catch (Exception e) {
    }

    try {
        config = new JSONObject(PreferenceManager
                .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext())
                .getString("config", "{}"));
    } catch (JSONException e) {
        e.printStackTrace();
        config = new JSONObject();
    }

    useragent = "IRCCloud" + version + " (" + android.os.Build.MODEL + "; "
            + Locale.getDefault().getCountry().toLowerCase() + "; " + "Android "
            + android.os.Build.VERSION.RELEASE;

    WindowManager wm = (WindowManager) IRCCloudApplication.getInstance()
            .getSystemService(Context.WINDOW_SERVICE);
    useragent += "; " + wm.getDefaultDisplay().getWidth() + "x" + wm.getDefaultDisplay().getHeight();

    if (network_type != null)
        useragent += "; " + network_type;

    useragent += ")";

    WifiManager wfm = (WifiManager) IRCCloudApplication.getInstance().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);
    wifiLock = wfm.createWifiLock(TAG);

    kms = new X509ExtendedKeyManager[1];
    kms[0] = new X509ExtendedKeyManager() {
        @Override
        public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
            return SSLAuthAlias;
        }

        @Override
        public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
            throw new UnsupportedOperationException();
        }

        @Override
        public X509Certificate[] getCertificateChain(String alias) {
            return SSLAuthCertificateChain;
        }

        @Override
        public String[] getClientAliases(String keyType, Principal[] issuers) {
            throw new UnsupportedOperationException();
        }

        @Override
        public String[] getServerAliases(String keyType, Principal[] issuers) {
            throw new UnsupportedOperationException();
        }

        @Override
        public PrivateKey getPrivateKey(String alias) {
            return SSLAuthKey;
        }
    };

    tms = new TrustManager[1];
    tms[0] = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            throw new CertificateException("Not implemented");
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
                trustManagerFactory.init((KeyStore) null);

                for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
                    if (trustManager instanceof X509TrustManager) {
                        X509TrustManager x509TrustManager = (X509TrustManager) trustManager;
                        x509TrustManager.checkServerTrusted(chain, authType);
                    }
                }
            } catch (KeyStoreException e) {
                throw new CertificateException(e);
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException(e);
            }

            if (BuildConfig.SSL_FPS != null && BuildConfig.SSL_FPS.length > 0) {
                try {
                    MessageDigest md = MessageDigest.getInstance("SHA-1");
                    byte[] sha1 = md.digest(chain[0].getEncoded());
                    // http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
                    final char[] hexArray = "0123456789ABCDEF".toCharArray();
                    char[] hexChars = new char[sha1.length * 2];
                    for (int j = 0; j < sha1.length; j++) {
                        int v = sha1[j] & 0xFF;
                        hexChars[j * 2] = hexArray[v >>> 4];
                        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
                    }
                    String hexCharsStr = new String(hexChars);
                    boolean matched = false;
                    for (String fp : BuildConfig.SSL_FPS) {
                        if (fp.equals(hexCharsStr)) {
                            matched = true;
                            break;
                        }
                    }
                    if (!matched)
                        throw new CertificateException("Incorrect CN in cert chain");
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    WebSocketClient.setTrustManagers(tms);
}

From source file:com.devbrackets.android.playlistcore.service.PlaylistServiceCore.java

/**
 * Used to perform the onCreate functionality when the service is actually created.  This
 * should be overridden instead of {@link #onCreate()} due to a bug in some Samsung devices
 * where {@link #onStartCommand(Intent, int, int)} will get called before {@link #onCreate()}.
 *//* w w w.jav a  2  s .c o m*/
protected void onServiceCreate() {
    mediaProgressPoll.setProgressListener(this);
    audioFocusHelper = new AudioFocusHelper(getApplicationContext());
    audioFocusHelper.setAudioFocusCallback(this);

    //Attempts to obtain the wifi lock only if the manifest has requested the permission
    if (getPackageManager().checkPermission(Manifest.permission.WAKE_LOCK,
            getPackageName()) == PackageManager.PERMISSION_GRANTED) {
        wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_FULL, "mcLock");
        wifiLock.setReferenceCounted(false);
    } else {
        Log.w(TAG, "Unable to acquire WAKE_LOCK due to missing manifest permission");
    }

    getPlaylistManager().registerService(this);

    //Another part of the workaround for some Samsung devices
    if (workaroundIntent != null) {
        startService(workaroundIntent);
        workaroundIntent = null;
    }
}

From source file:com.research.net.Utility.java

/**
 * Get a HttpClient object which is setting correctly .
 * /*  ww w .  jav  a 2 s.  com*/
 * @param context
 *            : context of activity
 * @return HttpClient: HttpClient object
 */
public static DefaultHttpClient getHttpClient(Context context) {
    BasicHttpParams httpParameters = new BasicHttpParams();
    // Set the default socket timeout (SO_TIMEOUT) // in
    // milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setConnectionTimeout(httpParameters, Utility.SET_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, Utility.SET_SOCKET_TIMEOUT);
    DefaultHttpClient client = new DefaultHttpClient(httpParameters);
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    /*if (!wifiManager.isWifiEnabled()) {
    // ??PN????
    Uri uri = Uri.parse("content://telephony/carriers/preferapn");
    Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
    if (mCursor != null && mCursor.moveToFirst()) {
        // ??????
        String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
        if (proxyStr != null && proxyStr.trim().length() > 0) {
            HttpHost proxy = new HttpHost(proxyStr, 80);
            client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        }
        mCursor.close();
    }
     }*/
    return client;
}

From source file:org.androidpn.client.NotificationReceiver.java

private void logic(String notificationMessage) {
    // TODO Auto-generated method stub

    // System.out.println("notificationMessage" + notificationMessage);

    // split[0] ????  logic
    // split[1]? parameter
    // split[2]setup ??log?
    ConfigTest.CASE_LIST = new ArrayList<List<ActionBean>>();
    String[] split = notificationMessage.split("###");
    String logic = split[0];/*from  w w  w . j a  va2 s.c o  m*/
    // ??split[0]
    Gson gson = new Gson();
    // TypeToken<List<List<ActionBean>>> actionLogic = new
    // TypeToken<List<List<ActionBean>>>() {
    // };
    TypeToken<List<CaseBean>> actionLogic = new TypeToken<List<CaseBean>>() {
    };

    // ConfigTest.CASE_LIST = gson.fromJson(logic,
    // actionLogic.getType());
    List<CaseBean> behaviorList = gson.fromJson(logic, actionLogic.getType());

    for (int i = 0; i < behaviorList.size(); i++) {
        CaseBean caseBean = behaviorList.get(i);
        List<ActionBean> behavior = caseBean.getBehavior();
        ConfigTest.CASE_LIST.add(behavior);

    }

    // Intent logicIntent = new Intent(context, LogicService.class);
    // context.startService(logicIntent);

    String parameter = split[1];
    // ?split[1]?sdcard
    try {
        JSONArray jsonArray = new JSONArray(parameter);
        for (int i = 0; i < jsonArray.length(); i++) {
            IOUtil.writeStringToFile("[" + jsonArray.getString(i) + "]", "sdcard/testcase",
                    "sdcard/testcase/parameter" + i + ".json", false);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    String setUp = split[2];
    // setUp.json ?
    // ConfigTest.SETUP_PATH = setUp.substring(13, setUp.length() -
    // "\"}]".length());// [{"logpath":"/sdcard/testcase/"}]

    // split[2]json?
    Gson setupGson = new Gson();
    TypeToken<SetupBean> setupType = new TypeToken<SetupBean>() {
    };
    SetupBean setupBean = setupGson.fromJson(split[2], setupType.getType());
    // TelephonyManager tm = (TelephonyManager) context
    // .getSystemService(context.TELEPHONY_SERVICE);

    // ?
    // long time = Long.parseLong(setupBean.getTime());
    // SimpleDateFormat sdf = new
    // SimpleDateFormat("yyyyMMddHHmmss");
    // String sDateTime = sdf.format(time); // 08/31/2006

    // ??
    String setupJson = "[{\"logpath\":\"" + setupBean.getLogpath()
            + context.getSharedPreferences(ConfigSP.SP_reseach, Context.MODE_PRIVATE).getString(
                    ConfigSP.SP_phone_id, "12345")
            + "_" + setupBean.getCasename() + "_" + setupBean.getTime() + "_file" + "\","
            + "\"testcaseparafile\":\"" + setupBean.getLogpath() + "parameter.json\"}]";
    // log??
    ConfigTest.LOG_FILE_NAME = context.getSharedPreferences(ConfigSP.SP_reseach, Context.MODE_PRIVATE)
            .getString(ConfigSP.SP_phone_id, "12345") + "_" + setupBean.getCasename() + "_"
            + setupBean.getTime() + "_file";
    Log.i("--info--time--", setupBean.getTime());
    // action??
    ConfigTest.ACTION_NAME = setupBean.getCasename();
    // log
    ConfigTest.LOG_FILE_TIME = setupBean.getTime();

    // 
    ConfigTest.CLOCK = setupBean.getClock();

    IOUtil.writeStringToFile(setupJson, "sdcard/testcase", "sdcard/testcase/setup.json", false);

    if (setupBean.getDoubleroute().equals("0")) {// wifi
        // ServiceManager serviceManager = new ServiceManager(context);
        // serviceManager.startService();
        /**
         * ???ID?PN?
         */

        // Intent intent = new Intent(context, BatteryService.class);
        // context.stopService(intent);// ???
        // Intent intent1 = new Intent(context, SignalService.class);
        // context.stopService(intent1);// ???

        // ?WifiManager
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        // ?WifiInfo
        mWifiInfo = mWifiManager.getConnectionInfo();
        // WiFi
        // if (mWifiManager.isWifiEnabled()) {
        // mWifiManager.setWifiEnabled(false);
        // }

        /**
         * PN?
         */
        // NotificationService.getinstance().getXmppManager().setIsTesting(true);

        // ?
        Intent logicIntent = new Intent(context, LogicService.class);
        context.startService(logicIntent);
    } else {// ??
            // ?
        Intent logicIntent = new Intent(context, LogicService.class);
        context.startService(logicIntent);
    }

    /*
     * //jar try { IOUtil.writeStreamToFile("sdcard/testcase",
     * contextParam.getResources().getAssets().open("testcase.jar"), new
     * File("sdcard/testcase/testcase.jar")); } catch (IOException e) {
     * e.printStackTrace(); }
     */
    /*
     * String[] cmd = new String[] { "su", "uiautomator runtest " +
     * "/sdcard" + "/" + "testcase" + "/" + "testcase.jar" +
     * " -c com.testcase." + taskArr[i] }; CMDUtil.execShellCMD(cmd);
     */
    /*
     * String[] cmd = new String[] { "su",
     * "uiautomator runtest /sdcard/testcase/UiAutomatorPrjDemo.jar -c com.WeiXinText"
     * }; try { CMDUtil.execShellCMD(cmd); } catch (IOException e) {
     * e.printStackTrace(); } catch (InterruptedException e) {
     * e.printStackTrace(); }
     */

    /*
     * String[] taskArr = {"TelCaseUI", "SMSCaseUI", "WeiXinTextCase"}; try
     * { String[] cmd; for (int i = 0; i < taskArr.length; i++) { cmd = new
     * String[] { "su", "uiautomator runtest " + "/sdcard" + "/" +
     * "testcase" + "/" + "testcase.jar" + " -c com.testcase." + taskArr[i]
     * }; CMDUtil.execShellCMD(cmd); switch (i) { case 0: Thread
     * .sleep(Integer.parseInt(terminalConfigVO.getDialDuration())*
     * Integer.parseInt(terminalConfigVO.getDialRepeatTimes())*1000+
     * 10*1000); break; case 1: Thread.sleep(20*1000); break; case 2:
     * 
     * break; default: break; } // Thread.sleep(30*1000); } } catch
     * (IOException e) { e.printStackTrace(); } catch (InterruptedException
     * e) { e.printStackTrace(); }
     */

    // // ?###{}
    //
    //
    // ///
    // String[] split = notificationMessage.split("###");
    // Gson gson = new Gson();
    // if ("\"?\"".equals(split[0])) {
    // //
    // TypeToken<ArrayList<ConfigMsgBean>> ruleToken = new
    // TypeToken<ArrayList<ConfigMsgBean>>(){};
    // ArrayList<ConfigMsgBean> configList = gson.fromJson(split[1],
    // ruleToken.getType());
    // SharedPreferences sp =
    // context.getSharedPreferences(ConfigPN.SP_SET,
    // Context.MODE_PRIVATE);
    // Editor editor = sp.edit();
    // for (int i = 0; i < configList.size(); i++) {
    // ConfigMsgBean ConfigMsgBean = configList.get(i);
    // editor.putString(ConfigMsgBean.getStrEnKey(),
    // ConfigMsgBean.getStrParameter());
    // }
    // editor.commit();
    // return;
    // }
    //
    //
    // //
    // if ("".equals(split[0])) {
    // //
    // TypeToken<CalibrationBean> calibrationToken = new
    // TypeToken<CalibrationBean>(){};
    // CalibrationBean calibrationBean = gson.fromJson(split[1],
    // calibrationToken.getType());
    // Intent correctIntent = new Intent(contextParam, AcCorrect.class);
    // correctIntent.putExtra("strProject",
    // calibrationBean.getStrProject());
    // correctIntent.putExtra("dateTime",
    // calibrationBean.getStrDateTime());
    // correctIntent.putExtra("strBands",
    // calibrationBean.getStrBands());
    // correctIntent.putExtra("signalWaitTime",
    // calibrationBean.getSignalWaitTime()+"");
    // correctIntent.putExtra("executeWaitTime",
    // calibrationBean.getExecuteWaitTime()+"");
    // correctIntent.putExtra("upWaitTime",
    // calibrationBean.getUpWaitTime()+"");
    // correctIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    // contextParam.startActivity(correctIntent);
    // return;
    // }
    //
    //
    // //
    // TypeToken<List<RelationBean>> relationToken = new
    // TypeToken<List<RelationBean>>(){};
    // List<RelationBean> relationJson = gson.fromJson(split[0],
    // relationToken.getType());
    // IntentData.getInstance().setIntent_Testing_relationList(relationJson);
    //
    // //
    // TypeToken<Map<String, ArrayList<RuleBean>>> ruleToken = new
    // TypeToken<Map<String, ArrayList<RuleBean>>>(){};
    // Map<String, ArrayList<RuleBean>> ruleJson =
    // gson.fromJson(split[1], ruleToken.getType());
    // IntentData.getInstance().setIntent_Testing_ruleMap(ruleJson);
    //
    // //?
    // String dateTimeServer = split[2];
    // SharedPreferences sp =
    // contextParam.getSharedPreferences(ConfigPN.SP_PN,
    // Context.MODE_PRIVATE);
    // Editor editor = sp.edit();
    // editor.putString("dateTimeServer", dateTimeServer);
    // editor.commit();
    //
    // //?/
    // String taskType = split[3];
    //
    // //
    // int testTimes = relationJson.get(0).getIntTestTimes();
    // IntentData.getInstance().setIntent_Testing_times(testTimes);
    //
    //
    // //
    // //??||???
    // String interactionAPID =
    // contextParam.getSharedPreferences(ConfigPN.SP_SET,
    // Context.MODE_PRIVATE).getString(ConfigPN.SP_SET_GLOBALAPID, "");
    // String interactionAPPW =
    // contextParam.getSharedPreferences(ConfigPN.SP_SET,
    // Context.MODE_PRIVATE).getString(ConfigPN.SP_SET_GLOBALAPPW, "");
    // if (interactionAPID.equals("") || interactionAPPW.equals("")) {
    // Toast.makeText(contextParam, "",
    // Toast.LENGTH_LONG).show();
    // } else {
    // //
    // if (taskType.equals("normalTask")) {
    // Intent skipAcTestingIntent = new Intent(contextParam,
    // AcTesting.class);
    // skipAcTestingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    // contextParam.startActivity(skipAcTestingIntent);
    // //
    // } else if (taskType.equals("terminalTask")) {
    // // SimpleDateFormat sdf = new
    // SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // Date date = new Date(Long.parseLong(dateTimeServer));
    //
    //
    // AlarmManager am = (AlarmManager)
    // context.getSystemService(Context.ALARM_SERVICE);
    // Intent intent_broadcast = new Intent(context,
    // TimerReceiver.class);
    // PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
    // 0, intent_broadcast, 0);
    // System.out.println(Long.parseLong(dateTimeServer)+ " - "+
    // System.currentTimeMillis());
    // am.set(AlarmManager.RTC_WAKEUP, Long.parseLong(dateTimeServer),
    // pendingIntent); //????
    // }
    // }
}

From source file:com.landenlabs.all_devtool.NetFragment.java

public void updateList() {
    // Time today = new Time(Time.getCurrentTimezone());
    // today.setToNow();
    // today.format(" %H:%M:%S")
    Date dt = new Date();
    m_titleTime.setText(m_timeFormat.format(dt));

    boolean expandAll = m_list.isEmpty();
    m_list.clear();/*from  w ww  .j a  v a 2s  .  c  o m*/

    // Swap colors
    int color = m_rowColor1;
    m_rowColor1 = m_rowColor2;
    m_rowColor2 = color;

    ActivityManager actMgr = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);

    try {
        String androidIDStr = Settings.Secure.getString(getContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);
        addBuild("Android ID", androidIDStr);

        try {
            AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getContext());
            final String adIdStr = adInfo.getId();
            final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
            addBuild("Ad ID", adIdStr);
        } catch (IOException e) {
            // Unrecoverable error connecting to Google Play services (e.g.,
            // the old version of the service doesn't support getting AdvertisingId).
        } catch (GooglePlayServicesNotAvailableException e) {
            // Google Play services is not available entirely.
        }

        /*
        try {
        InstanceID instanceID = InstanceID.getInstance(getContext());
        if (instanceID != null) {
            // Requires a Google Developer project ID.
            String authorizedEntity = "<need to make this on google developer site>";
            instanceID.getToken(authorizedEntity, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
            addBuild("Instance ID", instanceID.getId());
        }
        } catch (Exception ex) {
        }
        */

        ConfigurationInfo info = actMgr.getDeviceConfigurationInfo();
        addBuild("OpenGL", info.getGlEsVersion());
    } catch (Exception ex) {
        m_log.e(ex.getMessage());
    }

    // --------------- Connection Services -------------
    try {
        ConnectivityManager connMgr = (ConnectivityManager) getActivity()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
        if (netInfo != null) {
            Map<String, String> netListStr = new LinkedHashMap<String, String>();

            putIf(netListStr, "Available", "Yes", netInfo.isAvailable());
            putIf(netListStr, "Connected", "Yes", netInfo.isConnected());
            putIf(netListStr, "Connecting", "Yes", !netInfo.isConnected() && netInfo.isConnectedOrConnecting());
            putIf(netListStr, "Roaming", "Yes", netInfo.isRoaming());
            putIf(netListStr, "Extra", netInfo.getExtraInfo(), !TextUtils.isEmpty(netInfo.getExtraInfo()));
            putIf(netListStr, "WhyFailed", netInfo.getReason(), !TextUtils.isEmpty(netInfo.getReason()));
            if (Build.VERSION.SDK_INT >= 16) {
                putIf(netListStr, "Metered", "Avoid heavy use", connMgr.isActiveNetworkMetered());
            }

            netListStr.put("NetworkType", netInfo.getTypeName());
            if (connMgr.getAllNetworkInfo().length > 1) {
                netListStr.put("Available Networks:", " ");
                for (NetworkInfo netI : connMgr.getAllNetworkInfo()) {
                    if (netI.isAvailable()) {
                        netListStr.put(" " + netI.getTypeName(), netI.isAvailable() ? "Yes" : "No");
                    }
                }
            }

            if (netInfo.isConnected()) {
                try {
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                            .hasMoreElements();) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                .hasMoreElements();) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress()) {
                                if (inetAddress.getHostAddress() != null) {
                                    String ipType = (inetAddress instanceof Inet4Address) ? "IPv4" : "IPv6";
                                    netListStr.put(intf.getName() + " " + ipType, inetAddress.getHostAddress());
                                }
                                // if (!TextUtils.isEmpty(inetAddress.getHostName()))
                                //     listStr.put( "HostName", inetAddress.getHostName());
                            }
                        }
                    }
                } catch (Exception ex) {
                    m_log.e("Network %s", ex.getMessage());
                }
            }

            addBuild("Network...", netListStr);
        }
    } catch (Exception ex) {
        m_log.e("Network %s", ex.getMessage());
    }

    // --------------- Telephony Services -------------
    TelephonyManager telephonyManager = (TelephonyManager) getActivity()
            .getSystemService(Context.TELEPHONY_SERVICE);
    if (telephonyManager != null) {
        Map<String, String> cellListStr = new LinkedHashMap<String, String>();
        try {
            cellListStr.put("Version", telephonyManager.getDeviceSoftwareVersion());
            cellListStr.put("Number", telephonyManager.getLine1Number());
            cellListStr.put("Service", telephonyManager.getNetworkOperatorName());
            cellListStr.put("Roaming", telephonyManager.isNetworkRoaming() ? "Yes" : "No");
            cellListStr.put("Type", getNetworkTypeName(telephonyManager.getNetworkType()));

            if (Build.VERSION.SDK_INT >= 17) {
                if (telephonyManager.getAllCellInfo() != null) {
                    for (CellInfo cellInfo : telephonyManager.getAllCellInfo()) {
                        String cellName = cellInfo.getClass().getSimpleName();
                        int level = 0;
                        if (cellInfo instanceof CellInfoCdma) {
                            level = ((CellInfoCdma) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoGsm) {
                            level = ((CellInfoGsm) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoLte) {
                            level = ((CellInfoLte) cellInfo).getCellSignalStrength().getLevel();
                        } else if (cellInfo instanceof CellInfoWcdma) {
                            if (Build.VERSION.SDK_INT >= 18) {
                                level = ((CellInfoWcdma) cellInfo).getCellSignalStrength().getLevel();
                            }
                        }
                        cellListStr.put(cellName, "Level% " + String.valueOf(100 * level / 4));
                    }
                }
            }

            for (NeighboringCellInfo cellInfo : telephonyManager.getNeighboringCellInfo()) {
                int level = cellInfo.getRssi();
                cellListStr.put("Cell level%", String.valueOf(100 * level / 31));
            }

        } catch (Exception ex) {
            m_log.e("Cell %s", ex.getMessage());
        }

        if (!cellListStr.isEmpty()) {
            addBuild("Cell...", cellListStr);
        }
    }

    // --------------- Bluetooth Services (API18) -------------
    if (Build.VERSION.SDK_INT >= 18) {
        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (bluetoothAdapter != null) {

                Map<String, String> btListStr = new LinkedHashMap<String, String>();

                btListStr.put("Enabled", bluetoothAdapter.isEnabled() ? "yes" : "no");
                btListStr.put("Name", bluetoothAdapter.getName());
                btListStr.put("ScanMode", String.valueOf(bluetoothAdapter.getScanMode()));
                btListStr.put("State", String.valueOf(bluetoothAdapter.getState()));
                Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                // If there are paired devices
                if (pairedDevices.size() > 0) {
                    // Loop through paired devices
                    for (BluetoothDevice device : pairedDevices) {
                        // Add the name and address to an array adapter to show in a ListView
                        btListStr.put("Paired:" + device.getName(), device.getAddress());
                    }
                }

                BluetoothManager btMgr = (BluetoothManager) getActivity()
                        .getSystemService(Context.BLUETOOTH_SERVICE);
                if (btMgr != null) {
                    // btMgr.getAdapter().
                }
                addBuild("Bluetooth", btListStr);
            }

        } catch (Exception ex) {

        }
    }

    // --------------- Wifi Services -------------
    final WifiManager wifiMgr = (WifiManager) getContext().getApplicationContext()
            .getSystemService(Context.WIFI_SERVICE);

    if (wifiMgr != null && wifiMgr.isWifiEnabled() && wifiMgr.getDhcpInfo() != null) {

        if (mSystemBroadcastReceiver == null) {
            mSystemBroadcastReceiver = new SystemBroadcastReceiver(wifiMgr);
            getActivity().registerReceiver(mSystemBroadcastReceiver, INTENT_FILTER_SCAN_AVAILABLE);
        }

        if (ActivityCompat.checkSelfPermission(getContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(getContext(),
                        Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (wifiMgr.getScanResults() == null || wifiMgr.getScanResults().size() != mLastScanSize) {
                mLastScanSize = wifiMgr.getScanResults().size();
                wifiMgr.startScan();
            }
        }

        Map<String, String> wifiListStr = new LinkedHashMap<String, String>();
        try {
            DhcpInfo dhcpInfo = wifiMgr.getDhcpInfo();

            wifiListStr.put("DNS1", Formatter.formatIpAddress(dhcpInfo.dns1));
            wifiListStr.put("DNS2", Formatter.formatIpAddress(dhcpInfo.dns2));
            wifiListStr.put("Default Gateway", Formatter.formatIpAddress(dhcpInfo.gateway));
            wifiListStr.put("IP Address", Formatter.formatIpAddress(dhcpInfo.ipAddress));
            wifiListStr.put("Subnet Mask", Formatter.formatIpAddress(dhcpInfo.netmask));
            wifiListStr.put("Server IP", Formatter.formatIpAddress(dhcpInfo.serverAddress));
            wifiListStr.put("Lease Time(sec)", String.valueOf(dhcpInfo.leaseDuration));

            WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
            if (wifiInfo != null) {
                wifiListStr.put("LinkSpeed Mbps", String.valueOf(wifiInfo.getLinkSpeed()));
                int numberOfLevels = 10;
                int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), numberOfLevels + 1);
                wifiListStr.put("Signal%", String.valueOf(100 * level / numberOfLevels));
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiListStr.put("MAC", getMacAddr());
                } else {
                    wifiListStr.put("MAC", wifiInfo.getMacAddress());
                }
            }

        } catch (Exception ex) {
            m_log.e("Wifi %s", ex.getMessage());
        }

        if (!wifiListStr.isEmpty()) {
            addBuild("WiFi...", wifiListStr);
        }

        try {
            if (ActivityCompat.checkSelfPermission(getContext(),
                    Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(getContext(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                List<ScanResult> listWifi = wifiMgr.getScanResults();
                if (listWifi != null && !listWifi.isEmpty()) {
                    int idx = 0;

                    for (ScanResult scanResult : listWifi) {
                        Map<String, String> wifiScanListStr = new LinkedHashMap<String, String>();
                        wifiScanListStr.put("SSID", scanResult.SSID);
                        if (Build.VERSION.SDK_INT >= 23) {
                            wifiScanListStr.put("  Name", scanResult.operatorFriendlyName.toString());
                            wifiScanListStr.put("  Venue", scanResult.venueName.toString());
                        }

                        //        wifiScanListStr.put("  BSSID ",scanResult.BSSID);
                        wifiScanListStr.put("  Capabilities", scanResult.capabilities);
                        //       wifiScanListStr.put("  Center Freq", String.valueOf(scanResult.centerFreq0));
                        //       wifiScanListStr.put("  Freq width", String.valueOf(scanResult.channelWidth));
                        wifiScanListStr.put("  Level, Freq",
                                String.format("%d, %d", scanResult.level, scanResult.frequency));
                        if (Build.VERSION.SDK_INT >= 17) {
                            Date wifiTime = new Date(scanResult.timestamp);
                            wifiScanListStr.put("  Time", wifiTime.toLocaleString());
                        }
                        addBuild(String.format("WiFiScan #%d", ++idx), wifiScanListStr);
                    }
                }
            }
        } catch (Exception ex) {
            m_log.e("WifiList %s", ex.getMessage());
        }

        try {
            List<WifiConfiguration> listWifiCfg = wifiMgr.getConfiguredNetworks();

            for (WifiConfiguration wifiCfg : listWifiCfg) {
                Map<String, String> wifiCfgListStr = new LinkedHashMap<String, String>();
                if (Build.VERSION.SDK_INT >= 23) {
                    wifiCfgListStr.put("Name", wifiCfg.providerFriendlyName);
                }
                wifiCfgListStr.put("SSID", wifiCfg.SSID);
                String netStatus = "";
                switch (wifiCfg.status) {
                case WifiConfiguration.Status.CURRENT:
                    netStatus = "Connected";
                    break;
                case WifiConfiguration.Status.DISABLED:
                    netStatus = "Disabled";
                    break;
                case WifiConfiguration.Status.ENABLED:
                    netStatus = "Enabled";
                    break;
                }
                wifiCfgListStr.put(" Status", netStatus);
                wifiCfgListStr.put(" Priority", String.valueOf(wifiCfg.priority));
                if (null != wifiCfg.wepKeys) {
                    //               wifiCfgListStr.put(" wepKeys", TextUtils.join(",", wifiCfg.wepKeys));
                }
                String protocols = "";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.RSN))
                    protocols = "RSN ";
                if (wifiCfg.allowedProtocols.get(WifiConfiguration.Protocol.WPA))
                    protocols = protocols + "WPA ";
                wifiCfgListStr.put(" Protocols", protocols);

                String keyProt = "";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE))
                    keyProt = "none";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP))
                    keyProt = "WPA+EAP ";
                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK))
                    keyProt = "WPA+PSK ";
                wifiCfgListStr.put(" Keys", keyProt);

                if (wifiCfg.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) {
                    // Remove network connections with no Password.
                    // wifiMgr.removeNetwork(wifiCfg.networkId);
                }

                addBuild("WiFiCfg #" + wifiCfg.networkId, wifiCfgListStr);
            }

        } catch (Exception ex) {
            m_log.e("Wifi Cfg List %s", ex.getMessage());
        }
    }

    if (expandAll) {
        // updateList();
        int count = m_list.size();
        for (int position = 0; position < count; position++)
            m_listView.expandGroup(position);
    }

    m_adapter.notifyDataSetChanged();
}