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:is.hello.buruberi.bluetooth.stacks.android.NativeBluetoothStack.java
@Override @RequiresPermission(allOf = { Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, }) public Observable<Void> turnOn() { if (adapter == null) { return Observable.error(new ChangePowerStateException()); }/*from ww w.j a v a2s . c o m*/ final ReplaySubject<Void> turnOnMirror = ReplaySubject.createWithSize(1); final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, BluetoothAdapter.ERROR); final int newState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); if (oldState == BluetoothAdapter.STATE_OFF && newState == BluetoothAdapter.STATE_TURNING_ON) { logger.info(LOG_TAG, "Bluetooth turning on"); } else if (oldState == BluetoothAdapter.STATE_TURNING_ON && newState == BluetoothAdapter.STATE_ON) { logger.info(LOG_TAG, "Bluetooth turned on"); applicationContext.unregisterReceiver(this); turnOnMirror.onNext(null); turnOnMirror.onCompleted(); } else { logger.info(LOG_TAG, "Bluetooth failed to turn on"); applicationContext.unregisterReceiver(this); turnOnMirror.onError(new ChangePowerStateException()); } } }; applicationContext.registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); if (!adapter.enable()) { applicationContext.unregisterReceiver(receiver); return Observable.error(new ChangePowerStateException()); } return turnOnMirror; }
From source file:com.nbplus.iotapp.service.IoTService.java
public void handleMessage(Message msg) { if (msg == null) { return;//w ww . ja va 2s . c o m } Log.d(TAG, "handle message msg.what = " + msg.what); switch (msg.what) { // when using iot gateway case IoTServiceCommand.IOT_GATEWAY_CONNECTED: { Log.d(TAG, "IoTServiceCommand.IOT_GATEWAY_CONNECTED received..."); mIoTGatewayWorkerMessengerRef = new WeakReference<>(msg.replyTo); // TODO : test handler if (mIoTGatewayWorkerMessengerRef != null) { try { Messenger workerMessenger = mIoTGatewayWorkerMessengerRef.get(); if (workerMessenger != null) { Message testMsg = new Message(); msg.what = IoTServiceCommand.IOT_GATEWAY_DISCONNECTED; Log.d(TAG, "test IoTServiceCommand.IOT_GATEWAY_DISCONNECTED"); workerMessenger.send(testMsg); } } catch (Exception e) { e.printStackTrace(); } } break; } case IoTServiceCommand.SCANNING_START: { Bundle extras = msg.getData(); if (extras == null) { Log.w(TAG, "Scanning bundle data is not found !!!"); return; } boolean isPeriodic = extras.getBoolean(IoTServiceCommand.KEY_DATA); Log.d(TAG, "IoTServiceCommand.SCANNING_START called. periodic = " + isPeriodic); if (mUseIoTGateway) { } else { if (mBluetoothLeService != null && mServiceStatus == IoTServiceStatus.RUNNING) { mIsBleScanPeriodic = isPeriodic; mBluetoothLeService.scanLeDevicePeriodically(true, isPeriodic); } } break; } case IoTServiceCommand.SCANNING_STOP: { Bundle extras = msg.getData(); if (extras == null) { Log.w(TAG, "Scanning bundle data is not found !!!"); return; } //boolean isPeriodic = extras.getBoolean(IoTServiceCommand.KEY_DATA); Log.d(TAG, "IoTServiceCommand.SCANNING_STOP called."); if (mUseIoTGateway) { } else { if (mBluetoothLeService != null && mServiceStatus == IoTServiceStatus.RUNNING) { mIsBleScanPeriodic = false; mBluetoothLeService.scanLeDevicePeriodically(false, false); } } break; } case HANDLER_MESSAGE_CONNECTIVITY_CHANGED: final boolean isConnected = NetworkUtils.isConnected(this); Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED received isConnected = " + isConnected); if (mLastConnectionStatus == isConnected) { Log.d(TAG, "mLastConnectionStatus == isConnected do not anything."); return; } mLastConnectionStatus = isConnected; if (mLastConnectionStatus) { Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED network is connected !!!"); // TODO : re-connect if (mServiceStatus == IoTServiceStatus.STOPPED) { } } else { Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED network is disconnected !!!"); } break; case HANDLER_MESSAGE_BT_STATE_CHANGED: Log.d(TAG, "HANDLER_MESSAGE_CONNECTIVITY_CHANGED received !!!"); final int state = msg.arg1; if ((mLastConnectionStatus && state == BluetoothAdapter.STATE_ON) || (!mLastConnectionStatus && state == BluetoothAdapter.STATE_OFF)) { return; } mLastConnectionStatus = (state == BluetoothAdapter.STATE_ON) ? true : false; if (mLastConnectionStatus) { Log.d(TAG, "HANDLER_MESSAGE_BT_STATE_CHANGED bluetooth is enabled !!!"); if (mServiceStatus != IoTServiceStatus.RUNNING) { final Intent gattServiceIntent = new Intent(this, BluetoothLeService.class); if (!bindService(gattServiceIntent, mBluetoothServiceConnection, BIND_AUTO_CREATE)) { Log.e(TAG, ">> bind BluetoothServiceConnection failed.... !!!"); } } } else { Log.d(TAG, "HANDLER_MESSAGE_BT_STATE_CHANGED bluetooth is disabled !!!"); mErrorCodes = IoTResultCodes.BLUETOOTH_NOT_ENABLED; unbindService(mBluetoothServiceConnection); mServiceStatus = IoTServiceStatus.STOPPED; mHandler.removeMessages(HANDLER_MESSAGE_CONNECTION_NOT_RESPOND); mConnectedDeviceList.clear(); mRequestHandleMap.clear(); sendServiceStatusNotification(); } break; case IoTServiceCommand.REGISTER_SERVICE: { Bundle b = msg.getData(); if (msg.replyTo == null || b == null) { Log.e(TAG, "Invalid register args..."); break; } String msgId = b.getString(IoTServiceCommand.KEY_MSGID, ""); if (!StringUtils.isEmptyString(msgId)) { Log.d(TAG, "msgId == " + msgId); String[] strArrays = msgId.split("_"); if (strArrays.length == 2) { mRegisteredAppMessenger = new WeakReference<>(msg.replyTo); sendResultToApplication(msg.replyTo, msgId, null, msg.what, IoTResultCodes.SUCCESS); // ?? ?? ? ? . sendServiceStatusNotification(); } else { Log.e(TAG, "Invalid register args..."); sendResultToApplication(msg.replyTo, msgId, null, msg.what, IoTResultCodes.INVALID_REQUEST_ARGUMENTS); break; } } else { Log.e(TAG, "Invalid register args..."); sendResultToApplication(msg.replyTo, "", null, msg.what, IoTResultCodes.INVALID_REQUEST_ARGUMENTS); break; } break; } case IoTServiceCommand.UNREGISTER_SERVICE: { Bundle b = msg.getData(); if (b == null) { Log.e(TAG, "Invalid register args..."); break; } String msgId = b.getString(IoTServiceCommand.KEY_MSGID, ""); if (!StringUtils.isEmptyString(msgId)) { String[] strArrays = msgId.split("_"); if (strArrays.length == 2) { Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get(); if (clientMessenger != null) { sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.SUCCESS); mRegisteredAppMessenger = null; } else { //?? } } else { Log.e(TAG, "Invalid register args..."); break; } } else { Log.e(TAG, "Invalid un-register args..."); } break; } case IoTServiceCommand.GET_DEVICE_LIST: { if (mUseIoTGateway) { // TODO } else { mBluetoothLeService.scanLeDevice(false); mBluetoothLeService.scanLeDevicePeriodically(true, mIsBleScanPeriodic); } break; } case IoTServiceCommand.DEVICE_DISCONNECT_ALL: { Bundle b = msg.getData(); String msgId = b.getString(IoTServiceCommand.KEY_MSGID, ""); b.setClassLoader(IoTHandleData.class.getClassLoader()); IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA); if (mConnectedDeviceList.size() > 0) { mIsDisconnectAllState = true; ioTHandleData.setMsgId(msgId); ioTHandleData.setRequestCommand(msg.what); String connectedDeviceId = mConnectedDeviceList.get(0); if (mUseIoTGateway) { // TODO } else { if (mBluetoothLeService != null) { mBluetoothLeService.disconnect(connectedDeviceId); } else { Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get(); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); } } } else { Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get(); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.SUCCESS); } break; } case IoTServiceCommand.DEVICE_CONNECT: { Bundle b = msg.getData(); b.setClassLoader(IoTHandleData.class.getClassLoader()); IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA); String msgId = b.getString(IoTServiceCommand.KEY_MSGID, ""); Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get(); if (ioTHandleData == null) { sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.FAILED); Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null"); return; } if (mRequestHandleMap.get(ioTHandleData.getDeviceId()) != null) { Log.d(TAG, "Already previous command deviceid = " + ioTHandleData.getDeviceId() + ", command = " + ioTHandleData.getRequestCommand()); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); return; } if (mUseIoTGateway) { } else { if (mBluetoothLeService == null) { sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); Log.w(TAG, "case IoTServiceCommand.DEVICE_CONNECT : mBluetoothLeService or ioTHandleData is null"); return; } if (ioTHandleData.getDeviceTypeId() != IoTDevice.DEVICE_TYPE_ID_BT) { sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); Log.w(TAG, "case IoTServiceCommand.DEVICE_DISCONNECT : is not bt device... mUseIoTGateway == false"); return; } if (ioTHandleData.isKeepAliveDevice()) { if (mKeepAliveConnectionDeviceList.contains(ioTHandleData.getDeviceId())) { Log.d(TAG, "Keep alive device is already connected.. id = " + ioTHandleData.getDeviceId()); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.SUCCESS); // send to IoT interface module Message connectedMsg = new Message(); connectedMsg.what = IoTServiceCommand.DEVICE_CONNECTED; Bundle extras = new Bundle(); extras.putString(IoTServiceCommand.KEY_DEVICE_UUID, ioTHandleData.getDeviceId()); connectedMsg.setData(extras); sendNotificationToApplication(connectedMsg); return; } } if (mBluetoothLeService.connect(ioTHandleData.getDeviceId())) { ioTHandleData.setMsgId(msgId); ioTHandleData.setRequestCommand(msg.what); mRequestHandleMap.put(ioTHandleData.getDeviceId(), ioTHandleData); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.SUCCESS); // ?... connect ? . Message notRespondMsg = new Message(); notRespondMsg.what = HANDLER_MESSAGE_CONNECTION_NOT_RESPOND; Bundle extras = new Bundle(); extras.putParcelable(IoTServiceCommand.KEY_DATA, ioTHandleData); notRespondMsg.setData(extras); mHandler.sendMessageDelayed(notRespondMsg, CONNECTION_NOT_RESPOND_WAIT_TIME); } else { Log.w(TAG, "mBluetoothLeService.connect() return false"); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); } } break; } case HANDLER_MESSAGE_CONNECTION_NOT_RESPOND: { Log.d(TAG, "HANDLER_MESSAGE_CONNECTION_NOT_RESPOND ..."); Bundle b = msg.getData(); b.setClassLoader(IoTHandleData.class.getClassLoader()); IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA); if (mBluetoothLeService != null) { mBluetoothLeService.disconnect(ioTHandleData.getDeviceId()); } mRequestHandleMap.remove(ioTHandleData.getDeviceId()); Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get(); sendResultToApplication(clientMessenger, ioTHandleData.getMsgId(), ioTHandleData.getDeviceId(), IoTServiceCommand.DEVICE_CONNECT, IoTResultCodes.DEVICE_CONNECTION_NOT_RESPOND); break; } case IoTServiceCommand.DEVICE_DISCONNECT: { Bundle b = msg.getData(); b.setClassLoader(IoTHandleData.class.getClassLoader()); IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA); String msgId = b.getString(IoTServiceCommand.KEY_MSGID, ""); Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get(); if (ioTHandleData == null) { sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.FAILED); Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null"); return; } if (mRequestHandleMap.get(ioTHandleData.getDeviceId()) != null) { Log.d(TAG, "Already previous command deviceid = " + ioTHandleData.getDeviceId() + ", command = " + ioTHandleData.getRequestCommand()); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); return; } if (mUseIoTGateway) { } else { if (mBluetoothLeService == null) { sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); Log.w(TAG, "case IoTServiceCommand.DEVICE_DISCONNECT : mBluetoothLeService or ioTHandleData is null"); return; } if (ioTHandleData.getDeviceTypeId() != IoTDevice.DEVICE_TYPE_ID_BT) { sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); Log.w(TAG, "case IoTServiceCommand.DEVICE_DISCONNECT : is not bt device... mUseIoTGateway == false"); return; } if (mConnectedDeviceList.contains(ioTHandleData.getDeviceId()) || mKeepAliveConnectionDeviceList.contains(ioTHandleData.getDeviceId())) { ioTHandleData.setMsgId(msgId); ioTHandleData.setRequestCommand(msg.what); mRequestHandleMap.put(ioTHandleData.getDeviceId(), ioTHandleData); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.SUCCESS); mBluetoothLeService.disconnect(ioTHandleData.getDeviceId()); } else { Log.w(TAG, "mConnectedDeviceList.contains(ioTHandleData.getDeviceId()) is false"); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); } } break; } case IoTServiceCommand.DEVICE_READ_DATA: case IoTServiceCommand.DEVICE_WRITE_DATA: case IoTServiceCommand.DEVICE_SET_NOTIFICATION: { Bundle b = msg.getData(); b.setClassLoader(IoTHandleData.class.getClassLoader()); IoTHandleData ioTHandleData = b.getParcelable(IoTServiceCommand.KEY_DATA); String msgId = b.getString(IoTServiceCommand.KEY_MSGID, ""); Messenger clientMessenger = (mRegisteredAppMessenger == null) ? null : mRegisteredAppMessenger.get(); if (ioTHandleData == null) { sendResultToApplication(clientMessenger, msgId, null, msg.what, IoTResultCodes.FAILED); Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null"); return; } if (mRequestHandleMap.get(ioTHandleData.getDeviceId()) != null) { Log.d(TAG, "Already previous command deviceid = " + ioTHandleData.getDeviceId() + ", command = " + ioTHandleData.getRequestCommand()); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); return; } if (mUseIoTGateway) { } else { if (mBluetoothLeService == null) { sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); Log.w(TAG, "case READ_WRITE_SETNOTI : ioTHandleData is null"); return; } if (ioTHandleData.getDeviceTypeId() != IoTDevice.DEVICE_TYPE_ID_BT) { sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); Log.w(TAG, "case READ_WRITE_SETNOTI : is not bt device... mUseIoTGateway == false"); return; } if (mConnectedDeviceList.contains(ioTHandleData.getDeviceId()) || mKeepAliveConnectionDeviceList.contains(ioTHandleData.getDeviceId())) { ioTHandleData.setMsgId(msgId); ioTHandleData.setRequestCommand(msg.what); boolean result = true; switch (msg.what) { case IoTServiceCommand.DEVICE_READ_DATA: result = mBluetoothLeService.readCharacteristic(ioTHandleData.getDeviceId(), ioTHandleData.getServiceUuid(), ioTHandleData.getCharacteristicUuid()); break; case IoTServiceCommand.DEVICE_WRITE_DATA: result = mBluetoothLeService.writeRemoteCharacteristic(ioTHandleData.getDeviceId(), ioTHandleData.getServiceUuid(), ioTHandleData.getCharacteristicUuid(), ioTHandleData.getValue()); break; case IoTServiceCommand.DEVICE_SET_NOTIFICATION: result = mBluetoothLeService.setCharacteristicNotification(ioTHandleData.getDeviceId(), ioTHandleData.getServiceUuid(), ioTHandleData.getCharacteristicUuid(), true); break; } if (result) { mRequestHandleMap.put(ioTHandleData.getDeviceId(), ioTHandleData); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.SUCCESS); } else { sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); } } else { Log.w(TAG, "mConnectedDeviceList.contains(ioTHandleData.getDeviceId()) is false"); sendResultToApplication(clientMessenger, msgId, ioTHandleData.getDeviceId(), msg.what, IoTResultCodes.FAILED); } } break; } } }
From source file:org.bart452.runningshoesensor.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); requestPermission();//from w w w . ja v a2 s.co m context = getApplicationContext(); mHeaderImageView = (ImageView) findViewById(R.id.appBarIv); Picasso.with(context).load(R.drawable.sunset_road_landscape).into(mHeaderImageView); // Toolbar mToolbar = (Toolbar) findViewById(R.id.toolBar); setSupportActionBar(mToolbar); mCollapsingTb = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbar); mCollapsingTb.setTitle("Shoe sensor"); mCollapsingTb.setExpandedTitleGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP); // Bluetooth final BluetoothManager mBleMan = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBleAdapter = mBleMan.getAdapter(); mBleScanner = mBleAdapter.getBluetoothLeScanner(); mCharList = new ArrayList<>(); mBleSem = new Semaphore(1); mBleThread = new BleThread(mBleSem); mBleThread.start(); mBleReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) { if (mBleAdapter.getState() == BluetoothAdapter.STATE_ON) { Log.d(LOG_TAG, "BT ON"); mScanFab.setEnabled(true); if (mSnackBar != null) { if (mSnackBar.isShown()) mSnackBar.dismiss(); } } else { mScanFab.setEnabled(false); bleEnable(); } } } }; // Text mDevNameTv = (TextView) findViewById(R.id.devNameTv); mDevNameTv.setText(getString(R.string.device_name) + " No device found"); mRssiTv = (TextView) findViewById(R.id.rssiTv); mAddrTv = (TextView) findViewById(R.id.devAddrTv); // Buttons and switches mScanFab = (FloatingActionButton) findViewById(R.id.scanFab); mScanFab.setOnClickListener(this); mConnSwitch = (Switch) findViewById(R.id.connSwitch); mConnSwitch.setOnClickListener(this); //Graph mDataGraph = (GraphView) findViewById(R.id.dataGraph); mDataXSeries = new LineGraphSeries<>(); mDataYSeries = new LineGraphSeries<>(); mDataYSeries.setBackgroundColor(Color.RED); mDataGraph.addSeries(mDataXSeries); mDataGraph.addSeries(mDataYSeries); mDataGraph.getViewport().setXAxisBoundsManual(true); mDataGraph.getViewport().setMinX(0); mDataGraph.getViewport().setMaxX(20); // Animation mRotateAnim = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); mRotateAnim.setDuration(SCAN_PERIOD); mRotateAnim.setInterpolator(new LinearInterpolator()); bleEnable(); }
From source file:is.hello.buruberi.bluetooth.stacks.android.NativeBluetoothStack.java
@Override @RequiresPermission(allOf = { Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, }) public Observable<Void> turnOff() { if (adapter == null) { return Observable.error(new ChangePowerStateException()); }// www . j ava2 s . c o m final ReplaySubject<Void> turnOnMirror = ReplaySubject.createWithSize(1); final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, BluetoothAdapter.ERROR); final int newState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); if (oldState == BluetoothAdapter.STATE_ON && newState == BluetoothAdapter.STATE_TURNING_OFF) { logger.info(LOG_TAG, "Bluetooth turning off"); } else if (oldState == BluetoothAdapter.STATE_TURNING_OFF && newState == BluetoothAdapter.STATE_OFF) { logger.info(LOG_TAG, "Bluetooth turned off"); applicationContext.unregisterReceiver(this); turnOnMirror.onNext(null); turnOnMirror.onCompleted(); } else { logger.info(LOG_TAG, "Bluetooth failed to turn off"); applicationContext.unregisterReceiver(this); turnOnMirror.onError(new ChangePowerStateException()); } } }; applicationContext.registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); if (!adapter.disable()) { applicationContext.unregisterReceiver(receiver); return Observable.error(new ChangePowerStateException()); } return turnOnMirror; }
From source file:com.commontime.plugin.LocationManager.java
private void initBluetoothListener() { //check access if (!hasBlueToothPermission()) { debugWarn("Cannot listen to Bluetooth service when BLUETOOTH permission is not added"); return;/*from w w w . jav a2 s . co m*/ } //check device support try { iBeaconManager.checkAvailability(); } catch (Exception e) { //if device does not support iBeacons an error is thrown debugWarn("Cannot listen to Bluetooth service: " + e.getMessage()); return; } if (broadcastReceiver != null) { debugWarn("Already listening to Bluetooth service, not adding again"); return; } broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); // Only listen for Bluetooth server changes if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); final int oldState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, BluetoothAdapter.ERROR); debugLog("Bluetooth Service state changed from " + getStateDescription(oldState) + " to " + getStateDescription(state)); switch (state) { case BluetoothAdapter.ERROR: beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusNotDetermined"); break; case BluetoothAdapter.STATE_OFF: case BluetoothAdapter.STATE_TURNING_OFF: if (oldState == BluetoothAdapter.STATE_ON) beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusDenied"); break; case BluetoothAdapter.STATE_ON: beaconServiceNotifier.didChangeAuthorizationStatus("AuthorizationStatusAuthorized"); break; case BluetoothAdapter.STATE_TURNING_ON: break; } } } private String getStateDescription(int state) { switch (state) { case BluetoothAdapter.ERROR: return "ERROR"; case BluetoothAdapter.STATE_OFF: return "STATE_OFF"; case BluetoothAdapter.STATE_TURNING_OFF: return "STATE_TURNING_OFF"; case BluetoothAdapter.STATE_ON: return "STATE_ON"; case BluetoothAdapter.STATE_TURNING_ON: return "STATE_TURNING_ON"; } return "ERROR" + state; } }; // Register for broadcasts on BluetoothAdapter state change IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); cordova.getActivity().registerReceiver(broadcastReceiver, filter); }
From source file:ac.robinson.bettertogether.hotspot.HotspotManagerService.java
private void initialiseHotspots(@Nullable ConnectionOptions connectionOptions) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { mHotspotMode = true;/*from w w w .j ava2s . c om*/ if (CREATE_WIFI_HOTSPOT_SUPPORTED) { configureAndStartWifiHotspot(connectionOptions); } switch (mBluetoothAdapter.getState()) { case BluetoothAdapter.STATE_ON: configureAndStartBluetoothHotspot(connectionOptions); break; case BluetoothAdapter.STATE_TURNING_ON: break; // finish configuration in receiver case BluetoothAdapter.STATE_TURNING_OFF: case BluetoothAdapter.STATE_OFF: default: mBluetoothAdapter.enable(); // finish configuration in receiver } }
From source file:io.v.android.impl.google.discovery.plugins.ble.Driver.java
public synchronized String debugString() { if (mBluetoothAdapter == null) { return "Not available"; }/*from w ww .j av a 2 s. c o m*/ StringBuilder b = new StringBuilder().append("BluetoothAdapter: "); switch (mBluetoothAdapter.getState()) { case BluetoothAdapter.STATE_ON: b.append("ON"); break; case BluetoothAdapter.STATE_TURNING_ON: b.append("Turning on"); break; case BluetoothAdapter.STATE_OFF: b.append("OFF"); break; case BluetoothAdapter.STATE_TURNING_OFF: b.append("Turning off"); break; default: b.append("Unknown state"); break; } b.append("\n"); b.append("ENABLED: ").append(mEnabled).append("\n"); if (mServices.size() > 0) { b.append("ADVERTISING ").append(mServices.size()).append(" services\n"); } if (mLeScanCallback != null) { b.append("SCANNING\n"); } b.append("OnServiceReadCallbacks: ").append(mOnServiceReadCallbacks).append("\n"); return b.toString(); }
From source file:git.egatuts.nxtremotecontroller.activity.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { final MainActivity self = this; super.onCreate(savedInstanceState); super.setActiveTheme(super.getPreferenceTheme()); super.setContentView(R.layout.main_layout); toolbar = (Toolbar) super.findViewById(R.id.toolbar); this.setSupportToolbar(); this.drawerFragment = (NavigationDrawerFragment) fragmentManager.findFragmentById(R.id.drawer_fragment); this.drawerFragment.setup(R.id.drawer_fragment, (DrawerLayout) super.findViewById(R.id.drawer_element), this.toolbar); this.appKillerReceiver = new AppKillerReceiver(this, new AppKillerListener() { @Override// w w w.j av a 2 s .co m public void onAppNeedsRestart(Context context, Intent intent) { self.selfDestroyed = true; self.finish(); } }); this.progressDialogOnDismiss = new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { self.getShortProgressDialog().setOnDismissListener(null); new Handler().postDelayed(new Runnable() { @Override public void run() { self.replaceFragmentWith(self.selectedFragment, self.activeFragment); } }, 200); } }; this.bluetoothEnableReceiver = new BluetoothEnableReceiver(this, new BluetoothEnableListener() { @Override public void onStateChange(Context context, Intent intent) { int state = (int) self.bluetoothEnableReceiver.getIntentData(intent); final BaseIndeterminateProgressDialog progress = self.getShortProgressDialog(); Integer text = null; int hasToChange = 0; boolean hasToShow = false; /* * We define if we have to change the fragment or we have to show a progress dialog. */ switch (state) { case BluetoothAdapter.STATE_OFF: hasToChange = 2; break; case BluetoothAdapter.STATE_ON: hasToChange = 1; break; case BluetoothAdapter.STATE_TURNING_OFF: hasToShow = true; text = R.string.bluetooth_disabling; break; case BluetoothAdapter.STATE_TURNING_ON: hasToShow = true; text = R.string.bluetooth_enabling; break; } /* * Here we have to show a progress dialog indicating that the bluetooth state is changing. */ if (hasToShow && text != null) { self.showingTime = System.currentTimeMillis(); progress.show(); progress.setText(text); } else if (hasToChange != 0) { if (hasToChange == 1) self.selectedFragment = self.lastFragment; if (hasToChange == 2) self.selectedFragment = new BluetoothFragment(); if (!hasToShow && progress.isShowing()) { progress.setOnDismissListener(self.progressDialogOnDismiss); if (System.currentTimeMillis() - self.showingTime < 500) { new Handler().postDelayed(new Runnable() { @Override public void run() { progress.dismiss(); } }, 750); } else { progress.dismiss(); } } } } }); this.rippleViewListener = new RippleView.AnimationFinishListener() { @Override public void onFinish() { self.startControlDevice(self.controlIntent); } }; }
From source file:ac.robinson.bettertogether.hotspot.HotspotManagerService.java
private void connectBluetoothHotspot(@NonNull ConnectionOptions options) { Log.d(TAG, "Attempting connection via Bluetooth"); switch (mBluetoothAdapter.getState()) { case BluetoothAdapter.STATE_ON: Log.d(TAG, "Starting Bluetooth discovery"); mBluetoothAdapter.cancelDiscovery(); mBluetoothAdapter.startDiscovery(); setBluetoothErrorTimeout();/*from www.j a v a 2 s . co m*/ break; case BluetoothAdapter.STATE_TURNING_ON: Log.d(TAG, "Waiting for Bluetooth to be enabled"); break; // start discovery in receiver case BluetoothAdapter.STATE_OFF: case BluetoothAdapter.STATE_TURNING_OFF: default: Log.d(TAG, "Enabling Bluetooth / waiting for receiver to enable"); mBluetoothAdapter.enable(); // start discovery in receiver } }
From source file:com.evothings.BLE.java
private void reset(final CordovaArgs args, final CallbackContext cc) throws JSONException { mResetCallbackContext = null;//w ww . j a v a 2 s .com BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter(); if (mScanCallbackContext != null) { a.stopLeScan(this); mScanCallbackContext = null; } int state = a.getState(); //STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF. if (state == BluetoothAdapter.STATE_TURNING_ON) { // reset in progress; wait for STATE_ON. mResetCallbackContext = cc; return; } if (state == BluetoothAdapter.STATE_TURNING_OFF) { // reset in progress; wait for STATE_OFF. mResetCallbackContext = cc; return; } if (state == BluetoothAdapter.STATE_OFF) { boolean res = a.enable(); if (res) { mResetCallbackContext = cc; } else { cc.error("enable"); } return; } if (state == BluetoothAdapter.STATE_ON) { boolean res = a.disable(); if (res) { mResetCallbackContext = cc; } else { cc.error("disable"); } return; } cc.error("Unknown state: " + state); }