所有程序执行的代码都是有入口的,在这里我们暂时分析一种情景,蓝牙打开着,蓝牙耳机连接。
在设置界面点击蓝牙耳机操作:
packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothDevicePreference.java
void onClicked() {
int bondState = mCachedDevice.getBondState();
if (mCachedDevice.isConnected()) {
askDisconnect();
} else if (bondState == BluetoothDevice.BOND_BONDED) { //已经配对,但是未连接
mCachedDevice.connect(true);
} else if (bondState == BluetoothDevice.BOND_NONE) { //没有配对
pair();
}
}
mCachedDevice.connect(true);方法会直接调用CachedBluetoothDevice.java的connect的方法。
packages/apps/Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
void connect(boolean connectAllProfiles) {
if (!ensurePaired()) { //配对处理暂时不关注
return;
}
mConnectAttempted = SystemClock.elapsedRealtime();
connectWithoutResettingTimer(connectAllProfiles);
}
代码执行到connectWithoutResettingTimer,注释就不粘贴了。
private void connectWithoutResettingTimer(boolean connectAllProfiles) {
......
// Reset the only-show-one-error-dialog tracking variable
mIsConnectingErrorPossible = true;
int preferredProfiles = 0;
for (LocalBluetoothProfile profile : mProfiles) {
if (connectAllProfiles ? profile.isConnectable() : profile.isAutoConnectable()) {
if (profile.isPreferred(mDevice)) {
++preferredProfiles;
connectInt(profile);
}
}
}
if (DEBUG) Log.d(TAG, "Preferred profiles = " + preferredProfiles);
if (preferredProfiles == 0) {
connectAutoConnectableProfiles();
}
}
不同的协议实现类,继承于LocalBluetoothProfile,以HeadsetProfile为例。
synchronized void