Example usage for android.bluetooth BluetoothAdapter ERROR

List of usage examples for android.bluetooth BluetoothAdapter ERROR

Introduction

In this page you can find the example usage for android.bluetooth BluetoothAdapter ERROR.

Prototype

int ERROR

To view the source code for android.bluetooth BluetoothAdapter ERROR.

Click Source Link

Document

Sentinel error value for this class.

Usage

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  w w w . j  a va 2  s.  co 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:de.unifreiburg.es.iLitIt.LighterBluetoothService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (mBluetoothChangeReceiver == null) {
        mBluetoothChangeReceiver = new BroadcastReceiver() {
            @Override/* www  . jav  a  2s .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: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());
    }// ww w. ja v  a2 s.  c om

    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: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());
    }/* ww  w. ja  v a 2  s  .  co 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;// ww w .  j  a  va 2  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:com.android.dragonkeyboardfirmwareupdater.KeyboardFirmwareUpdateService.java

/**
 * Handles intents ACTION_CONNECTION_STATE_CHANGED, ACTION_STATE_CHANGED,
 * ACTION_BOND_STATE_CHANGED, ACTION_KEYBOARD_UPDATE_CONFIRMED.
 * <p/>/* www  .  j a va 2  s. co  m*/
 * [ACTION_STATE_CHANGED]
 * This action is used to keep track of ON/OFF state change on the system Bluetooth adapter.
 * The
 * purpose is to synchronize the local Bluetooth connectivity with system Bluetooth state.
 * <p/>
 * [ACTION_CONNECTION_STATE_CHANGED]
 * This action is used to keep track of the connection change on the target device. The purpose
 * is to synchronize the connection cycles of the local GATT connection and the system
 * Bluetooth
 * connection.
 * <p/>
 * [ACTION_BOND_STATE_CHANGED]
 * This action is used to keep track of the bond state change on the target device. The purpose
 * is to the connection cycles of the local GATT connection and the system Bluetooth
 * connection.
 * <p/>
 * [ACTION_KEYBOARD_UPDATE_CONFIRMED]
 * This action is used to receive the update confirmation from the user. The purpose is to
 * trigger DFU process.
 */
private void onHandleIntent(Context context, Intent intent) {
    final String action = intent.getAction();
    Log.d(TAG, "onHandleIntent: Received action: " + action);

    if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {

        if (!isBluetoothEnabled()) {
            Log.w(TAG, "onHandleIntent: Bluetooth connectivity not enabled");
            return;
        }

        // Match the connected device with the default keyboard name.
        Bundle extras = intent.getExtras();
        if (extras == null)
            return;
        final BluetoothDevice device = extras.getParcelable(BluetoothDevice.EXTRA_DEVICE);
        final int deviceConnectionState = extras.getInt(BluetoothAdapter.EXTRA_CONNECTION_STATE);

        Log.d(TAG, "onHandleIntent: " + device.getName() + " [" + device.getAddress() + "] change to state: "
                + deviceConnectionState);

        // Match the name of the target keyboard.
        if (!isTargetKeyboard(device))
            return;

        if (deviceConnectionState == BluetoothAdapter.STATE_CONNECTED) {
            // Prevent the second keyboard from using the service.
            if (isUpdateServiceInUse())
                return;

            obtainKeyboardInfo(device.getName(), device.getAddress());

            if (mDfuStatus != DFU_STATE_INFO_READY) {
                Log.w(TAG, "onHandleIntent: DFU preparation failed");
                changeDfuStatus(DFU_STATE_OBTAIN_INFO_ERROR);
                return;
            }

            showUpdateNotification();
        } else if (deviceConnectionState == BluetoothAdapter.STATE_DISCONNECTING) {
            handleGattDisconnection();
        }

    } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
        final int adapterState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
        if (adapterState == BluetoothAdapter.STATE_ON) {
            if (!isBluetoothEnabled())
                enableBluetoothConnectivity();
        } else if (adapterState == BluetoothAdapter.STATE_TURNING_OFF) {
            // Terminate update process and disable Bluetooth connectivity.
            disableBluetoothConnectivity();

            // Since BluetoothAdapter has been disabled, the callback of disconnection would not
            // be called. Therefore a separate clean-up of GATT connection is need.
            cleanUpGattConnection();
        }

    } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
        Bundle extras = intent.getExtras();
        if (extras == null)
            return;
        final BluetoothDevice device = extras.getParcelable(BluetoothDevice.EXTRA_DEVICE);
        final int deviceBondState = extras.getInt(BluetoothDevice.EXTRA_BOND_STATE);

        Log.d(TAG, "onHandleIntent: state change on device " + device.getName() + " [" + device.getAddress()
                + "], bond state: " + deviceBondState);

        if (!isTargetKeyboard(device))
            return;

        if (deviceBondState == BluetoothDevice.BOND_NONE) {
            handleGattDisconnection();
        }

    } else if (ACTION_KEYBOARD_UPDATE_CONFIRMED.equals(action)) {
        dismissUpdateNotification();

        if (mDfuStatus != DFU_STATE_INFO_READY || mDfuStatus == DFU_STATE_UPDATING) {
            Log.w(TAG, "onHandleIntent: DFP preparation not ready or DFU is in progress. ");
            changeDfuStatus(DFU_STATE_UPDATE_ABORTED);
            return;
        }

        String keyboardName = intent.getStringExtra(EXTRA_KEYBOARD_NAME);
        String keyboardAddress = intent.getStringExtra(EXTRA_KEYBOARD_ADDRESS);
        if (!mKeyboardName.equals(keyboardName) || !mKeyboardAddress.equals(keyboardAddress)) {
            Log.w(TAG, "onHandleIntent: No DFU service associated with " + keyboardName + " [" + keyboardAddress
                    + "]");
            return;
        }

        Log.d(TAG, "onHandleIntent: Start update process on " + keyboardName + " [" + keyboardAddress + "]");
        changeDfuStatus(DFU_STATE_SWITCHING_TO_DFU_MODE);

    } else if (ACTION_KEYBOARD_UPDATE_POSTPONED.equals(action)) {
        dismissUpdateNotification();
        // TODO(mcchou): Update the preference when the Settings keyboard entry is available.
    }
}