Java Code Examples for android.bluetooth.BluetoothProfile#STATE_CONNECTED

The following examples show how to use android.bluetooth.BluetoothProfile#STATE_CONNECTED . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseBleService.java    From bleYan with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
	BleLog.i(TAG, "onConnectionStateChange: State = " + BleUtils.getBleConnectStatus(status)
			+ " newState = " + BleUtils.getBleConnectStatus(newState));

	if (newState == BluetoothProfile.STATE_CONNECTED) {
		updateState(BleConnectState.CONNECTED);
		//start discoverServices
		BleLog.i(TAG, "gatt.discoverServices()");
		gatt.discoverServices();
	} else if (newState == BluetoothProfile.STATE_CONNECTING) {
		updateState(BleConnectState.CONNECTING);
	} else if (newState == BluetoothProfile.STATE_DISCONNECTING) {
		updateState(BleConnectState.DISCONNECTING);
	} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
		//disconnect
		sIsWriting = false;
		sWriteQueue.clear();
		updateState(BleConnectState.DISCONNECTED);
          }
}
 
Example 2
Source File: BLEPeripheralDefault.java    From itag with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(@NonNull BluetoothGatt gatt, int status, int newState) {
    if (BuildConfig.DEBUG) {
        Log.d(LT, "onConnectionStateChange id=" + identifier() +
                " addr=" + gatt.getDevice().getAddress() +
                " status=" + status +
                " newState=" + newState);
    }
    if (status == GATT_SUCCESS) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            setGatt(gatt);
            setState(BLEPeripheralState.connected);
            observables.channelConnected.broadcast(new BLEPeripheralObservablesInterface.ConnectedEvent());
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            close();
            observables.channelDisconnected.broadcast(new BLEPeripheralObservablesInterface.DisconnectedEvent(status));
        }
    } else {
        close();
        if (getState() == BLEPeripheralState.connecting) {
            observables.channelConnectionFailed.broadcast(new BLEPeripheralObservablesInterface.ConnectionFailedEvent(status));
        } else {
            observables.channelDisconnected.broadcast(new BLEPeripheralObservablesInterface.DisconnectedEvent(status));
        }
    }
}
 
Example 3
Source File: BTConnectionManager.java    From redalert-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);

    //Log.e(TAG, "onConnectionStateChange (2): " + newState);

    BTConnectionManager.this.gatt = gatt;

    if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED)
    {
        gatt.discoverServices();
    }
    else if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_DISCONNECTED)
    {
        Log.e(TAG, "onConnectionStateChange disconnect: " + newState);
        disconnect();
    }
    else if (status != BluetoothGatt.GATT_SUCCESS)
    {
        gatt.disconnect();
    }
}
 
Example 4
Source File: ServicesActivity.java    From BLEService with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	String deviceAddress = intent.getStringExtra(DeviceService.EXTRA_DEVICE_ADDRESS);
	int state = intent.getIntExtra(DeviceService.EXTRA_STATE, 0);
	if (state == BluetoothProfile.STATE_CONNECTED) {
		try {
			mService.discoverServices(mDevice.getAddress());
		} catch (RemoteException rex) {
			rex.printStackTrace();
		}

	}
  		TextView tvState = (TextView) ServicesActivity.this.findViewById(R.id.peripheral_status);
  		tvState.setText(Integer.toString(state));  		

}
 
Example 5
Source File: BluetoothLeService.java    From IoT-Firstep with GNU General Public License v3.0 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 6
Source File: BluetoothPeripheral.java    From blessed-android with MIT License 6 votes vote down vote up
private void successfullyDisconnected(int previousState) {
    if (previousState == BluetoothProfile.STATE_CONNECTED || previousState == BluetoothProfile.STATE_DISCONNECTING) {
        Timber.i("disconnected '%s' on request", getName());
    } else if (previousState == BluetoothProfile.STATE_CONNECTING) {
        Timber.i("cancelling connect attempt");
    }

    if (bondLost) {
        completeDisconnect(false, GATT_SUCCESS);
        if (listener != null) {
            // Consider the loss of the bond a connection failure so that a connection retry will take place
            callbackHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    listener.connectFailed(BluetoothPeripheral.this, GATT_SUCCESS);
                }
            }, DELAY_AFTER_BOND_LOST); // Give the stack some time to register the bond loss internally. This is needed on most phones...
        }
    } else {
        completeDisconnect(true, GATT_SUCCESS);
    }
}
 
Example 7
Source File: DeviceActivity.java    From BLERW with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
		int newState) {
	if (newState == BluetoothProfile.STATE_CONNECTED) {
		mStatus = newState;
		mConnGatt.discoverServices();
	} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
		mStatus = newState;
		runOnUiThread(new Runnable() {
			public void run() {
				mReadManufacturerNameButton.setEnabled(false);
				mReadSerialNumberButton.setEnabled(false);
				mWriteAlertLevelButton.setEnabled(false);
			};
		});
	}
}
 
Example 8
Source File: BroadcomBle.java    From GizwitsBLE with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothDevice device, int status,
		int newState) {
	if (mBluetoothGatt == null) {
		return;
	}

	if (newState == BluetoothProfile.STATE_CONNECTED) {
		mService.bleGattConnected(device);
		mBluetoothGatt.discoverServices(device);
		mAddress = device.getAddress();
	} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
		mService.bleGattDisConnected(device.getAddress());
		mAddress = null;
	}
}
 
Example 9
Source File: PairedDevicesFragment.java    From wearmouse with Apache License 2.0 6 votes vote down vote up
@Override
@MainThread
public void onConnectionStateChanged(BluetoothDevice device, int state) {
    updatePreferenceBondState(device);

    Context context = getContext();
    if (state != BluetoothProfile.STATE_DISCONNECTED) {
        Intent intent = NotificationService.buildIntent(device.getName(), state);
        intent.setClass(context, NotificationService.class);
        context.startService(intent);
    }

    if (state == BluetoothProfile.STATE_CONNECTED) {
        ((WearablePreferenceActivity) getActivity())
                .startPreferenceFragment(new ModeSelectFragment(), true);
    }
}
 
Example 10
Source File: BluetoothLeDeviceBase.java    From BlogPracticeDems with Apache License 2.0 6 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        if (connectChangedListener != null) {
            connectChangedListener.onConnected();
        }
        mConnectionState = STATE_CONNECTED;
        mBluetoothGatt.discoverServices();

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        if (connectChangedListener != null) {
            connectChangedListener.onDisconnected();
        }
        mConnectionState = STATE_DISCONNECTED;
    }
}
 
Example 11
Source File: MkrSciBleManager.java    From science-journal with Apache License 2.0 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
  if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) {
    this.gatt = gatt;
    characteristics.clear();
    gatt.discoverServices();
  } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
    readyForAction = false;
    gatt.disconnect();
  }
}
 
Example 12
Source File: SecurityChipTestActivity.java    From NewXmPluginSDK with Apache License 2.0 5 votes vote down vote up
private void doBoltOperate() {
    if (isOperating) {
        updateLockMsg("正在反锁操作,请等待");
        return;
    }

    if (XmBluetoothManager.getInstance().getConnectStatus(mDevice.getMac()) == BluetoothProfile.STATE_CONNECTED) {
        mHandler.sendEmptyMessageDelayed(MSG_BOLT_TIMEOUT, OPERATE_TIMEOUT);
        isOperating = true;
        XmBluetoothManager.getInstance().securityChipOperate(
                mDevice.getMac(),
                XmBluetoothManager.SECURITY_CHIP_BOLT_OPERATOR,
                new Response.BleReadResponse() {
                    @Override
                    public void onResponse(int code, byte[] data) {
                        isOperating = false;
                        mHandler.removeMessages(MSG_BOLT_TIMEOUT);
                        if (code == XmBluetoothManager.Code.REQUEST_SUCCESS) {
                            updateLockMsg("反锁成功, data = " + toHexString(data));
                        } else {
                            updateLockMsg("反锁失败");
                        }
                    }
                });
    } else {
        Toast.makeText(activity(), "设备未连接,请先建立连接", Toast.LENGTH_SHORT).show();
    }
}
 
Example 13
Source File: MyoGattCallback.java    From myo_AndoridEMG with MIT License 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    super.onConnectionStateChange(gatt, status, newState);
    Log.d(TAG, "onConnectionStateChange: " + status + " -> " + newState);
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        // GATT Connected
        // Searching GATT Service
        gatt.discoverServices();

    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        // GATT Disconnected
        stopCallback();
        Log.d(TAG,"Bluetooth Disconnected");
    }
}
 
Example 14
Source File: BLEComm.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
private synchronized void onConnectionStateChangeSynchronized(BluetoothGatt gatt, int status, int newState) {
    if (L.isEnabled(L.PUMPBTCOMM))
        log.debug("onConnectionStateChange");

    if (newState == BluetoothProfile.STATE_CONNECTED) {
        mBluetoothGatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        close();
        isConnected = false;
        isConnecting = false;
        RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED));
        if (L.isEnabled(L.PUMPBTCOMM))
            log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected
    }
}
 
Example 15
Source File: DexShareCollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    Log.w(TAG, "Gatt state change status: " + status + " new state: " + newState);
    writeStatusConnectionFailures(status);
    if (status == 133) {
        Log.e(TAG, "Got the status 133 bug, GROSS!!");
    }
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        mBluetoothGatt = gatt;
        device = mBluetoothGatt.getDevice();
        mConnectionState = STATE_CONNECTED;
        ActiveBluetoothDevice.connected();
        Log.w(TAG, "Connected to GATT server.");

        Log.w(TAG, "discovering services");
        currentGattTask = GATT_SETUP;
        if (!mBluetoothGatt.discoverServices()) {
            Log.w(TAG, "discovering failed");
            if(shouldDisconnect) {
                stopSelf();
            } else {
                setRetryTimer();
            }
        }
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        mConnectionState = STATE_DISCONNECTED;
        ActiveBluetoothDevice.disconnected();
        if(shouldDisconnect) {
            stopSelf();
        } else {
            setRetryTimer();
        }
        Log.w(TAG, "Disconnected from GATT server.");
    } else {
        Log.w(TAG, "Gatt callback... strange state.");
    }
}
 
Example 16
Source File: AbstractHOGPServer.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Override
public void onConnectionStateChange(final BluetoothDevice device, final int status, final int newState) {
    if (DEBUG) {
        Log.d(TAG, "onConnectionStateChange status: " + status + ", newState: " + newState);
    }

    if (mGattServer == null) {
        return;
    }

    switch (newState) {
        case BluetoothProfile.STATE_CONNECTED:
            if (DEBUG) {
                Log.d(TAG, "BluetoothProfile.STATE_CONNECTED bondState: " + device.getBondState());
            }

            // check bond status
            if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                paringDevice(device);
            } else if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                connectDevice(device);
            }
            break;

        case BluetoothProfile.STATE_DISCONNECTED:
            if (DEBUG) {
                Log.w(TAG, "BluetoothProfile.STATE_DISCONNECTED");
            }
            disconnectDevice(device);
            break;

        default:
            // do nothing
            break;
    }
}
 
Example 17
Source File: DexCollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        mConnectionState = STATE_CONNECTED;
        ActiveBluetoothDevice.connected();
        Log.w(TAG, "Connected to GATT server.");
        mBluetoothGatt.discoverServices();
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        mConnectionState = STATE_DISCONNECTED;
        ActiveBluetoothDevice.disconnected();
        Log.w(TAG, "Disconnected from GATT server.");
        setRetryTimer();
    }
}
 
Example 18
Source File: BleRequestImpl.java    From Android-BLE with Apache License 2.0 4 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
                                    int newState) {
    BluetoothDevice device = gatt.getDevice();
    if (device == null){
        return;
    }
    String address = device.getAddress();
    //remove timeout callback
    cancelTimeout(address);
    T bleDevice = getBleDeviceInternal(address);
    //There is a problem here Every time a new object is generated that causes the same device to be disconnected and the connection produces two objects
    if (status == BluetoothGatt.GATT_SUCCESS) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            connectedAddressList.add(device.getAddress());
            if (connectWrapperCallback != null){
                bleDevice.setConnectionState(BleDevice.CONNECTED);
                connectWrapperCallback.onConnectionChanged(bleDevice);
            }
            BleLog.d(TAG, "onConnectionStateChange:----device is connected.");
            BluetoothGatt bluetoothGatt = gattHashMap.get(device.getAddress());
            if (null != bluetoothGatt){
                // Attempts to discover services after successful connection.
                BleLog.d(TAG, "trying to start service discovery");
                bluetoothGatt.discoverServices();
            }
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            BleLog.d(TAG, "onConnectionStateChange:----device is disconnected.");
            if (connectWrapperCallback != null){
                bleDevice.setConnectionState(BleDevice.DISCONNECT);
                connectWrapperCallback.onConnectionChanged(bleDevice);
            }
            close(device.getAddress());
        }
    } else {
        //Occurrence 133 or 257 19 Equal value is not 0: Connection establishment failed due to protocol stack
        BleLog.e(TAG, "onConnectionStateChange----: " + "Connection status is abnormal:" + status);
        close(device.getAddress());
        if (connectWrapperCallback != null){
            int errorCode = getErrorCode(bleDevice);
            connectWrapperCallback.onConnectException(bleDevice, errorCode);
            bleDevice.setConnectionState(BleDevice.DISCONNECT);
            connectWrapperCallback.onConnectionChanged(bleDevice);
        }
    }

}
 
Example 19
Source File: UpdateFragment.java    From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void updateUiForBeacons(int connectionState, int lockState) {
    switch (connectionState) {
        case BluetoothProfile.STATE_CONNECTED:
            if (UpdateService.LOCKED == lockState) {
                mIsBeaconLocked = true;
                mCurrentLockState = LOCKED;
            } else if(UpdateService.UNLOCKED == lockState || UpdateService.UNLOCKED_AUTOMATIC_RELOCK_DISABLED == lockState) {
                mChallenge = null; //setting the challenge to a null or else the user will be prompted with a unlock failure message
                mCurrentLockState = lockState;
                mIsBeaconLocked = false;
                mBeaconHelp.setVisibility(View.GONE);
                mBeaconConfigurationContainer.setVisibility(View.VISIBLE);
                mFrameTypeContainer.setVisibility(View.VISIBLE);
            }
            break;
        case BluetoothProfile.STATE_DISCONNECTED:
            setHasOptionsMenu(false);
            getActivity().invalidateOptionsMenu();
            if(mClearActiveSlot != null) {
                mClearActiveSlot.setImageBitmap(null);
                mClearActiveSlot = null;
            }
            if(mRefreshActiveSlot != null) {
                mRefreshActiveSlot.setImageBitmap(null);
                mRefreshActiveSlot = null;
            }
            mBeaconHelp.setVisibility(View.VISIBLE);
            mBeaconConfigurationContainer.setVisibility(View.GONE);
            mFrameTypeContainer.setVisibility(View.GONE);
            //clear all resources on disconnection
            mBeaconPublicEcdhKey = null;
            mDecryptedIdentityKey = null;
            mServiceEcdhKey = null;
            mIsBeaconLocked = true;
            if(mActiveSlotsTypes != null) {
                mActiveSlotsTypes.clear();
            }
            if(mMaxActiveSlotsAdapter != null){
                mMaxActiveSlotsAdapter.clear();
                mMaxActiveSlotsAdapter = null;
            }
            break;
    }
}
 
Example 20
Source File: DexShareCollectionService.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
    Log.i(TAG, "Gatt state change status: " + status + " new state: " + newState);
    if (status == 133) {
        statusErrors++;
        Log.e(TAG, "Got the status 133 bug, bad news! count:"+statusErrors+" - Might require devices to forget each other: instance uptime: "+JoH.qs((JoH.ts()-instance)/1000,0));
        if (statusErrors>4)
        {
            Log.wtf(TAG,"Forcing bluetooth reset to try to combat errors");
            statusErrors=0;
            JoH.niceRestartBluetooth(getApplicationContext());
            setRetryTimer();
            close();
            stopSelf();
            return;
        }
    }
    if (newState == BluetoothProfile.STATE_CONNECTED) {
        mBluetoothGatt = gatt;
        device = mBluetoothGatt.getDevice();
        mConnectionState = STATE_CONNECTED;
        ActiveBluetoothDevice.connected();
        Log.i(TAG, "Connected to GATT server.");

        Log.i(TAG, "discovering services");
        currentGattTask = GATT_SETUP;
        if (mBluetoothGatt == null || !mBluetoothGatt.discoverServices()) {
            Log.w(TAG, "discovering failed");
            if(shouldDisconnect) {
                stopSelf();
            } else {
                setRetryTimer();
            }
        }
    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
        mConnectionState = STATE_DISCONNECTED;
        ActiveBluetoothDevice.disconnected();
        if(shouldDisconnect) {
            stopSelf();
        } else {
            setRetryTimer();
        }
        Log.d(TAG, "Disconnected from GATT server.");
    } else {
        Log.d(TAG, "Gatt callback... strange state.");
    }
}