List of usage examples for android.bluetooth BluetoothAdapter STATE_ON
int STATE_ON
To view the source code for android.bluetooth BluetoothAdapter STATE_ON.
Click Source Link
From source file:com.jaguarlandrover.auto.remote.vehicleentry.RviService.java
protected void starting(Intent intent) { if (intent != null && intent.getExtras() != null) { int btState = intent.getExtras().getInt("bluetooth", BluetoothAdapter.STATE_OFF); if (btState == BluetoothAdapter.STATE_ON) { Log.w(TAG, "BT on, start ranging"); br.start();/*w w w.j ava 2 s . c o m*/ } else if (btState == BluetoothAdapter.STATE_OFF) { Log.w(TAG, "BT off, stop ranging"); br.stop(); } } }
From source file:is.hello.buruberi.bluetooth.stacks.android.NativeBluetoothStack.java
@RequiresPermission(Manifest.permission.BLUETOOTH) public NativeBluetoothStack(@NonNull Context applicationContext, @NonNull ErrorListener errorListener, @NonNull LoggerFacade logger) {//from www .ja v a 2 s . c o m this.applicationContext = applicationContext; this.errorListener = errorListener; this.logger = logger; this.bluetoothManager = (BluetoothManager) applicationContext.getSystemService(Context.BLUETOOTH_SERVICE); this.adapter = bluetoothManager.getAdapter(); if (adapter != null) { final BroadcastReceiver powerStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final int newState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); if (newState == BluetoothAdapter.STATE_ON) { enabled.onNext(true); } else if (newState == BluetoothAdapter.STATE_OFF || newState == BluetoothAdapter.ERROR) { enabled.onNext(false); } } }; applicationContext.registerReceiver(powerStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); enabled.onNext(adapter.isEnabled()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { final BroadcastReceiver pairingReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); final Intent broadcast = new Intent(ACTION_PAIRING_REQUEST); broadcast.putExtra(GattPeripheral.EXTRA_NAME, device.getName()); broadcast.putExtra(GattPeripheral.EXTRA_ADDRESS, device.getAddress()); LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast); } }; applicationContext.registerReceiver(pairingReceiver, new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST)); } } else { logger.warn(LOG_TAG, "Host device has no bluetooth hardware!"); enabled.onNext(false); } }
From source file:com.google.android.apps.forscience.ble.DeviceDiscoverer.java
public boolean canScan() { return mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON; }
From source file:org.deviceconnect.android.deviceplugin.sphero.setting.fragment.DeviceSelectionPageFragment.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); isThreadRunning = true;/*from w w w.j av a 2 s. c o m*/ new Thread(new Runnable() { @Override public void run() { BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { return; } int prevState = mBluetoothAdapter.getState(); while (isThreadRunning) { if (prevState != mBluetoothAdapter.getState()) { if ((mBluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) && (prevState == BluetoothAdapter.STATE_TURNING_ON || prevState == BluetoothAdapter.STATE_OFF)) { threadHandler.post(new Runnable() { @Override public void run() { stopDiscovery(); startDiscovery(); } }); } prevState = mBluetoothAdapter.getState(); } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); }
From source file:com.evothings.BLE.java
private void checkPowerState(BluetoothAdapter adapter, CallbackContext cc, Runnable onPowerOn) { if (adapter == null) { return;//from www .j ava 2s.c o m } if (adapter.getState() == BluetoothAdapter.STATE_ON) { // Bluetooth is ON onPowerOn.run(); } else { mOnPowerOn = onPowerOn; mPowerOnCallbackContext = cc; Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); cordova.startActivityForResult(this, enableBtIntent, 0); } }
From source file:com.piusvelte.taplock.client.core.TapLockService.java
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF); if (state == BluetoothAdapter.STATE_ON) { if (mStartedBT) { if (mUIInterface != null) { try { mUIInterface.setMessage("Bluetooth enabled"); } catch (RemoteException e) { Log.e(TAG, e.getMessage()); }// w ww . ja v a2s. c o m } if ((mQueueAddress != null) && (mQueueState != null)) requestWrite(mQueueAddress, mQueueState, mQueuePassphrase); else if (mRequestDiscovery && !mBtAdapter.isDiscovering()) mBtAdapter.startDiscovery(); else if (mUIInterface != null) { try { mUIInterface.setBluetoothEnabled(); } catch (RemoteException e) { Log.e(TAG, e.getMessage()); } } } } else if (state == BluetoothAdapter.STATE_TURNING_OFF) { if (mUIInterface != null) { try { mUIInterface.setMessage("Bluetooth disabled"); } catch (RemoteException e) { Log.e(TAG, e.getMessage()); } } stopThreads(); } } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() == BluetoothDevice.BOND_BONDED) { // connect if configured String address = device.getAddress(); for (JSONObject deviceJObj : mDevices) { try { if (deviceJObj.getString(KEY_ADDRESS).equals(address)) { // if queued mDeviceFound = (mQueueAddress != null) && mQueueAddress.equals(address) && (mQueueState != null); break; } } catch (JSONException e) { Log.e(TAG, e.getMessage()); } } } else if (mRequestDiscovery && (mUIInterface != null)) { String unpairedDevice = TapLock .createDevice(device.getName(), device.getAddress(), DEFAULT_PASSPHRASE).toString(); try { mUIInterface.setUnpairedDevice(unpairedDevice); } catch (RemoteException e) { Log.e(TAG, e.getMessage()); } } } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { if (mDeviceFound) { requestWrite(mQueueAddress, mQueueState, mQueuePassphrase); mDeviceFound = false; } else if (mRequestDiscovery) { mRequestDiscovery = false; if (mUIInterface != null) { try { mUIInterface.setDiscoveryFinished(); } catch (RemoteException e) { Log.e(TAG, e.toString()); } } } } else if (ACTION_TOGGLE.equals(action) && intent.hasExtra(EXTRA_DEVICE_ADDRESS)) { String address = intent.getStringExtra(EXTRA_DEVICE_ADDRESS); requestWrite(address, ACTION_TOGGLE, null); } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { // create widget if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); if (intent.hasExtra(EXTRA_DEVICE_NAME)) { // add a widget String deviceName = intent.getStringExtra(EXTRA_DEVICE_NAME); for (int i = 0, l = mDevices.size(); i < l; i++) { String name = null; try { name = mDevices.get(i).getString(KEY_NAME); } catch (JSONException e1) { e1.printStackTrace(); } if ((name != null) && name.equals(deviceName)) { JSONObject deviceJObj = mDevices.remove(i); JSONArray widgetsJArr; if (deviceJObj.has(KEY_WIDGETS)) { try { widgetsJArr = deviceJObj.getJSONArray(KEY_WIDGETS); } catch (JSONException e) { widgetsJArr = new JSONArray(); } } else widgetsJArr = new JSONArray(); widgetsJArr.put(appWidgetId); try { deviceJObj.put(KEY_WIDGETS, widgetsJArr); } catch (JSONException e) { e.printStackTrace(); } mDevices.add(i, deviceJObj); TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE), mDevices); break; } } } buildWidget(appWidgetId); } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) { int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); if (appWidgetIds != null) { for (int appWidgetId : appWidgetIds) buildWidget(appWidgetId); } } } else if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) { int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); Log.d(TAG, "delete appWidgetId: " + appWidgetId); for (int i = 0, l = mDevices.size(); i < l; i++) { JSONObject deviceJObj = mDevices.get(i); if (deviceJObj.has(KEY_WIDGETS)) { JSONArray widgetsJArr = null; try { widgetsJArr = deviceJObj.getJSONArray(KEY_WIDGETS); } catch (JSONException e) { e.printStackTrace(); } if (widgetsJArr != null) { boolean wasUpdated = false; JSONArray newWidgetsJArr = new JSONArray(); for (int widgetIdx = 0, wdigetsLen = widgetsJArr .length(); widgetIdx < wdigetsLen; widgetIdx++) { int widgetId; try { widgetId = widgetsJArr.getInt(widgetIdx); } catch (JSONException e) { widgetId = AppWidgetManager.INVALID_APPWIDGET_ID; e.printStackTrace(); } Log.d(TAG, "eval widgetId: " + widgetId); if ((widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) && (widgetId == appWidgetId)) { Log.d(TAG, "skip: " + widgetId); wasUpdated = true; } else { Log.d(TAG, "include: " + widgetId); newWidgetsJArr.put(widgetId); } } if (wasUpdated) { try { deviceJObj.put(KEY_WIDGETS, newWidgetsJArr); mDevices.remove(i); mDevices.add(i, deviceJObj); TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE), mDevices); Log.d(TAG, "stored: " + deviceJObj.toString()); } catch (JSONException e) { e.printStackTrace(); } } } } else { JSONArray widgetsJArr = new JSONArray(); try { deviceJObj.put(KEY_WIDGETS, widgetsJArr); mDevices.remove(i); mDevices.add(i, deviceJObj); TapLock.storeDevices(this, getSharedPreferences(KEY_PREFS, MODE_PRIVATE), mDevices); } catch (JSONException e) { e.printStackTrace(); } } } } } return START_STICKY; }
From source file:de.unifreiburg.es.iLitIt.LighterBluetoothService.java
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (mBluetoothChangeReceiver == null) { mBluetoothChangeReceiver = new BroadcastReceiver() { @Override/* ww w. ja v a 2 s. com*/ public void onReceive(Context context, Intent intent) { final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); switch (state) { case BluetoothAdapter.STATE_ON: onStartCommand(null, 0, 0); break; case BluetoothAdapter.STATE_OFF: break; default: break; } } }; IntentFilter mif = new IntentFilter(); mif.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(mBluetoothChangeReceiver, mif); } if (mSmartWatchAnnotationReceiver == null) { mSmartWatchAnnotationReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (mEventList == null) return; String via = intent.getStringExtra("ess.imu_logger.libs.data_save.extra.annotationVia"); mEventList.add(new CigaretteEvent(new Date(), via == null ? "intent" : via, null)); } }; // create watch ui intent listener IntentFilter filter = new IntentFilter("ess.imu_logger.libs.data_save.annotate"); registerReceiver(mSmartWatchAnnotationReceiver, filter); } // For API level 18 and above, get a reference to BluetoothAdapter through // BluetoothManager. //if (serviceIsInitialized) // return START_STICKY; mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); if (mBluetoothManager == null) { Log.e(TAG, "Unable to initialize BluetoothManager."); return START_NOT_STICKY; } mBluetoothAdapter = mBluetoothManager.getAdapter(); if (mBluetoothAdapter == null) { Log.e(TAG, "Unable to obtain a BluetoothAdapter."); return START_NOT_STICKY; } // for DEBUGGING only // PreferenceManager.getDefaultSharedPreferences(this).edit().clear().apply(); /** check if we are already bound to a device, if not start scanning for one */ mBluetoothDeviceAddress = PreferenceManager.getDefaultSharedPreferences(this).getString(KEY_DEVICEADDR, null); mLastBatteryVoltage = PreferenceManager.getDefaultSharedPreferences(this).getFloat(KEY_BATVOLTAGE, 0.0f); mBatteryEmpty = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(KEY_BATEMTPY, false); super.onStartCommand(intent, flags, startId); /** load the stored events */ if (mEventList == null) { mEventList = CigAnnotationWriter.readCigaretteList(this); mEventList.register(rCigAnnotationWriter); mEventList.register(rCigIntentBroadcaster); } /** set-up the location service, we need this to run here, since we need to *access the location whenever there is a chang to the cigarette model. */ mLocationClient = new LocationClient(this, mLocationHandler, mLocationHandler); mEventList.register(new DelayedObserver(1000, mLocationHandler)); /** start to scan for LE devices in the area */ mHandler = new Handler(Looper.getMainLooper()); mHandler.post(rStartLEScan); /** create a notification on a pending connection */ PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); mNotification = (new NotificationCompat.Builder(this)).setContentText("downloading cigarette events") .setContentTitle("iLitIt").setSmallIcon(R.drawable.ic_cigarette_black).setProgress(0, 0, true) .setAutoCancel(true).setContentIntent(i).build(); mLowBatteryWarning = (new NotificationCompat.Builder(this)).setContentTitle("iLitIt - battery low") .setContentText("replace battery as soons as possible").setSmallIcon(R.drawable.ic_launcher) .build(); return START_STICKY; }
From source file:co.aurasphere.bluepair.bluetooth.BluetoothController.java
/** * Called when the Bluetooth status changed. *//*from ww w . ja v a 2s . c o m*/ public void onBluetoothStatusChanged() { // Does anything only if a device discovery has been scheduled. if (bluetoothDiscoveryScheduled) { int bluetoothState = bluetooth.getState(); switch (bluetoothState) { case BluetoothAdapter.STATE_ON: // Bluetooth is ON. Log.d(TAG, "Bluetooth succesfully enabled, starting discovery"); startDiscovery(); // Resets the flag since this discovery has been performed. bluetoothDiscoveryScheduled = false; break; case BluetoothAdapter.STATE_OFF: // Bluetooth is OFF. Log.d(TAG, "Error while turning Bluetooth on."); Toast.makeText(context, "Error while turning Bluetooth on.", Toast.LENGTH_SHORT); // Resets the flag since this discovery has been performed. bluetoothDiscoveryScheduled = false; break; default: // Bluetooth is turning ON or OFF. Ignore. break; } } }
From source file:pl.mrwojtek.sensrec.app.HeartRateDialog.java
public void onBluetoothAdapterState(int state) { switch (state) { case BluetoothAdapter.STATE_OFF: scanLeDevice(false);/*from w w w .j a va 2 s .c o m*/ break; case BluetoothAdapter.STATE_TURNING_OFF: // Ignore for now break; case BluetoothAdapter.STATE_ON: scanLeDevice(true); break; case BluetoothAdapter.STATE_TURNING_ON: // Ignore for now break; } }
From source file:com.mozilla.SUTAgentAndroid.SUTAgentAndroid.java
/** Called when the activity is first created. */ @Override//w w w .j a va 2 s. co 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(); } }); }