List of usage examples for android.bluetooth BluetoothAdapter isEnabled
@RequiresPermission(Manifest.permission.BLUETOOTH) public boolean isEnabled()
From source file:org.envirocar.app.activity.MainActivity.java
private void openFragment(int position) { FragmentManager manager = getSupportFragmentManager(); switch (position) { // Go to the dashboard case DASHBOARD: if (isFragmentVisible(DASHBOARD_TAG)) { break; }//from w ww. ja va 2 s.c om Fragment dashboardFragment = getSupportFragmentManager().findFragmentByTag(DASHBOARD_TAG); if (dashboardFragment == null) { dashboardFragment = new DashboardFragment(); } manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); manager.beginTransaction().replace(R.id.content_frame, dashboardFragment, DASHBOARD_TAG).commit(); break; //Start the Login activity case LOGIN: if (UserManager.instance().isLoggedIn()) { UserManager.instance().logOut(); ListTracksFragment listMeasurementsFragment = (ListTracksFragment) getSupportFragmentManager() .findFragmentByTag("MY_TRACKS"); // check if this fragment is initialized if (listMeasurementsFragment != null) { listMeasurementsFragment.clearRemoteTracks(); } else { //the remote tracks need to be removed in any case DbAdapterImpl.instance().deleteAllRemoteTracks(); } Crouton.makeText(this, R.string.bye_bye, Style.CONFIRM).show(); } else { if (isFragmentVisible(LOGIN_TAG)) { break; } LoginFragment loginFragment = new LoginFragment(); manager.beginTransaction().replace(R.id.content_frame, loginFragment, LOGIN_TAG) .addToBackStack(null).commit(); } break; // Go to the settings case SETTINGS: Intent configIntent = new Intent(this, SettingsActivity.class); startActivity(configIntent); break; // Go to the track list case MY_TRACKS: if (isFragmentVisible(MY_TRACKS_TAG)) { break; } ListTracksFragment listMeasurementFragment = new ListTracksFragment(); manager.beginTransaction().replace(R.id.content_frame, listMeasurementFragment, MY_TRACKS_TAG) .addToBackStack(null).commit(); break; // Start or stop the measurement process case START_STOP_MEASUREMENT: if (!navDrawerItems[position].isEnabled()) return; SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(this.getApplicationContext()); String remoteDevice = preferences.getString(org.envirocar.app.activity.SettingsActivity.BLUETOOTH_KEY, null); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null && adapter.isEnabled() && remoteDevice != null) { if (CarManager.instance().getCar() == null) { Intent settingsIntent = new Intent(this, SettingsActivity.class); startActivity(settingsIntent); } else { /* * We are good to go. process the state and stuff */ OnTrackModeChangeListener trackModeListener = new OnTrackModeChangeListener() { @Override public void onTrackModeChange(int tm) { trackMode = tm; } }; createStartStopUtil().processButtonClick(trackModeListener); } } else { Intent settingsIntent = new Intent(this, SettingsActivity.class); startActivity(settingsIntent); } break; case HELP: if (isFragmentVisible(HELP_TAG)) { break; } HelpFragment helpFragment = new HelpFragment(); manager.beginTransaction().replace(R.id.content_frame, helpFragment, HELP_TAG).addToBackStack(null) .commit(); break; case SEND_LOG: if (isFragmentVisible(SEND_LOG_TAG)) { break; } SendLogFileFragment logFragment = new SendLogFileFragment(); manager.beginTransaction().replace(R.id.content_frame, logFragment, SEND_LOG_TAG).addToBackStack(null) .commit(); default: break; case LOGBOOK: if (isFragmentVisible(LOGBOOK_TAG)) { break; } LogbookFragment logbookFragment = new LogbookFragment(); manager.beginTransaction().replace(R.id.content_frame, logbookFragment, LOGBOOK_TAG) .addToBackStack(null).commit(); break; } drawer.closeDrawer(drawerList); }
From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java
/** Called when the activity is first created. */ @Override//from www . j a v a 2 s . c o m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); fixScreenOrientation(); DoCommand dc = new DoCommand(getApplication()); Log.i("SUTAgentAndroid", dc.prgVersion); dc.FixDataLocalPermissions(); // Get configuration settings from "ini" file File dir = getFilesDir(); File iniFile = new File(dir, "SUTAgent.ini"); String sIniFile = iniFile.getAbsolutePath(); String lc = dc.GetIniData("General", "LogCommands", sIniFile); if (lc != "" && Integer.parseInt(lc) == 1) { SUTAgentAndroid.LogCommands = true; } SUTAgentAndroid.RegSvrIPAddr = dc.GetIniData("Registration Server", "IPAddr", sIniFile); SUTAgentAndroid.RegSvrIPPort = dc.GetIniData("Registration Server", "PORT", sIniFile); SUTAgentAndroid.HardwareID = dc.GetIniData("Registration Server", "HARDWARE", sIniFile); SUTAgentAndroid.Pool = dc.GetIniData("Registration Server", "POOL", sIniFile); SUTAgentAndroid.sTestRoot = dc.GetIniData("Device", "TestRoot", sIniFile); SUTAgentAndroid.Abi = android.os.Build.CPU_ABI; log(dc, "onCreate"); dc.SetTestRoot(SUTAgentAndroid.sTestRoot); Log.i("SUTAgentAndroid", "Test Root: " + SUTAgentAndroid.sTestRoot); tv = (TextView) this.findViewById(R.id.Textview01); if (getLocalIpAddress() == null) setUpNetwork(sIniFile); String macAddress = "Unknown"; if (android.os.Build.VERSION.SDK_INT > 8) { try { NetworkInterface iface = NetworkInterface .getByInetAddress(InetAddress.getAllByName(getLocalIpAddress())[0]); if (iface != null) { byte[] mac = iface.getHardwareAddress(); if (mac != null) { StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); for (int i = 0; i < mac.length; i++) { f.format("%02x%s", mac[i], (i < mac.length - 1) ? ":" : ""); } macAddress = sUniqueID = sb.toString(); } } } catch (UnknownHostException ex) { } catch (SocketException ex) { } } else { // Fall back to getting info from wifiman on older versions of Android, // which don't support the NetworkInterface interface WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (wifiMan != null) { WifiInfo wifi = wifiMan.getConnectionInfo(); if (wifi != null) macAddress = wifi.getMacAddress(); if (macAddress != null) sUniqueID = macAddress; } } if (sUniqueID == null) { BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter(); if ((ba != null) && (ba.isEnabled() != true)) { ba.enable(); while (ba.getState() != BluetoothAdapter.STATE_ON) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } sUniqueID = ba.getAddress(); ba.disable(); while (ba.getState() != BluetoothAdapter.STATE_OFF) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } else { if (ba != null) { sUniqueID = ba.getAddress(); sUniqueID.toLowerCase(); } } } if (sUniqueID == null) { TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); if (mTelephonyMgr != null) { sUniqueID = mTelephonyMgr.getDeviceId(); if (sUniqueID == null) { sUniqueID = "0011223344556677"; } } } String hwid = getHWID(this); sLocalIPAddr = getLocalIpAddress(); Toast.makeText(getApplication().getApplicationContext(), "SUTAgent [" + sLocalIPAddr + "] ...", Toast.LENGTH_LONG).show(); String sConfig = dc.prgVersion + lineSep; sConfig += "Test Root: " + sTestRoot + lineSep; sConfig += "Unique ID: " + sUniqueID + lineSep; sConfig += "HWID: " + hwid + lineSep; sConfig += "ABI: " + Abi + lineSep; sConfig += "OS Info" + lineSep; sConfig += "\t" + dc.GetOSInfo() + lineSep; sConfig += "Screen Info" + lineSep; int[] xy = dc.GetScreenXY(); sConfig += "\t Width: " + xy[0] + lineSep; sConfig += "\t Height: " + xy[1] + lineSep; sConfig += "Memory Info" + lineSep; sConfig += "\t" + dc.GetMemoryInfo() + lineSep; sConfig += "Network Info" + lineSep; sConfig += "\tMac Address: " + macAddress + lineSep; sConfig += "\tIP Address: " + sLocalIPAddr + lineSep; displayStatus(sConfig); sRegString = "NAME=" + sUniqueID; sRegString += "&IPADDR=" + sLocalIPAddr; sRegString += "&CMDPORT=" + 20701; sRegString += "&DATAPORT=" + 20700; sRegString += "&OS=Android-" + dc.GetOSInfo(); sRegString += "&SCRNWIDTH=" + xy[0]; sRegString += "&SCRNHEIGHT=" + xy[1]; sRegString += "&BPP=8"; sRegString += "&MEMORY=" + dc.GetMemoryConfig(); sRegString += "&HARDWARE=" + HardwareID; sRegString += "&POOL=" + Pool; sRegString += "&ABI=" + Abi; String sTemp = Uri.encode(sRegString, "=&"); sRegString = "register " + sTemp; pruneCommandLog(dc.GetSystemTime(), dc.GetTestRoot()); if (!bNetworkingStarted) { Thread thread = new Thread(null, doStartService, "StartServiceBkgnd"); thread.start(); bNetworkingStarted = true; Thread thread2 = new Thread(null, doRegisterDevice, "RegisterDeviceBkgnd"); thread2.start(); } monitorBatteryState(); // If we are returning from an update let'em know we're back Thread thread3 = new Thread(null, doUpdateCallback, "UpdateCallbackBkgnd"); thread3.start(); final Button goButton = (Button) findViewById(R.id.Button01); goButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); }
From source file:com.pdmanager.views.patient.TechnicianActivity.java
private boolean isBluetoothEnabled() { try {/*www .j a va2 s .co m*/ BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter != null) { return mBluetoothAdapter.isEnabled(); } return false; } catch (Exception ex) { return false; } }
From source file:com.example.shoe.DirectionsTest.java
public void bluetooth() { // create a bluetooth adapter BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); if (bluetooth != null) { // continue with setup, an adapter exists String status;/*from ww w . j a v a 2s. co m*/ if (bluetooth.isEnabled()) { // get address of bluetooth device String mydeviceaddress = bluetooth.getAddress(); // get name of bluetooth device String mydevicename = bluetooth.getName(); int stateInt = bluetooth.getState(); String state = ""; switch (stateInt) { case 0: state = "STATE_DISCONNECTING"; break; case 1: state = "STATE_CONNECTING"; break; case 2: state = "STATE_CONNECTED"; break; case 10: state = "STATE_OFF"; break; case 11: state = "STATE_TURNING_ON"; break; case 12: state = "STATE_ON"; break; case 13: state = "STATE_TURNING_OFF"; break; case 20: state = "SCAN_MODE_NONE"; break; case 21: state = "SCAN_MODE_CONNECTABLE"; break; case 23: state = "SCAN_MODE_CONNECTABLE_DISCOVERABLE"; break; default: state = "UNKNOWN_STATE"; break; } status = mydevicename + " : " + mydeviceaddress + " : " + state; //status = mydevicename + " : " + mydeviceaddress; } else { status = "Bluetooth is not Enabled."; } Toast.makeText(this, status, Toast.LENGTH_LONG).show(); } }
From source file:com.gsoc.ijosa.liquidgalaxycontroller.PW.NearbyBeaconsFragment.java
private void startScanningDisplay(long scanStartTime, boolean hasResults) { BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { //Bluetooth not available Toast.makeText(getActivity(), getResources().getString(R.string.bluetoothNotAvailable), Toast.LENGTH_LONG);/*from w w w . j ava 2 s . com*/ } else if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BLUETOOTH); } else { // Start the scanning animation only if we don't haven't already been scanning // for long enough Log.d(TAG, "startScanningDisplay " + scanStartTime + " " + hasResults); long elapsedMillis = new Date().getTime() - scanStartTime; if (arrowDownLayout != null) { arrowDownLayout.setVisibility(View.VISIBLE); } if (elapsedMillis < FIRST_SCAN_TIME_MILLIS || (elapsedMillis < SECOND_SCAN_TIME_MILLIS && !hasResults)) { mScanningAnimationTextView.setAlpha(1f); mScanningAnimationDrawable.start(); if (getListView() != null) { getListView().setVisibility(View.INVISIBLE); } } else { showListView(); } // Schedule the timeouts // We delay at least 50 milliseconds to give the discovery service a chance to // give us cached results. mSecondScanComplete = false; long firstDelay = Math.max(FIRST_SCAN_TIME_MILLIS - elapsedMillis, 50); long secondDelay = Math.max(SECOND_SCAN_TIME_MILLIS - elapsedMillis, 50); long thirdDelay = Math.max(THIRD_SCAN_TIME_MILLIS - elapsedMillis, 50); mHandler.postDelayed(mFirstScanTimeout, firstDelay); mHandler.postDelayed(mSecondScanTimeout, secondDelay); mHandler.postDelayed(mThirdScanTimeout, thirdDelay); } }
From source file:com.android.launcher3.Utilities.java
public static boolean setBluetooth(boolean enable) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); boolean isEnabled = bluetoothAdapter.isEnabled(); if (enable && !isEnabled) { isBluetoothOn = true;//from w ww . j av a 2s. com return bluetoothAdapter.enable(); } else if (!enable && isEnabled) { isBluetoothOn = false; return bluetoothAdapter.disable(); } // No need to change bluetooth state return true; }
From source file:org.mobisocial.corral.ContentCorral.java
private void startBluetoothService() { if (mBluetoothAcceptThread != null) return;/*from ww w.ja v a 2 s . c o m*/ BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null || !adapter.isEnabled()) { return; } mBluetoothAcceptThread = new BluetoothAcceptThread(adapter, getLocalBluetoothServiceUuid(mContext)); mBluetoothAcceptThread.start(); }
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 w w .j a v a 2 s. 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(); }
From source file:com.nbplus.iotapp.service.IoTService.java
/** * ?? ? , enable ? ? ?? ./*w w w. j ava 2 s . c o m*/ */ public IoTResultCodes checkBluetoothEnabled() { // Use this check to determine whether BLE is supported on the device. Then you can // selectively disable BLE-related features. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { return IoTResultCodes.BLE_NOT_SUPPORTED; } // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to // BluetoothAdapter through BluetoothManager. final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); final BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); // Checks if Bluetooth is supported on the device. if (bluetoothAdapter == null) { return IoTResultCodes.BLUETOOTH_NOT_SUPPORTED; } // Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled, // fire an intent to display a dialog asking the user to grant permission to enable it. if (!bluetoothAdapter.isEnabled()) { return IoTResultCodes.BLUETOOTH_NOT_ENABLED; } mLastConnectionStatus = true; return IoTResultCodes.SUCCESS; }
From source file:ua.mkh.weather.MainActivity.java
public boolean low_mode_check() { boolean state = true; boolean state_brightness = true; boolean state_wifi = true; boolean state_bt = true; int status = Settings.System.getInt(getContentResolver(), "screen_brightness_mode", 0); if (status == 1) { state_brightness = false;/* w w w . jav a 2 s .com*/ } //0 // ContentResolver cResolver = getContentResolver(); int brightness = 0; try { //Get the current system brightness brightness = System.getInt(cResolver, System.SCREEN_BRIGHTNESS); } catch (SettingNotFoundException e) { //Throw an error case it couldn't be retrieved Log.e("Error", "Cannot access system brightness"); e.printStackTrace(); } if (brightness > 25) { state_brightness = false; } //WIFI ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled()) { if (mWifi.isConnected()) { } else { state_wifi = false; } } //Bluetooth BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter.isEnabled()) { state_bt = false; } if (state_brightness == false || state_wifi == false || state_bt == false) { state = false; } return state; }