Java Code Examples for android.bluetooth.BluetoothProfile

The following are top voted examples for showing how to use android.bluetooth.BluetoothProfile. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lrs_android   File: AgoraActivity.java   Source Code and License 8 votes vote down vote up
private void optional() {
        HeadsetPlugManager.getInstance().registerHeadsetPlugListener(this);
        mHeadsetListener = new HeadsetBroadcastReceiver();
        registerReceiver(mHeadsetListener, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
        mBluetoothHeadsetBroadcastListener = new BluetoothHeadsetBroadcastReceiver();
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter != null && BluetoothProfile.STATE_CONNECTED == mBtAdapter.getProfileConnectionState(BluetoothProfile.HEADSET)) {
            // on some devices, BT is not supported
            boolean bt = mBtAdapter.getProfileProxy(getBaseContext(), mBluetoothHeadsetListener, BluetoothProfile.HEADSET);
            int connection = mBtAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
        }
        IntentFilter i = new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        i.addAction(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED);
        i.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
        registerReceiver(mBluetoothHeadsetBroadcastListener, i);
//避免对window添加ui修改参数
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
    }
 
Example 2
Project: Make-A-Pede-Android-App   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
	String intentAction;
	if (newState == BluetoothProfile.STATE_CONNECTED) {
		intentAction = ACTION_CONNECTED;
		connectionState = STATE_CONNECTED;
		broadcastUpdate(intentAction);
		Log.i(TAG, "Connected to GATT server.");
		Log.i(TAG, "Attempting to start service discovery:" + bluetoothGatt.discoverServices());

	} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
		intentAction = ACTION_DISCONNECTED;
		connectionState = STATE_DISCONNECTED;
		Log.i(TAG, "Disconnected from GATT server.");
		broadcastUpdate(intentAction);
	}
}
 
Example 3
Project: Linphone4Android   File: BluetoothManager.java   Source Code and License 6 votes vote down vote up
private void startBluetooth() {
	if (isBluetoothConnected) {
		Log.e("[Bluetooth] Already started, skipping...");
		return;
	}
	
	mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	
	if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
		if (mProfileListener != null) {
			Log.w("[Bluetooth] Headset profile was already opened, let's close it");
			mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
		}
		
		mProfileListener = new BluetoothProfile.ServiceListener() {
			public void onServiceConnected(int profile, BluetoothProfile proxy) {
			    if (profile == BluetoothProfile.HEADSET) {
			        Log.d("[Bluetooth] Headset connected");
			        mBluetoothHeadset = (BluetoothHeadset) proxy;
			        isBluetoothConnected = true;
			    }
			}
			public void onServiceDisconnected(int profile) {
			    if (profile == BluetoothProfile.HEADSET) {
			        mBluetoothHeadset = null;
			        isBluetoothConnected = false;
			        Log.d("[Bluetooth] Headset disconnected");
			        LinphoneManager.getInstance().routeAudioToReceiver();
			    }
			}
		};
		boolean success = mBluetoothAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.HEADSET);
		if (!success) {
			Log.e("[Bluetooth] getProfileProxy failed !");
		}
	} else {
		Log.w("[Bluetooth] Interface disabled on device");
	}
}
 
Example 4
Project: Linphone4Android   File: BluetoothManager.java   Source Code and License 6 votes vote down vote up
public void stopBluetooth() {
	Log.w("[Bluetooth] Stopping...");
	isBluetoothConnected = false;
	
	disableBluetoothSCO();
	
	if (mBluetoothAdapter != null && mProfileListener != null && mBluetoothHeadset != null) {
		mBluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
		mProfileListener = null;
	}
	mBluetoothDevice = null;
	
	Log.w("[Bluetooth] Stopped!");
	
	if (LinphoneManager.isInstanciated()) {
		LinphoneManager.getInstance().routeAudioToReceiver();
	}
}
 
Example 5
Project: TrainAppTFG   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    Log.d("BLUETOOTH", "Estado de conexión bluetooth: " + (newState == BluetoothProfile.STATE_CONNECTED ? "Connected" : "Disconnected"));

    if(newState == BluetoothProfile.STATE_CONNECTED){
        //setState(State.CONNECTED);
        mBluetoothGatt.discoverServices();
    }
    else{
        //setState(State.IDDLE);
        //TODO Realizar todas las tareas necesarias cuando se desconecte la pulsera
        Log.d("BLUETOOTH", "Se ha desconectado el dispostivo bluetooth");
    }
}
 
Example 6
Project: arduator   File: ArduinoCommBle.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    if (newState == BluetoothProfile.STATE_CONNECTED) {
        connected = true;
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        connected = false;
        btGatt.close();
        btGatt = null;
        charSerial = null;
        messenger.obtainMessage(MessageConstants.STATUS, StatusCode.Disconnected).sendToTarget();
    } else {
        messenger.obtainMessage(MessageConstants.ERROR, ErrorCode.Connect).sendToTarget();
        taskConnectTimeout.cancel();
    }
}
 
Example 7
Project: nc-android-webrtcpeer   File: BluetoothManager.java   Source Code and License 6 votes vote down vote up
/**
 * Stops and closes all components related to Bluetooth audio.
 */
public void stop() {
    ThreadUtils.checkIsOnMainThread();
    Log.d(TAG, "stop: BT state=" + bluetoothState);
    if (bluetoothAdapter == null) {
        return;
    }
    // Stop BT SCO connection with remote device if needed.
    stopScoAudio();
    // Close down remaining BT resources.
    if (bluetoothState == State.UNINITIALIZED) {
        return;
    }
    unregisterReceiver(bluetoothHeadsetReceiver);
    cancelTimer();
    if (bluetoothHeadset != null) {
        bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, bluetoothHeadset);
        bluetoothHeadset = null;
    }
    bluetoothAdapter = null;
    bluetoothDevice = null;
    bluetoothState = State.UNINITIALIZED;
    Log.d(TAG, "stop done: BT state=" + bluetoothState);
}
 
Example 8
Project: lrs_android   File: AgoraActivity.java   Source Code and License 6 votes vote down vote up
private void optionalDestroy() {
    if (mBtAdapter != null) {
        mBtAdapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothProfile);
        mBluetoothProfile = null;
        mBtAdapter = null;
    }
    if (mBluetoothHeadsetBroadcastListener != null) {
        unregisterReceiver(mBluetoothHeadsetBroadcastListener);
        mBluetoothHeadsetBroadcastListener = null;
    }
    if (mHeadsetListener != null) {
        unregisterReceiver(mHeadsetListener);
        mHeadsetListener = null;
    }
    HeadsetPlugManager.getInstance().unregisterHeadsetPlugListener(this);
}
 
Example 9
Project: BLE-PEPS   File: BluetoothLeClass.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        if(mOnConnectListener!=null)
            mOnConnectListener.onConnect(gatt);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        if(mOnDisconnectListener!=null)
            mOnDisconnectListener.onDisconnect(gatt);
        Log.i(TAG, "Disconnected from GATT server.");
    }

    if(mOnConnectStatusChangedListener!=null)
        mOnConnectStatusChangedListener.onConnectStatusChanged(gatt,status,newState);
        Log.i(TAG, "Changed");

}
 
Example 10
Project: BLE-PEPS   File: BluetoothLeClass.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        if(mOnConnectListener!=null)
            mOnConnectListener.onConnect(gatt);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        if(mOnDisconnectListener!=null)
            mOnDisconnectListener.onDisconnect(gatt);
        Log.i(TAG, "Disconnected from GATT server.");
    }

    if(mOnConnectStatusChangedListener!=null)
        mOnConnectStatusChangedListener.onConnectStatusChanged(gatt,status,newState);
        Log.i(TAG, "Changed");

}
 
Example 11
Project: sdc-1-quickstart-android   File: MainActivity.java   Source Code and License 6 votes vote down vote up
/**
 * Callback indicating when GATT client has connected/disconnected to/from a remote
 * GATT server.
 *
 * @param gatt     GATT client
 * @param status   Status of the connect or disconnect operation.
 *                 {@link BluetoothGatt#GATT_SUCCESS} if the operation succeeds.
 * @param newState Returns the new connection state. Can be one of
 *                 {@link android.bluetooth.BluetoothProfile#STATE_DISCONNECTED} or
 *                 {@link android.bluetooth.BluetoothProfile#STATE_CONNECTED}
 */
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    // boolean indicating whether or not the next step is successful, default is false
    boolean success = false;

    // Start Service discovery if we're now connected
    if (status == BluetoothGatt.GATT_SUCCESS) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            success = gatt.discoverServices();
        } // else: not connected, continue
    } // else: not successful

    onStep(gatt, success);
}
 
Example 12
Project: buildAPKsSamples   File: BluetoothHDPService.java   Source Code and License 6 votes vote down vote up
/**
 * Make sure Bluetooth and health profile are available on the Android device.  Stop service
 * if they are not available.
 */
@Override
public void onCreate() {
    super.onCreate();
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        // Bluetooth adapter isn't available.  The client of the service is supposed to
        // verify that it is available and activate before invoking this service.
        stopSelf();
        return;
    }
    if (!mBluetoothAdapter.getProfileProxy(this, mBluetoothServiceListener,
            BluetoothProfile.HEALTH)) {
        Toast.makeText(this, R.string.bluetooth_health_profile_not_available,
                Toast.LENGTH_LONG);
        stopSelf();
        return;
    }
}
 
Example 13
Project: igrow-android   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        mConnectionState = STATE_CONNECTED;
        broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        mConnectionState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
Example 14
Project: AppRTC-Android   File: AppRTCBluetoothManager.java   Source Code and License 6 votes vote down vote up
/** Stops and closes all components related to Bluetooth audio. */
public void stop() {
  ThreadUtils.checkIsOnMainThread();
  Log.d(TAG, "stop: BT state=" + bluetoothState);
  if (bluetoothAdapter == null) {
    return;
  }
  // Stop BT SCO connection with remote device if needed.
  stopScoAudio();
  // Close down remaining BT resources.
  if (bluetoothState == State.UNINITIALIZED) {
    return;
  }
  unregisterReceiver(bluetoothHeadsetReceiver);
  cancelTimer();
  if (bluetoothHeadset != null) {
    bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, bluetoothHeadset);
    bluetoothHeadset = null;
  }
  bluetoothAdapter = null;
  bluetoothDevice = null;
  bluetoothState = State.UNINITIALIZED;
  Log.d(TAG, "stop done: BT state=" + bluetoothState);
}
 
Example 15
Project: AndroidRTC   File: AppRTCBluetoothManager.java   Source Code and License 6 votes vote down vote up
/**
 * Stops and closes all components related to Bluetooth audio.
 */
public void stop() {
    ThreadUtils.checkIsOnMainThread();
    unregisterReceiver(bluetoothHeadsetReceiver);
    Log.d(TAG, "stop: BT state=" + bluetoothState);
    if (bluetoothAdapter != null) {
        // Stop BT SCO connection with remote device if needed.
        stopScoAudio();
        // Close down remaining BT resources.
        if (bluetoothState != State.UNINITIALIZED) {
            cancelTimer();
            if (bluetoothHeadset != null) {
                bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, bluetoothHeadset);
                bluetoothHeadset = null;
            }
            bluetoothAdapter = null;
            bluetoothDevice = null;
            bluetoothState = State.UNINITIALIZED;
        }
    }
    Log.d(TAG, "stop done: BT state=" + bluetoothState);
}
 
Example 16
Project: bluewatcher   File: BluetoothClientService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
	String intentAction;
	if (newState == BluetoothProfile.STATE_CONNECTED) {
		Log.i(TAG, "Connected to GATT server.");
		if( gatt.getDevice().getBondState() != BluetoothDevice.BOND_BONDED ) {
			broadcastUpdate(ACTION_NOT_PAIRED);
			gatt.disconnect();
			return;
		}
		Log.i(TAG, "Attempting to start service discovery" );
		mBluetoothGatt.discoverServices();
		connected = true;
		broadcastUpdate(ACTION_GATT_CLIENT_CONNECTED);
	}
	else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
		intentAction = ACTION_GATT_CLIENT_DISCONNECTED;
		Log.i(TAG, "Disconnected from GATT server.");
		broadcastUpdate(intentAction);
		connected = false;
	}
}
 
Example 17
Project: PairingExample   File: MainActivity.java   Source Code and License 6 votes vote down vote up
public void run()
{
    /* In example we don't start discovery, but any case if it is discovering, stop it */
    if(failedConnect != true) {
        /* Create profile listeners for A2DP and Headset profiles */
        mBluetoothAdapter.getProfileProxy(getApplicationContext(), mProfileListener, BluetoothProfile.A2DP);
        mBluetoothAdapter.getProfileProxy(getApplicationContext(), mProfileListener, BluetoothProfile.HEADSET);


        /* Paired with Classic BT, update UI */
        classic_paired = true;
        tryBLE = true;

        TextUpdateHandler.post(updateRunnable);

        read_ble_handler.postDelayed(runnable, 5000);
    }
}
 
Example 18
Project: Android-BLE-to-Arduino   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        mConnectionState = STATE_CONNECTED;
        broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        mConnectionState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
Example 19
Project: Snach-Android   File: BLEManager.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                    int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        resetConnectionTimeoutChecker();

        isSnachConnected = true;

        BLEManager.this.gatt = gatt; // TODO check if right device is discovered (instead of another BLE device with a different GATT..)
        Log.i("BLE", "Connected to GATT server.");
        Log.i("BLE", "Attempting to start service discovery:" + startServiceDiscovery(gatt));

        sendBroadcastConnectionChanged(isSnachConnected);

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        isSnachConnected = false;
        mConnectionListener.ConnectionLost();
        Log.i("BLE", "Disconnected from GATT server.");
    }
}
 
Example 20
Project: UDOOBluLib-android   File: UdooBluService.java   Source Code and License 6 votes vote down vote up
/**
     * Connects to the GATT server hosted on the Bluetooth LE device.
     *
     * @param address The device address of the destination device.
     * @return Return true if the connection is initiated successfully. The connection result is reported asynchronously through the
     * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} callback.
     */
    public void connect(final String address, IBleDeviceListener iBleDeviceListener) {
        UdooBluException udooBluException = checkBluetooth(getApplicationContext());
        if (udooBluException != null) {
            if (iBleDeviceListener != null)
                iBleDeviceListener.onError(udooBluException);
        } else {
            final BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
            int connectionState = mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT);

            BluetoothGatt bluetoothGatt = checkAndGetGattItem(address);
            if (connectionState == BluetoothProfile.STATE_DISCONNECTED) {
//                 Previously connected device. Try to reconnect.
                if (bluetoothGatt != null) {
                    Log.d(TAG, "Re-use GATT connection");
                    if (bluetoothGatt.connect()) {
                    } else {
                        Log.w(TAG, "GATT re-connect failed.");
                    }
                } else if (device == null) {
                    Log.w(TAG, "Device not found.  Unable to connect.");
                } else {
                    Log.d(TAG, "Create a new GATT connection.");
                    bluetoothGatt = device.connectGatt(this, false, bluetoothGattCallbackBuilder());
                    mBluetoothGatts.put(address, bluetoothGatt);
                }
            } else {
                Log.w(TAG, "Attempt to connect in state: " + connectionState);
                bond(address);
                bluetoothGatt = device.connectGatt(this, false, bluetoothGattCallbackBuilder());
                mBluetoothGatts.put(address, bluetoothGatt);
            }
        }
    }
 
Example 21
Project: UDOOBluLib-android   File: UdooBluService.java   Source Code and License 6 votes vote down vote up
/**
 * Disconnects an existing connection or cancel a pending connection. The disconnection result is reported asynchronously through the
 * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} callback.
 */
public void disconnect(String address) {
    if (mBtAdapter == null) {
        Log.w(TAG, "disconnect: BluetoothAdapter not initialized");
        return;
    }
    final BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
    int connectionState = mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
    BluetoothGatt bluetoothGatt = checkAndGetGattItem(address);
    if (bluetoothGatt != null) {
        Log.i(TAG, "disconnect");
        if (connectionState != BluetoothProfile.STATE_DISCONNECTED) {
            bluetoothGatt.disconnect();
        } else {
            Log.w(TAG, "Attempt to disconnect in state: " + connectionState);
        }
    }
}
 
Example 22
Project: MagicLight-Controller   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    Log.e(TAG, "onConnectionStateChanged");

    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) { // STATE : connected
        intentAction = ACTION_GATT_CONNECTED;
        mConnectionState = STATE_CONNECTED;

        broadcastUpdate(intentAction); // broadcast Gatt connection state : connected

        Log.e(TAG, "Connected to GATT server.");
        Log.e(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { // STATE : disconnected
        intentAction = ACTION_GATT_DISCONNECTED;
        mConnectionState = STATE_DISCONNECTED;

        broadcastUpdate(intentAction); // broadcast Gatt connection state : disconnected

        Log.e(TAG, "Disconnected from GATT server.");
    }
}
 
Example 23
Project: mi-band-2   File: BLEMiBand2Helper.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
    switch(newState)
    {
        case BluetoothProfile.STATE_CONNECTED:
            Log.d(TAG, "Gatt state: connected");
            gatt.discoverServices();
            isConnectedToGatt = true;
            raiseonConnect();
            break;
        default:
            Log.d(TAG, "Gatt state: not connected");
            isConnectedToGatt = false;
            raiseonDisconnect();
            break;
    }
}
 
Example 24
Project: AndroidthingsStudy   File: BluetoothHDPService.java   Source Code and License 6 votes vote down vote up
/**
 * Make sure Bluetooth and health profile are available on the Android device.  Stop service
 * if they are not available.
 */
@Override
public void onCreate() {
    super.onCreate();
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        // Bluetooth adapter isn't available.  The client of the service is supposed to
        // verify that it is available and activate before invoking this service.
        stopSelf();
        return;
    }
    if (!mBluetoothAdapter.getProfileProxy(this, mBluetoothServiceListener,
            BluetoothProfile.HEALTH)) {
        Toast.makeText(this, R.string.bluetooth_health_profile_not_available,
                Toast.LENGTH_LONG);
        stopSelf();
        return;
    }
}
 
Example 25
Project: sample-bluetooth-audio   File: A2dpSinkActivity.java   Source Code and License 6 votes vote down vote up
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(A2dpSinkHelper.ACTION_CONNECTION_STATE_CHANGED)) {
        int oldState = A2dpSinkHelper.getPreviousProfileState(intent);
        int newState = A2dpSinkHelper.getCurrentProfileState(intent);
        BluetoothDevice device = A2dpSinkHelper.getDevice(intent);
        Log.d(TAG, "Bluetooth A2DP sink changing connection state from " + oldState +
                " to " + newState + " device " + device);
        if (device != null) {
            String deviceName = Objects.toString(device.getName(), "a device");
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                speak("Connected to " + deviceName);
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                speak("Disconnected from " + deviceName);
            }
        }
    }
}
 
Example 26
Project: Android-nRF-Beacon-for-Eddystone   File: UpdateService.java   Source Code and License 6 votes vote down vote up
/**
 * Disconnects from the device and closes the Bluetooth GATT object afterwards.
 */
public void disconnectAndClose() {
    // This sometimes happen when called from UpdateService.ACTION_GATT_ERROR event receiver in UpdateFragment.
    if (mBluetoothGatt == null)
        return;

    setState(STATE_DISCONNECTING);
    mBluetoothGatt.disconnect();

    // Sometimes the connection gets error 129 or 133. Calling disconnect() method does not really disconnect... sometimes the connection is already broken.
    // Here we have a security check that notifies UI about disconnection even if onConnectionStateChange(...) has not been called.
    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (mConnectionState == STATE_DISCONNECTING)
                mGattCallback.onConnectionStateChange(mBluetoothGatt, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_DISCONNECTED);
        }
    }, 1500);
}
 
Example 27
Project: Android-nRF-Beacon-for-Eddystone   File: UpdateFragment.java   Source Code and License 6 votes vote down vote up
@Override
public void onDeviceSelected(final BluetoothDevice device, final String name) {
    if (mConnectionProgressDialog != null) {
        mConnectionProgressDialog.setTitle(getString(R.string.prog_dialog_connect_title));
        mConnectionProgressDialog.setMessage(getString(R.string.prog_dialog_connect_message));
        mConnectionProgressDialog.show();
    }

    final Activity activity = getActivity();
    final Intent service = new Intent(activity, UpdateService.class);
    service.putExtra(UpdateService.EXTRA_DATA, device);
    updateUiForBeacons(BluetoothProfile.STATE_CONNECTED, UpdateService.LOCKED);
    activity.startService(service);
    mBounnd = true;
    activity.bindService(service, mServiceConnection, 0);
}
 
Example 28
Project: ssj   File: BLESensorListener.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        mConnectionState = STATE_CONNECTED;

        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        mConnectionState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");

    }
}
 
Example 29
Project: BLEServerSimple   File: ANCSGattCallback.java   Source Code and License 6 votes vote down vote up
@Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                        int newState) {
        Log.i(TAG, "onConnectionStateChange,newState " + newState + "status:" + status);
        try{
            mBleState = BleStatus.values()[newState];
        }catch(Exception e){
            e.printStackTrace();
        }
        notifyListeners();

        if (newState == BluetoothProfile.STATE_CONNECTED
                && status == BluetoothGatt.GATT_SUCCESS) {
//            mBluetoothGatt = gatt;
            mBleState = BleStatus.BUILD_DISCOVER_SERVICE;
            notifyListeners();
            gatt.discoverServices();
        } else {
            Log.i(TAG, "onConnectionStateChange,failure");
            if(mOnGattDisconnectListener != null){
                mOnGattDisconnectListener.onGattDisconnectListener(gatt);
            }

        }
    }
 
Example 30
Project: Grandroid2   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    Config.logi("BluetoothGatt connection State Changed: [" + status + "]" + newState);
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        mConnectionState = STATE_CONNECTED;
        broadcastUpdate(intentAction, gatt.getDevice().getAddress());
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to startScan findService discovery:" +
                gatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        mConnectionState = STATE_DISCONNECTED;
        gatt.close();//make 133 not fire.
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction, gatt.getDevice().getAddress());
    }
}
 
Example 31
Project: android-xmpp-iot-demo   File: XiotBluetoothLeManager.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
	switch (newState) {
		case BluetoothProfile.STATE_CONNECTED:
			LOGGER.info("GATT connected: " + gatt);
			gatt.discoverServices();
			break;
		case BluetoothProfile.STATE_DISCONNECTED:
			LOGGER.info("GATT disconnected: " + gatt);
			MainActivity.withMainActivity((ma) -> {
				Toast.makeText(ma, "Connection to Polar H7 lost", Toast.LENGTH_SHORT).show();
			});
			mPolarH7BluetoothGatt = null;
			resetHeartRateInformation();
			break;
		default:
			throw new AssertionError();
	}
}
 
Example 32
Project: unreademailsformiband   File: MiBandService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(final BluetoothGatt gatt, int status, int newState)
{
    super.onConnectionStateChange(gatt, status, newState);
    Log.d(TAG, "onConnectionStateChange status="+status+" newState="+newState);
    if (newState == BluetoothProfile.STATE_CONNECTED)
    {
        handler.post(new Runnable() {
            @Override
            public void run() {
                gatt.discoverServices();
            }
        });
    }
    else if (newState == BluetoothProfile.STATE_DISCONNECTED)
    {
        //Util.sendBroadcast(getApplicationContext(), Constants.INTENT_MISCALE_DISCONNECTED);

        closeGatt();
    }
}
 
Example 33
Project: AsteroidOSSync   File: P_BleDevice_Listeners.java   Source Code and License 6 votes vote down vote up
private void onNativeConnectFail(final BluetoothGatt gatt, final int gattStatus)
{
	//--- DRK > NOTE: Making an assumption that the underlying stack agrees that the connection state is STATE_DISCONNECTED.
	//---				This is backed up by basic testing, but even if the underlying stack uses a different value, it can probably
	//---				be assumed that it will eventually go to STATE_DISCONNECTED, so SweetBlue library logic is sounder "living under the lie" for a bit regardless.
	m_device.m_nativeWrapper.updateNativeConnectionState(gatt, BluetoothProfile.STATE_DISCONNECTED);

	final P_Task_Connect connectTask = m_queue.getCurrent(P_Task_Connect.class, m_device);

	if (connectTask != null)
	{
		connectTask.onNativeFail(gattStatus);
	}
	else
	{
		m_device.onNativeConnectFail((PE_TaskState) null, gattStatus, AutoConnectUsage.UNKNOWN);
	}
}
 
Example 34
Project: AsteroidOSSync   File: P_BleServer_Listeners.java   Source Code and License 6 votes vote down vote up
private void onNativeConnectFail(final BluetoothDevice nativeDevice, final int gattStatus)
{
	//--- DRK > NOTE: Making an assumption that the underlying stack agrees that the connection state is STATE_DISCONNECTED.
	//---				This is backed up by basic testing, but even if the underlying stack uses a different value, it can probably
	//---				be assumed that it will eventually go to STATE_DISCONNECTED, so SweetBlue library logic is sounder "living under the lie" for a bit regardless.
	m_server.m_nativeWrapper.updateNativeConnectionState(nativeDevice.getAddress(), BluetoothProfile.STATE_DISCONNECTED);

	if( hasCurrentConnectTaskFor(nativeDevice) )
	{
		final P_Task_ConnectServer connectTask = m_queue.getCurrent(P_Task_ConnectServer.class, m_server);

		connectTask.onNativeFail(gattStatus);
	}
	else
	{
		m_server.onNativeConnectFail(nativeDevice, BleServer.ConnectionFailListener.Status.NATIVE_CONNECTION_FAILED_EVENTUALLY, gattStatus);
	}
}
 
Example 35
Project: ai_ble_framework   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
  String intentAction;
  if (newState == BluetoothProfile.STATE_CONNECTED) {
    intentAction = ACTION_GATT_CONNECTED;
    mConnectionState = STATE_CONNECTED;
    broadcastUpdate(intentAction);
    Log.i(TAG, "Connected to GATT server.");
    // Attempts to discover services after successful connection.
    Log.i(TAG, "Attempting to start service discovery:" +
        mBluetoothGatt.discoverServices());

  } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
    intentAction = ACTION_GATT_DISCONNECTED;
    mConnectionState = STATE_DISCONNECTED;
    Log.i(TAG, "Disconnected from GATT server.");
    broadcastUpdate(intentAction);
  }
}
 
Example 36
Project: science-journal   File: MyBleService.java   Source Code and License 6 votes vote down vote up
public void disconnectDevice(String address) {
    BluetoothGatt bluetoothGatt = addressToGattClient.get(address);
    if (btAdapter == null || address == null || bluetoothGatt == null) {
        // Broadcast the disconnect so BleFlow doesn't hang waiting for it; something else
        // already disconnected us in this case.
        sendGattBroadcast(address, BleEvents.GATT_DISCONNECT, null);
        return;
    }
    BluetoothDevice device = btAdapter.getRemoteDevice(address);
    int bleState = bluetoothManager.getConnectionState(device,
            BluetoothProfile.GATT);
    if (bleState != BluetoothProfile.STATE_DISCONNECTED
            && bleState != BluetoothProfile.STATE_DISCONNECTING) {
        bluetoothGatt.disconnect();
    } else {
        bluetoothGatt.close();
        addressToGattClient.remove(address);
        sendGattBroadcast(address, BleEvents.GATT_DISCONNECT, null);
    }
}
 
Example 37
Project: TappyBLE   File: TappyBleDelegate.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if(gatt.getDevice().getAddress().equals(bleDeviceAddress)) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            changeState(TappyBleState.CONNECTED);
            bluetoothGattRef.compareAndSet(null,gatt);
            BluetoothGatt bluetoothGatt = bluetoothGattRef.get();
            Log.i(TAG, "Connected to GATT server.");
            // Attempts to discover services after successful connection.
            if (bluetoothGatt != null) {
                Log.i(TAG, "Attempting to start service discovery:" +
                        bluetoothGatt.discoverServices());
            } else {
                Log.wtf(TAG, "Somehow connected with no gatt");
                changeState(TappyBleState.ERROR);
            }

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            changeState(TappyBleState.DISCONNECTED);
            Log.i(TAG, "Disconnected from GATT server.");
        }
    }
}
 
Example 38
Project: BLE_Tutorials   File: Service_BTLE_GATT.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;

        mConnectionState = STATE_CONNECTED;

        broadcastUpdate(intentAction);

        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices());
    }
    else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;

        mConnectionState = STATE_DISCONNECTED;

        Log.i(TAG, "Disconnected from GATT server.");

        broadcastUpdate(intentAction);
    }
}
 
Example 39
Project: mibandGeocaching   File: BLECommunicationManager.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
    mGatt = gatt;

    switch(newState)
    {
        case BluetoothProfile.STATE_CONNECTED:
            Log.d(TAG, "Gatt state: connected");
            gatt.discoverServices();
            mDeviceConnected = true;
            if(mConnectionLatch != null)
            {
                mConnectionLatch.countDown();
            }
            break;
        default:
            Log.d(TAG, "Gatt state: not connected");
            mDeviceConnected = false;
            break;
    }
}
 
Example 40
Project: sample-android-ble   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        mConnectionState = STATE_CONNECTED;
        broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        mConnectionState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
Example 41
Project: xDrip   File: ShareTest.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        mBluetoothGatt = gatt;
        mConnectionState = STATE_CONNECTED;
        ActiveBluetoothDevice.connected();
        Log.i(TAG, "Connected to GATT server.");
        Log.i(TAG, "Connection state: Bonded - " + device.getBondState());

        if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
            currentGattTask = GATT_SETUP;
            mBluetoothGatt.discoverServices();

        } else {
            device.setPin("000000".getBytes());
            device.createBond();
        }
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        mConnectionState = STATE_DISCONNECTED;
        ActiveBluetoothDevice.disconnected();
        Log.w(TAG, "Disconnected from GATT server.");
    }
}
 
Example 42
Project: BLE-Mesh   File: BLEGattClients.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothDevice device,int newState) {

    switch (newState){
        case BluetoothProfile.STATE_CONNECTED:
            /**
             * If Local device is not scanner ( advertiser instead),
             * then remote device is scanner,
             * so we can connect its gatt server
             */
            if (!centralScannedDevices.contains(device.getAddress())) {
                peripheralReceivedDevices.add(device.getAddress());
                device.connectGatt(context,false,getGattCallback());
            }
            break;
        case BluetoothProfile.STATE_DISCONNECTED:
            peripheralReceivedDevices.remove(device.getAddress());
            break;
    }
}
 
Example 43
Project: IoT-Firstep   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
Example 44
Project: IoT-Firstep   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
Example 45
Project: IoT-Firstep   File: BluetoothLeService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    String intentAction;
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        intentAction = ACTION_GATT_CONNECTED;
        broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        intentAction = ACTION_GATT_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        broadcastUpdate(intentAction);
    }
}
 
Example 46
Project: ESeal   File: ACSUtilityService.java   Source Code and License 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    Message msg = null;
    //msg = mEventHandler.obtainMessage(EVENT_DATA_AVAILABLE);
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        //intentAction = ACTION_GATT_CONNECTED;
        mConnectionState = STATE_CONNECTED;
        msg = mCurrentEventHandler.obtainMessage(EVENT_GATT_CONNECTED);
        //broadcastUpdate(intentAction);
        Log.i(TAG, "Connected to GATT server.");
        // Attempts to discover services after successful connection.
        Log.i(TAG, "Attempting to start service discovery:" +
                mBluetoothGatt.discoverServices());

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        //intentAction = ACTION_GATT_DISCONNECTED;
        mConnectionState = STATE_DISCONNECTED;
        Log.i(TAG, "Disconnected from GATT server.");
        close();
        msg = mCurrentEventHandler.obtainMessage(EVENT_GATT_DISCONNECTED);
        mBluetoothDeviceAddress = null;
        //broadcastUpdate(intentAction);
    }
    msg.sendToTarget();
}
 
Example 47
Project: thunderboard-android   File: BleManager.java   Source Code and License 6 votes vote down vote up
private void closeGatt() {

        if (gatt != null) {

            Timber.d("gatt device: %s, connected devices: %d", gatt.getDevice().getAddress(), bluetoothManager.getConnectedDevices(BluetoothProfile.GATT).size());
            ThunderBoardDevice device = getDeviceFromCache(gatt.getDevice().getAddress());
            if (device != null) {
                device.clear();
            }

            if (BluetoothGatt.STATE_DISCONNECTED == bluetoothManager.getConnectionState(gatt.getDevice(), BluetoothProfile.GATT)) {
                Timber.d("close");
                gatt.close();
            } else {
                Timber.d("disconnect");
                gatt.disconnect();
            }

            gatt = null;
        }
        for (int i = 0; i < devices.size(); i++) {
            Timber.d("device: %s", devices.get(i).getAddress());
        }
    }
 
Example 48
Project: mDL-ILP   File: GattClient.java   Source Code and License 5 votes vote down vote up
private synchronized void waitUntilConnected() throws InterruptedException {
    if (VDBG) { Log.d(TAG, "waitUntilConnected: [CMD]"); }
    while (connectionState != BluetoothProfile.STATE_CONNECTED) {
        wait();
    }
    if (VDBG) { Log.d(TAG, "waitUntilConnected: [DONE]"); }
}
 
Example 49
Project: android-ponewheel   File: BluetoothUtilImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    Log.d(TAG, "BluetoothGattCallback.nConnectionStateChange: status=" + status + " newState=" + newState);
    updateLog("Bluetooth connection state change: status="+ status + " newState=" + newState);
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        gatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        if (gatt.getDevice().getAddress().equals(mOWDevice.deviceMacAddress.get())) {
            onOWStateChangedToDisconnected(gatt);
        }
        updateLog("--> Closed " + gatt.getDevice().getAddress());
        Log.d(TAG, "Disconnect:" + gatt.getDevice().getAddress());
    }
}
 
Example 50
Project: AndroidSDK2.0   File: BTLEAdt.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    NLog.d("onConnectionStatusChange status " + status + ", newStatue " + newState);
    super.onConnectionStateChange(gatt, status, newState);
    watchDog.cancel();
    if ( watchDogAlreadyCalled )
    {
        return;
    }
    switch (newState)
    {
        case BluetoothProfile.STATE_CONNECTED:

            mBluetoothGatt = gatt;
            onBinded();
            NLog.d("Connected");
            mtuIndex = 0;
            mtu = mtuLIst[mtuIndex];
            boolean ret = gatt.requestMtu(mtu);
            NLog.d("mtu test result : " + ret);
            break;
        case BluetoothProfile.STATE_DISCONNECTED:
            NLog.d("Disconnected");
            if ( mConnectionThread == null )
            {
                NLog.d("Connect failed");
                responseMsg( new PenMsg( PenMsgType.PEN_CONNECTION_FAILURE) );
                onDisconnected();
            }
            else
            {
                mConnectionThread.stopRunning();
            }
            close();
            break;
    }
}
 
Example 51
Project: PeSanKita-android   File: BluetoothStateManager.java   Source Code and License 5 votes vote down vote up
public void onDestroy() {
    if (bluetoothHeadset != null && bluetoothAdapter != null && Build.VERSION.SDK_INT >= 11) {
        this.bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, bluetoothHeadset);
    }

    if (Build.VERSION.SDK_INT >= 11 && bluetoothConnectionReceiver != null) {
        context.unregisterReceiver(bluetoothConnectionReceiver);
    }

    if (bluetoothScoReceiver != null) {
        context.unregisterReceiver(bluetoothScoReceiver);
    }

    this.bluetoothHeadset = null;
}
 
Example 52
Project: AssistantBySDK   File: AssistantService.java   Source Code and License 5 votes vote down vote up
@Override
public void onServiceDisconnected(int profile) {
    Log.e("blueHeadsetListener", "onServiceDisconnected:" + profile);
    if (profile == BluetoothProfile.A2DP) {
        voiceMediator.setBluetoothA2dp(null);
    } else if (profile == BluetoothProfile.HEADSET) {
        voiceMediator.setBluetoothHeadset(null);
    }
}
 
Example 53
Project: AssistantBySDK   File: AssistantService.java   Source Code and License 5 votes vote down vote up
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
    Log.e("blueHeadsetListener", "onServiceConnected:" + profile);
    if (profile == BluetoothProfile.A2DP) {
        voiceMediator.setBluetoothA2dp((BluetoothA2dp) proxy);
    } else if (profile == BluetoothProfile.HEADSET) {
        voiceMediator.setBluetoothHeadset((BluetoothHeadset) proxy);
    }
}
 
Example 54
Project: CSipSimple   File: BluetoothUtils14.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isBTHeadsetConnected() {
    if(bluetoothAdapter != null) {
        return (bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET) == BluetoothAdapter.STATE_CONNECTED);
    }
    return false;
}
 
Example 55
Project: nc-android-webrtcpeer   File: BluetoothManager.java   Source Code and License 5 votes vote down vote up
@Override
// Called to notify the client when the proxy object has been connected to the service.
// Once we have the profile proxy object, we can use it to monitor the state of the
// connection and perform other operations that are relevant to the headset profile.
public void onServiceConnected(int profile, BluetoothProfile proxy) {
    if (profile != BluetoothProfile.HEADSET || bluetoothState == State.UNINITIALIZED) {
        return;
    }
    Log.d(TAG, "BluetoothServiceListener.onServiceConnected: BT state=" + bluetoothState);
    // Android only supports one connected Bluetooth Headset at a time.
    bluetoothHeadset = (BluetoothHeadset) proxy;
    updateAudioDeviceState();
    Log.d(TAG, "onServiceConnected done: BT state=" + bluetoothState);
}
 
Example 56
Project: nc-android-webrtcpeer   File: BluetoothManager.java   Source Code and License 5 votes vote down vote up
@Override
/** Notifies the client when the proxy object has been disconnected from the service. */
public void onServiceDisconnected(int profile) {
    if (profile != BluetoothProfile.HEADSET || bluetoothState == State.UNINITIALIZED) {
        return;
    }
    Log.d(TAG, "BluetoothServiceListener.onServiceDisconnected: BT state=" + bluetoothState);
    stopScoAudio();
    bluetoothHeadset = null;
    bluetoothDevice = null;
    bluetoothState = State.HEADSET_UNAVAILABLE;
    updateAudioDeviceState();
    Log.d(TAG, "onServiceDisconnected done: BT state=" + bluetoothState);
}
 
Example 57
Project: lrs_android   File: AgoraActivity.java   Source Code and License 5 votes vote down vote up
/**
 * 监听到蓝牙设备连接
 * @param profile
 * @param headset
 */
@Override
public void onServiceConnected(int profile, BluetoothProfile headset) {
    if (profile == BluetoothProfile.HEADSET) {
        LogUtil.e("onServiceConnected " + profile + " " + headset);
        mBluetoothProfile = headset;

        List<BluetoothDevice> devices = headset.getConnectedDevices();
        headsetPlugged(devices != null && devices.size() > 0);
    }
}
 
Example 58
Project: mobly-bundled-snippets   File: BluetoothA2dpSnippet.java   Source Code and License 5 votes vote down vote up
public BluetoothA2dpSnippet() {
    mContext = InstrumentationRegistry.getContext();
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    bluetoothAdapter.getProfileProxy(
            mContext, new A2dpServiceListener(), BluetoothProfile.A2DP);
    Utils.waitUntil(() -> sIsA2dpProfileReady, 60);
}
 
Example 59
Project: NaiveDemos   File: BleOperationService.java   Source Code and License 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    LogUtils.d(TAG, "onConnctionStateChange:" + Thread.currentThread().toString());
    if (BluetoothProfile.STATE_CONNECTED == newState) {
        //连接成功
        LogUtils.i(TAG, "onConnectionStateChange():连接成功,得到gatt,status = " + status);
        mState = State.STATE_CONNECTED;

        //发现服务
        boolean b = gatt.discoverServices();
        LogUtils.d(TAG, "试图查询 gatt 上的 services :" + b);

        //发送消息给 Activity
        sendMsgToClient(MsgClient.MSG_GATT_CONNECTED, null);


    } else if (BluetoothProfile.STATE_DISCONNECTED == newState) {
        //返回连接断开的消息
        sendMsgToClient(MsgClient.MSG_CONNECTED_DISMISS, null);

        //取消周期行读取 rssi 的操作
        cancelAllTasks();

        //清除当前 gatt
        refreshDeviceCache();
        gatt.disconnect();//不使用自带的重连功能
        closeGatt();

        //定时重连操作
        mScheduledThreadPool.schedule(task1, Attributes.RE_CONNECTING_TIME, TimeUnit.MILLISECONDS);

        LogUtils.i(TAG, "onConnectionStateChange():连接断开,status = " + status);
        mState = State.STATE_DISCONNECT;

    } else {
        LogUtils.i(TAG, "其它状态: status = " + status + ", newState = " + newState);
    }
}
 
Example 60
Project: BluetoothCtrl   File: BluetoothLeService.java   Source Code and License 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        broadcastUpdate(ACTION_GATT_CONNECTED);
        ULog.i("Connected to GATT server.");
        mBluetoothGatt.discoverServices();
        ULog.i("Attempting to start service discovery:");
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        broadcastUpdate(ACTION_GATT_DISCONNECTED);
        ULog.w("Disconnected from GATT server.");
    }
}