蓝牙打开流程:
android蓝牙打开流程之Off状态至BleOn状态-CSDN博客
android蓝牙打开流程之BleOn状态至On状态-CSDN博客
进入BleOn状态会先执行状态机的enter函数。
private class BleOnState extends BaseAdapterState {
...
}
private abstract class BaseAdapterState extends State {
@Override
public void enter() {
int currState = getStateValue();
infoLog("entered ");
mAdapterService.updateAdapterState(mPrevState, currState);
mPrevState = currState;
}
}
通过updateAdapterState最终将BleOn的状态变化传递给BluetoothManagerService。
void updateAdapterState(int prevState, int newState) {
mAdapterProperties.setState(newState);
if (mCallbacks != null) {
int n = mCallbacks.beginBroadcast();
for (int i = 0; i < n; i++) {
try {
mCallbacks.getBroadcastItem(i).onBluetoothStateChange(prevState, newState);
} catch (RemoteException e) {
debugLog("updateAdapterState() - Callback #" + i + " failed (" + e + ")");
}
}
mCallbacks.finishBroadcast();
}
...
}
private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
@Override
public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
Message msg =
mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE, prevState, newState);
mHandler.sendMessage(msg);
}
};
case MESSAGE_BLUETOOTH_STATE_CHANGE: {
bluetoothStateChangeHandler(prevState, newState);
private void bluetoothStateChangeHandler(int prevState, int newState) {
if (newState == BluetoothAdapter.STATE_BLE_ON || newState == BluetoothAdapter.STATE_OFF) {
boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
&& newState == BluetoothAdapter.STATE_BLE_ON);
else if (!intermediate_off) {
if (mBluetoothGatt != null || !mContext.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
continueFromBleOnState();
}
}
}
通过continueFromBleOnState继续BR开启流程,实际就是向adapter状态机发送了一条消息USER_TURN_ON。
private void continueFromBleOnState() {
if (isBluetoothPersistedStateOnBluetooth() || !isBleAppPresent()) {
// This triggers transition to STATE_ON
mBluetooth.onLeServiceUp();
persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
}
}
void onLeServiceUp() {
mAdapterStateMachine.sendMessage(AdapterState.USER_TURN_ON);
}
状态机在BleOnState状态处理这条消息,通过startProfileServices开启BR所有当前系统支持的profile。
private class BleOnState extends BaseAdapterState {
@Override
public boolean processMessage(Message msg) {
switch (msg.what) {
case USER_TURN_ON:
transitionTo(mTurningOnState);
break;
}
}
}
private class TurningOnState extends BaseAdapterState {
@Override
public void enter() {
super.enter();
sendMessageDelayed(BREDR_START_TIMEOUT, BREDR_START_TIMEOUT_DELAY);
mAdapterService.startProfileServices();
}
}
核心就是启动Bluetooth.apk中的各个profile的xxService,比如A2dpService.java/HeadsetService.java等等。
void startProfileServices() {
debugLog("startCoreServices()");
Class[] supportedProfileServices = Config.getSupportedProfiles();
if (supportedProfileServices.length == 1 && GattService.class.getSimpleName()
.equals(supportedProfileServices[0].getSimpleName())) {
mAdapterProperties.onBluetoothReady();
updateUuids();
setBluetoothClassFromConfig();
mAdapterStateMachine.sendMessage(AdapterState.BREDR_STARTED);
} else {
setAllProfileServiceStates(supportedProfileServices, BluetoothAdapter.STATE_ON);
}
}
private void setAllProfileServiceStates(Class[] services, int state) {
for (Class service : services) {
if (GattService.class.getSimpleName().equals(service.getSimpleName())) {
continue;
}
setProfileServiceState(service, state);
}
}
private void setProfileServiceState(Class service, int state) {
Intent intent = new Intent(this, service);
intent.putExtra(EXTRA_ACTION, ACTION_SERVICE_STATE_CHANGED);
intent.putExtra(BluetoothAdapter.EXTRA_STATE, state);
startService(intent);
}
以A2dpService.java为例,A2dpService继承ProfileService,按照android service的启动流程,会顺序执行onCreate和onStartCommand,从而执行A2dpService中自定义的create和start函数;执行完毕之后通过onProfileServiceStateChanged通知出去。
public class A2dpService extends ProfileService {
@Override
protected IProfileServiceBinder initBinder() {
return new BluetoothA2dpBinder(this);
}
@Override
protected void create() {
Log.i(TAG, "create()");
}
@Override
protected boolean start() {
...
}
}
public abstract class ProfileService extends Service {
@Override
public void onCreate() {
...
mAdapter = BluetoothAdapter.getDefaultAdapter();
mBinder = initBinder();
create();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
String action = intent.getStringExtra(AdapterService.EXTRA_ACTION);
if (AdapterService.ACTION_SERVICE_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_OFF) {
doStop();
} else if (state == BluetoothAdapter.STATE_ON) {
doStart();
}
}
return PROFILE_SERVICE_MODE;
}
private void doStart() {
...
mProfileStarted = start();
mAdapterService.onProfileServiceStateChanged(this, BluetoothAdapter.STATE_ON);
}
}
processProfileServiceStateChanged函数会比较配置文件中开启的profile和当前已经运行的profile数量是否一致,如果一致则向adapter状态机发送BREDR_STARTED消息。
public void onProfileServiceStateChanged(ProfileService profile, int state) {
Message m = mHandler.obtainMessage(MESSAGE_PROFILE_SERVICE_STATE_CHANGED);
m.obj = profile;
m.arg1 = state;
mHandler.sendMessage(m);
}
case MESSAGE_PROFILE_SERVICE_STATE_CHANGED:
processProfileServiceStateChanged((ProfileService) msg.obj, msg.arg1);
break;
private void processProfileServiceStateChanged(ProfileService profile, int state) {
switch (state) {
case BluetoothAdapter.STATE_ON:
if (!mRegisteredProfiles.contains(profile)) {
Log.e(TAG, profile.getName() + " not registered (STATE_ON).");
return;
}
if (mRunningProfiles.contains(profile)) {
Log.e(TAG, profile.getName() + " already running.");
return;
}
mRunningProfiles.add(profile);
if (GattService.class.getSimpleName().equals(profile.getName())) {
enableNativeWithGuestFlag();
} else if (mRegisteredProfiles.size() == Config.getSupportedProfiles().length
&& mRegisteredProfiles.size() == mRunningProfiles.size()) {
mAdapterProperties.onBluetoothReady();
updateUuids();
setBluetoothClassFromConfig();
mAdapterStateMachine.sendMessage(AdapterState.BREDR_STARTED);
}
break;
TurningOnState状态收到BREDR_STARTED之后,会转移状态至OnState。
private class TurningOnState extends BaseAdapterState {
@Override
public boolean processMessage(Message msg) {
switch (msg.what) {
case BREDR_STARTED:
transitionTo(mOnState);
break;
}
}
最后通过ACTION_STATE_CHANGED广播将蓝牙打开完成的状态告知感兴趣的模块。
private class OnState extends BaseAdapterState {
...
}
private abstract class BaseAdapterState extends State {
@Override
public void enter() {
int currState = getStateValue();
infoLog("entered ");
mAdapterService.updateAdapterState(mPrevState, currState);
mPrevState = currState;
}
}
void updateAdapterState(int prevState, int newState) {
mAdapterProperties.setState(newState);
if (mCallbacks != null) {
int n = mCallbacks.beginBroadcast();
for (int i = 0; i < n; i++) {
try {
mCallbacks.getBroadcastItem(i).onBluetoothStateChange(prevState, newState);
} catch (RemoteException e) {
debugLog("updateAdapterState() - Callback #" + i + " failed (" + e + ")");
}
}
mCallbacks.finishBroadcast();
}
...
}
private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
@Override
public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
Message msg =
mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE, prevState, newState);
mHandler.sendMessage(msg);
}
};
case MESSAGE_BLUETOOTH_STATE_CHANGE: {
bluetoothStateChangeHandler(prevState, newState);
private void bluetoothStateChangeHandler(int prevState, int newState) {
boolean isStandardBroadcast = true;
...
else if (newState == BluetoothAdapter.STATE_ON) {
boolean isUp = (newState == BluetoothAdapter.STATE_ON);
sendBluetoothStateCallback(isUp);
sendBleStateChanged(prevState, newState);
}
...
if (isStandardBroadcast) {
if (prevState == BluetoothAdapter.STATE_BLE_ON) {
// Show prevState of BLE_ON as OFF to standard users
prevState = BluetoothAdapter.STATE_OFF;
}
Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
}
}
至此,蓝牙打开完毕。