差满多乃几

Android Bluetooth

    蓝牙,Bluetooth,统一无线局域网通讯的标准的蓝牙技术,以低成本的近距离无线连接为基础,为移动通信设备建立一个短程无线连接。其实质内容是建立通用的无线电空中接口,使计算机和通信设备进一步结合,让不同的厂家生产便携式设备在没有电缆或电线相互连接的情况下,能在近距离范围内具有相互通信的一种技术。

特点:

    全球范围适用:使用展频、调频、全双工信号,标称速率为1600跳/秒。在大多数国家,无需经过许可便可使用2.4 GHz ISM波段;

    抗干扰:适配跳频(AFH)能力减少共用2.4 GHz频谱的无线技术之间出现的干扰;

    射程:根据具体应用中使用的射频种类,射程将有所不同;第三类射频 – 射程最高1米或3英尺;第二类射频 – 最常见于移动设备,射程为10米或33英尺;第一类射频 – 主要用于工业用例,射程为100米或300英尺;

    低功耗:蓝牙技术的设计能耗非常之低,规格允许射频处于非活跃状态时可以断电则进一步降低了能耗;

Android中的应用:

1,Bluetooth启动

    Android init进程中,启动Zygote后,由SystemServer启动Bleetooth服务,启动前通过SystemProperties的get方法来判断系统是不是使用模拟器内核;

  • 使用模拟器内核来启动android的系统,跳过蓝牙服务的启动,Android 4.0模拟器不支持蓝牙系统;

  • 真机启动,构造一个bluetooth的服务(BluetoothService)和一个蓝牙耳机服务(BluetoothA2dpService)

    另外,判断开机是否要启用蓝牙,若是飞行模式,关闭所有的使用无线频谱的模块(wifi,Bluetooth,GPS ...);若不是飞行模式且bluetooth开关为on,开启蓝牙服务,bluetoothService.enable();

/framework/base/services/java/com/android/server/SystemServer.java

// Skip Bluetooth if we have an emulator kernel
// TODO: Use a more reliable check to see if this product should
// support Bluetooth - see bug 988521
if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
    Slog.i(TAG, "No Bluetooh Service (emulator)");
} else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
    Slog.i(TAG, "No Bluetooth Service (factory test)");
} else {
    Slog.i(TAG, "Bluetooth Service");
    bluetooth = new BluetoothService(context);
    ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);
    bluetooth.initAfterRegistration();
    bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);
    ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,
                              bluetoothA2dp);
    bluetooth.initAfterA2dpRegistration();

    int airplaneModeOn = Settings.System.getInt(mContentResolver,
            Settings.System.AIRPLANE_MODE_ON, 0);
    int bluetoothOn = Settings.Secure.getInt(mContentResolver,
            Settings.Secure.BLUETOOTH_ON, 0);
    if (airplaneModeOn == 0 && bluetoothOn != 0) {
        bluetooth.enable();
    }
}

    BluetoothService的enable()会先判断进程有没有蓝牙管理的操作权限,然后再次判断系统的飞行模式有没有打开,若此时飞行模式是on,返回,不开蓝牙服务。在确保拥有权限并且不是出于飞行模式的情况下,往蓝牙状态机发送一个USER_TURN_ON的命令;

/framework/base/core/java/android/server/BluetoothService.java

public synchronized boolean enable(boolean saveSetting) {
        mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
                 "Need BLUETOOTH_ADMIN permission");
        // Airplane mode can prevent Bluetooth radio from being turned on.
        if (mIsAirplaneSensitive && isAirplaneModeOn() && !mIsAirplaneToggleable) {
            return false;
        }
        mBluetoothState.sendMessage(BluetoothAdapterStateMachine.USER_TURN_ON                ,saveSetting);
        return true;
    }