2014年12月17日 星期三

BT_一般掃描流程(轉)

原作者 平淡

android4.3中引入了藍牙低能耗le(low energy),相應的也有一些方法/類。不過代碼裡,並沒有找到初始調用的地方。所以這裡還是先只分析下bt普通的掃描流程(類似android 4.2),先貼出流程圖


主要通過“掃描”的流程來分析下
复制代码
BluetoothSettings.java::startScanning            ----package

LocalBluetoothAdapter.java::startScanning       ----package

BluetoothAdapter.java::startDiscovery            ----framework

AdapterService.java::startDiscovery              ----package

com_android_bluetooth_btservice_AdapterService.cpp::startDiscoveryNative -jni
复制代码
從這裡開始分析下用到的一些變量和結構體
首先看startDiscoveryNative方法:
复制代码
  static jboolean startDiscoveryNative(JNIEnv* env, jobject obj) {                                                   
      ALOGV("%s:",__FUNCTION__); 

      jboolean result = JNI_FALSE; 
      if (!sBluetoothInterface) return result; 
                                                                
      int ret = sBluetoothInterface->start_discovery();         
      result = (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
      return result;                                            
  }
复制代码
 分析点: int ret = sBluetoothInterface->start_discovery(); 
----------------------------------------------------------------------------
sBluetoothInterface的來源
查看com_android_bluetooth_btservice_AdapterService.cpp所在目錄的Android.mk文件,
复制代码
......
LOCAL_SHARED_LIBRARIES := \
    libandroid_runtime \
    libnativehelper \
    libcutils \
    libutils \
    liblog \
    libhardware
......
复制代码
libhardware是編譯時用到的,一般都是在hardware目錄中。然後可以在子目錄libhardware下找到bluetooth.h。在bluetooth.h中定義了bt_interface_t結構體。繼而尋找該結構體對像的創建位置。在external/bluetooth/bluedroid/btif/src/bluetooth.c文件中找到。如下所示:
复制代码
static const bt_interface_t bluetoothInterface = {
    sizeof(bluetoothInterface),    
    init,
    enable,
    disable,
    cleanup,
    get_adapter_properties,   
    get_adapter_property,
    set_adapter_property,
    get_remote_device_properties,  
    get_remote_device_property,    
    set_remote_device_property,    
    get_remote_service_record,
    get_remote_services,
    start_discovery,
    cancel_discovery,
    create_bond,
    remove_bond,
    cancel_bond,
    pin_reply,
    ssp_reply,
    get_profile_interface,
    dut_mode_configure,
    dut_mode_send,
#if BLE_INCLUDED == TRUE
    le_test_mode
#else
    NULL
#endif
};
复制代码
sBluetoothInterface對像便是獲得了bluetoothInterface對象。
接下來,打開藍牙、掃描等功能就會通過sBluetoothInterface調用結構體中聲明的相應方法了。

流程:settings界面發起,LocalBluetoothAdapter.java過渡,去framework的轉轉(BluetoothAdapter.java)後,回到packages的AdapterService.java,再走JNI,接著去external處理。
----------------------------------------------------------------------------
接下来,跟一遍star_discovery
 1.已經找到JNI層startDiscoveryNative函數對應的start_discovery方法(bluetooth.c),分析之。
复制代码
static int start_discovery(void)
{
    /* sanity check */
    if (interface_ready() == FALSE)    
        return BT_STATUS_NOT_READY;

    return btif_dm_start_discovery();
}
复制代码
2.分析btif_dm_start_discovery方法(btif_dm.c)
复制代码
bt_status_t btif_dm_start_discovery(void)
{
    tBTA_DM_INQ inq_params;
    tBTA_SERVICE_MASK services = 0;
    
    BTIF_TRACE_EVENT1("%s", __FUNCTION__);
    /* TODO: Do we need to handle multiple inquiries at the same time? */
    
    /* Set inquiry params and call API */
#if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE))
    inq_params.mode = BTA_DM_GENERAL_INQUIRY|BTA_BLE_GENERAL_INQUIRY;
#else
    inq_params.mode = BTA_DM_GENERAL_INQUIRY;
#endif 
    inq_params.duration = BTIF_DM_DEFAULT_INQ_MAX_DURATION;

    inq_params.max_resps = BTIF_DM_DEFAULT_INQ_MAX_RESULTS;
    inq_params.report_dup = TRUE;

    inq_params.filter_type = BTA_DM_INQ_CLR;
    /* TODO: Filter device by BDA needs to be implemented here */
    
    /* Will be enabled to TRUE once inquiry busy level has been received */
    btif_dm_inquiry_in_progress = FALSE;
    /* find nearby devices */ //下面是關鍵語句
    BTA_DmSearch(&inq_params, services, bte_search_devices_evt);

    return BT_STATUS_SUCCESS;
复制代码
(1) BTA_DmSearch分析
复制代码
void BTA_DmSearch(tBTA_DM_INQ *p_dm_inq, tBTA_SERVICE_MASK services, tBTA_DM_SEARCH_CBACK *p_cback) 
{

    tBTA_DM_API_SEARCH    *p_msg;  

    if ((p_msg = (tBTA_DM_API_SEARCH *) GKI_getbuf(sizeof(tBTA_DM_API_SEARCH))) != NULL)
    {
        memset(p_msg, 0, sizeof(tBTA_DM_API_SEARCH));

        p_msg->hdr.event = BTA_DM_API_SEARCH_EVT;
        memcpy(&p_msg->inq_params, p_dm_inq, sizeof(tBTA_DM_INQ));
        p_msg->services = services;    
        p_msg->p_cback = p_cback;      
        p_msg->rs_res  = BTA_DM_RS_NONE;
        bta_sys_sendmsg(p_msg);        
    }  

}
复制代码
看來只是發出一個消息,傳遞參數值。
(2)bte_search_devices_evt (btif_dm.c)
這條語句中,bte_search_devices_evt是真正用來搜索的,分析這個方法。貼出代碼:
复制代码
static void bte_search_devices_evt(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH *p_data)
{
    UINT16 param_len = 0;

    if (p_data)
        param_len += sizeof(tBTA_DM_SEARCH);
    /* Allocate buffer to hold the pointers (deep copy). The pointers will point to the end of the tBTA_DM_SEARCH */
    switch (event)
    {
        case BTA_DM_INQ_RES_EVT:
        {
            if (p_data->inq_res.p_eir)
                param_len += HCI_EXT_INQ_RESPONSE_LEN;
        }
        break;

        case BTA_DM_DISC_RES_EVT:
        {
            if (p_data->disc_res.raw_data_size && p_data->disc_res.p_raw_data)
                param_len += p_data->disc_res.raw_data_size;
        }
        break;
    }
    BTIF_TRACE_DEBUG3("%s event=%s param_len=%d", __FUNCTION__, dump_dm_search_event(event), param_len);

    /* if remote name is available in EIR, set teh flag so that stack doesnt trigger RNR */
    if (event == BTA_DM_INQ_RES_EVT)
        p_data->inq_res.remt_name_not_required = check_eir_remote_name(p_data, NULL, NULL);

    btif_transfer_context (btif_dm_search_devices_evt , (UINT16) event, (void *)p_data, param_len,
        (param_len > sizeof(tBTA_DM_SEARCH)) ? search_devices_copy_cb : NULL);
}
复制代码
看注釋,這個方法作用就是Switches context from BTE to BTIF for DM search events,即將context從bte傳給btif中的dm search事件。所以關鍵點在於btif_dm_search_devices_evt方法(btif_dm.c文件中定義),繼續貼代碼:
复制代码
static void btif_dm_search_devices_evt (UINT16 event, char *p_param)
{
    switch (event)
    {
        case BTA_DM_INQ_RES_EVT:
        {
            /* inquiry result */
            UINT32 cod;
            UINT8 *p_eir_remote_name = NULL;
            bt_bdname_t bdname;
            bt_bdaddr_t bdaddr;
            UINT8 remote_name_len;
            UINT8 *p_cached_name = NULL;
            tBTA_SERVICE_MASK services = 0;
            bdstr_t bdstr;

            p_search_data = (tBTA_DM_SEARCH *)p_param;
            //解析mac地址
            bdcpy(bdaddr.address, p_search_data->inq_res.bd_addr);
                
                /* Callback to notify upper layer of device */
                //下面是關鍵語句,回調方法
                HAL_CBACK(bt_hal_cbacks, device_found_cb,
                                 num_properties, properties);
            }
        }
        break;
......
复制代码
HAL_CBACK會注冊回調方法,這裡,會調用結構體對像bt_hal_cbacks中的device_found_cb方法。

繼續擴展:
(a) bt_hal_cbacks對像分析   (根據初始化流程分析從頭分析該bt_hal_cback對像的由來)
(a.1)首先,在AdapterService.java::onCreate方法中,有initNative方法。在相應JNI文件com_android_bluetooth_btservice_AdapterService.cpp中找到該方法,如下:
复制代码
static bool initNative(JNIEnv* env, jobject obj) {
    ALOGV("%s:",__FUNCTION__);
    ......
    if (sBluetoothInterface) {
        int ret = sBluetoothInterface->init(&sBluetoothCallbacks);
  ......
}
复制代码
(a.1.1)該JNI文件中定義了sBluetoothCallbacks,如下:
复制代码
bt_callbacks_t sBluetoothCallbacks = {
    sizeof(sBluetoothCallbacks),   
    adapter_state_change_callback, 
    adapter_properties_callback,   
    remote_device_properties_callback,
    device_found_callback,
    discovery_state_changed_callback,
    pin_request_callback,
    ssp_request_callback,
    bond_state_changed_callback,   
    acl_state_changed_callback,    
    callback_thread_event,
    dut_mode_recv_callback,

    le_test_mode_recv_callback
};
复制代码
bt_callbacks_t結構體的定義在hardware/libhardware/include/hardware/bluetooth.h中,代碼如下:
复制代码
/** Bluetooth DM callback structure. */
typedef struct {
    /** set to sizeof(bt_callbacks_t) */
    size_t size;
    adapter_state_changed_callback adapter_state_changed_cb;
    adapter_properties_callback adapter_properties_cb;
    remote_device_properties_callback remote_device_properties_cb;
    device_found_callback device_found_cb;
    discovery_state_changed_callback discovery_state_changed_cb;
    pin_request_callback pin_request_cb;
    ssp_request_callback ssp_request_cb;
    bond_state_changed_callback bond_state_changed_cb;
    acl_state_changed_callback acl_state_changed_cb;
    callback_thread_event thread_evt_cb;
    dut_mode_recv_callback dut_mode_recv_cb;
    le_test_mode_callback le_test_mode_cb;
} bt_callbacks_t;
复制代码
(a.1.2) 分析sBluetoothInterface對像的init方法。
因為sBluetoothInterface對像的值也是在bluetooth.c文件中定義的bluetoothInterface對像賦值的,所以直接找bluetoothInterface對像的定義處。
复制代码
static const bt_interface_t bluetoothInterface = {
    sizeof(bluetoothInterface),    
    init,
    enable,
    disable,
    cleanup,
    get_adapter_properties,
    get_adapter_property,
    set_adapter_property,
    get_remote_device_properties,  
    get_remote_device_property,    
    set_remote_device_property,    
    get_remote_service_record,
    get_remote_services,
    start_discovery,
    cancel_discovery,
    create_bond,
    remove_bond,
    cancel_bond,
    pin_reply,
    ssp_reply,
    get_profile_interface,
    dut_mode_configure,
    dut_mode_send,
#if BLE_INCLUDED == TRUE
    le_test_mode
#else
    NULL
#endif
};
复制代码
在該結構體中找到init方法,然後繼續在bluetooth.c中找init方法的定義。
复制代码
static int init(bt_callbacks_t* callbacks )
{
    ALOGI("init");

    /* sanity check */
    if (interface_ready() == TRUE)
        return BT_STATUS_DONE;

    /* store reference to user callbacks */
    bt_hal_cbacks = callbacks; //這裡為bt_hal_cbacks對象賦值

    /* add checks for individual callbacks ? */

    bt_utils_init();

    /* init btif */
    btif_init_bluetooth();

    return BT_STATUS_SUCCESS;
}
复制代码
通過上面標注的語句就知道了bt_hal_cback對像的由來,即sBluetoothCallbacks對像。

(b) HAL_CBACK分析
复制代码
#define HAL_CBACK(P_CB, P_CBACK, ...)\
    if (P_CB && P_CB->P_CBACK) {            \
        BTIF_TRACE_API2("HAL %s->%s", #P_CB, #P_CBACK); \
        P_CB->P_CBACK(__VA_ARGS__);         \
    }                                       \
    else {                                  \
        ASSERTC(0, "Callback is NULL", 0);  \
    }
复制代码
這個宏主要就是執行了P_CB->P_CBACK(__VA_ARGS__); 在這裡就是bt_hal_cback-> device_found_cb(...)方法。然後找到 sBluetoothCallbacks對像中對應的方法device_found_callback,繼而找到該方法定義處。
static void device_found_callback(int num_properties, bt_property_t *properties) {
  ......
      callbackEnv->CallVoidMethod(sJniCallbacksObj, method_deviceFoundCallback, addr);
  ......
JNI層的method_deviceFoundCallback函數對應java層的deviceFoundCallback方法,在JniCallbacks.java中。該類中又會調用RemoteDevice.java中的deviceFoundCallback方法。
然後,該回調方法中會發出廣播,action為BluetoothDevice.ACTION_FOUND。這個廣播會在BluetoothEventManager.java中處理。該類中通過addHandler方法,將action的值與相關handler接口類綁定。
接下來其他方法的處理,基本上也是這個套路。

總結下掃描的流程:
1.BluetoothEnabler類中調用startScanning方法,繼而會調用LocalBluetoothAdapter,然後進入framework層,調用BluetoothAdapter中的startDiscovery方法,然後調用了AdapterService::startDiscovery(ps:在BluetoothAdapter類中,有mService和mMangerService對像,前一個代表AdapterService,後一個指BluetoothManagerService,比如enable BT的時候,就會調用BluetoothManagerService的方法,這個具體分析的時候要注意)。接著,會調用JNI層com_android_bluetooth_btservice_AdapterService.cpp中的startDiscoveryNative方法。
這個流程其實還是蠻清晰的,從上層應用執行到中間層再准備到協議棧external中去了。
下面就開始糾結了,各層跳來跳去:即external的分析 
startDiscoveryNative (JNI層)
---> sBluetoothInterface->start_discovery() (bluetooth.c中)
---> btif_dm_start_discovery方法 (btif_dm.c)
---> BTA_DmSearch(&inq_params, services, bte_search_devices_evt);
---> bte_search_devices_evt
---> btif_dm_search_devices_evt
---> HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb,
                                 status, &bdaddr, 1, properties);
---> remote_device_properties_callback (JNI層)
--->callbackEnv->CallVoidMethod(sJniCallbacksObj, method_deviceFoundCallback, addr, types, props);
--> deviceFoundCallback (packages/apps/Bluetooth..JniCallbacks.java)
--> deviceFoundCallback (packages/apps/Bluetooth..RemoteDevices.java)
--->在RemoteDevices.java中會發出廣播,action为BluetoothDevice.ACTION_FOUND。
--->廣播接收者(packages/apps/Settings/..../BluetoothEventManager.java)
在其初始化方法中,為每個action綁定了一個名為XXHander的接口類,即以鍵值對形式保存。在廣播的onReceive方法中,調用相應接口類處理。
--->調用dispatchDeviceAdded方法 (還是在BluetoothEventManager.java中) ps:在這個方法中,會調用之前注冊的回調類(這個回調類是DeviceListPreferenceFragment.java)的onDeviceAdded方法。 ---> DeviceListPreferenceFragment.java::onDeviceAdded(還是在Settings模塊中) ---> DeviceListPreferenceFragment.java::createDevicePreference方法

2014年12月16日 星期二

android 藍牙源碼分析 (轉

轉自 http://www.cnblogs.com/chenbin7/archive/2012/07/26/2608135.html

BluetoothService類中定義的Native方法都在android_server_BluetoothServer.cpp裡建立jni調用

一,開啟(BT開啟關閉)(藍牙的打開關閉由類BluetoothEnabler控制。)
1.由BluetoothEnabler控制界面操作,在其構造函數裡會先調用LocalBluetoothManager.getInstance(上下文)。
2.然後在LocalBluetoothManager類的getInstance函數裡會調用當前類下的init()函數,該init()函數中通過BluetoothAdapter.getDefaultAdapter()獲得藍牙設備的句柄,如果當前沒有藍牙設備則返回null。
3.初始化完畢會監聽checkbox的狀態,當觸發點擊checkbox會響應onPreferenceChange方法,其中將調用LocalBluetoothManager.setBluetoothEnabled(啟用)方法。
而LocalBluetoothManager.setBluetoothEnabled(enable)方法,會調用mAdapter.enable()方法,enable()方法又會調用BluetoothService.enable()方法。其中,
(1)打開(關閉)操作成功後會有一個異步事件ACTION_STATE_CHANGED返回,異步事件由類BluetoothEventRedirector控制(接收廣播,進行處理)。在收到ACTION_STATE_CHANGED異步事件後,還需要做update本地設備profile的事情,讀取上次關閉前搜索到的藍牙設備。
(1.1)更新本地設備配置文件的事情:
(1.2)讀取上次關閉前搜索到的藍牙設備:
通過LocalBluetoothManager.setBluetoothStateInt(INT狀態)方法調到CachedBluetoothDeviceManager.onBluetoothStateChanged方法來讀取上次關閉之前搜索到device.
(2)來開啟EnableThread線程,進行打開操作,藍牙的打開關閉屬於異步操作。
ps:在啟動藍牙的時候,要注意的地方是不能正常啟動藍牙的情況,因為正常啟動的時候會返回BluetoothIntent.ENABLED_ACTION這個Intent,當時當啟動出現異常的時候是沒有Intent返回的,android使用回調函數來解決這個問題。下面是在bluetoothdeviceservice.java裡面能((IBluetoothDeviceCallback回調)的過程:(以下代碼屬於較低版本的android源碼,與較高版本源碼中已有所不同,只作為參考...)
复制代码
  1 public synchronized boolean enable(IBluetoothDeviceCallback callback) {
  2         checkPermissionBluetoothAdmin();
  3         Log.d(TAG,"start enable! ");
  4         // Airplane mode can prevent Bluetooth radio from being turned on.
  5         if (mIsAirplaneSensitive && isAirplaneModeOn()) {
  6             return false;
  7         }
  8         if (mIsEnabled) {
  9             return false;
 10         }
 11         if (mEnableThread != null && mEnableThread.isAlive()) {
 12             return false;
 13         }
 14    //   主要的启动过程是放在一个新起的线程里面,但是不管能不能启动 
 15    //    仍然返回了true
 16         mEnableThread = new EnableThread(callback);
 17         mEnableThread.start();
 18       //   
 19         return true;
 20   
 21         }
 22    
 23     private EnableThread mEnableThread;
 24     private class EnableThread extends Thread {
 25         private final IBluetoothDeviceCallback mEnableCallback;
 26         public EnableThread(IBluetoothDeviceCallback callback) {
 27             mEnableCallback = callback;
 28         }
 29         public void run() {
 30             boolean res = enableNative();
 31             if (res) {
 32                 mEventLoop.start();
 33             }
 34 
 35             if (mEnableCallback != null) {
 36                 try {
 37                  
 38                     // 通过回调函数来表明是否正常启动蓝牙设备
 39                     mEnableCallback.onEnableResult(res ?
 40                                                    BluetoothDevice.RESULT_SUCCESS :
 41                                                    BluetoothDevice.RESULT_FAILURE);
 42                 } catch (RemoteException e) {}
 43             }
 44 
 45             if (res) {
 46                 mIsEnabled = true;
 47                 mIsDiscovering = false;
 48 
 49                 Intent intent = new Intent(BluetoothIntent.ENABLED_ACTION);
 50                 mContext.sendBroadcast(intent);
 51                 }
 52             }else{
 53                 mIsEnabled = false;
 54                 mIsDiscovering = false;
 55             }
 56             mEnableThread = null;
 57         }
 58 }
 59 
 60 
 61 
 62 
 63 
 64     
 65 
 66 //  这个回调函数将被作为参数传进bluetoothservice 里面的enable(IBluetoothDeviceCallback callback)
 67 static class DeviceCallback extends IBluetoothDeviceCallback.Stub {
 68         Handler messageHandler;
 69 
 70         public void setHandler(Handler handler) {
 71             synchronized (this) {
 72                 messageHandler = handler;
 73             }
 74    
 75    
 76         public void onEnableResult(int result) {
 77             switch(result) {
 78 
 79   //  启动不成功的时候执行
 80                 case BluetoothDevice.RESULT_FAILURE:
 81                      messageHandler.sendMessage(messageHandler.obtainMessage(EVENT_FAILED_BT_ENABLE,0));
 82                     break;
 83             }
 84         }
 85        
 86 
 87 //   配对完成时执行
 88 public void onCreateBondingResult(String address, int result) {
 89             synchronized (this) {
 90                 if (messageHandler != null) {
 91                     if (result == BluetoothDevice.RESULT_FAILURE) {
 92                         messageHandler.sendMessage(messageHandler.obtainMessage(
 93                                 HANDLE_PAIRING_FAILED, address));
 94                     } else {
 95                         messageHandler.sendMessage(messageHandler.obtainMessage(
 96                                 HANDLE_PAIRING_PASSED, address));
 97                     }
 98                 }
 99             }
100         }
101 
102     }
复制代码


涉及到的類: 

BluetoothService(最主要的類,開啟具體命令的線程進行enable,disable等操作) 
LocalBluetoothManager(本機藍牙設備管理,開啟關閉,搜索等等,初始化BluetoothAdapter) 
BluetoothEnabler(界面的點擊和狀態文字的顯示) 
BluetoothAdapter(framework封裝的類,提供本地藍牙設備的配置,包括開啟藍牙,搜索周圍藍牙設備,設置本地藍牙可見性;建立LocalBluetoothManager和BluetoothService的映射關系,主要是通過它調用BluetoothService的函數)

BluetoothEventRedirector(接收Bluetooth API 的廣播和回調,並且將Settings中的UI線程上的事件分派到正確的類)



二、可檢測性(Discoverable)

1.藍牙的discoverable mode由類BluetoothDiscoverableEnabler控制。點擊將觸發OnPreferenceChangeListener監聽事件,調用onPreferenceChange()方法,該方法中調用setEnabled(true),而setEnabled(true)方法將調用到BluetoothAdapter的setScanMode () 方法。

藍牙模式有兩種模式SCAN_MODE_CONNECTABLE_DISCOVERABLE(可連接可發現)和SCAN_MODE_CONNECTABLE(可連接但不可發現)


涉及到的類: 
LocalBluetoothManager 
BluetoothDiscoverableEnabler 
BluetoothAdapter


三、掃描 
1.在BluetoothSetting裡觸發點擊,調用LocalBluetoothManager.startScanning(true)函數,通過BluetoothAdapter的startDiscovery調用到BluetoothService裡的startDiscovery來調用Native函數 startDiscoveryNative()。 
startDiscovery()是個異步函數,會立即返回,通過注冊 ACTION_DISCOVERY_STARTED、ACTION_DISCOVERY_FINISHED、ACTION_FOUND,來確定當前的狀態。 
當藍牙由disable變成enable時會調用掃描,當距離上次掃描超過5分鐘的前提下,退出頁面,再進到頁面的時候也會啟動掃描。 
在啟動scan的時候,還會判斷當前是否在播放音樂,如果在播放音樂,則不啟動掃描。 
點擊查找設備後,會把設備列表裡沒有配對的設備清除掉,保留配對狀態的設備。
掃描的過程是一個很耗費資源的過程,在掃描過程,不會去嘗試進行新的連接,掃描時間默認是12秒,它是以一個系統服務的形式存在的,可以調用cancelDiscovery()來取消掃描。 

四、連接 
1.1 在setting界面點擊連接,會調到CachedBluetoothDevice類的connect方法。
1.2 而connect方法會調用connectWithoutResettingTimer()方法。
1.3 而connectWithoutResettingTimer()方法會調用 connectInt方法。
在connectInt裡,根據不同的profile來獲得profilemanger,然後調用 profilemanger.connect()函數 。此處的鏈接會涉及到的profile有A2DP AVRCP DUN HSP HFP 等。
同理如果配對或者解除配對,也會調到CachedBluetoothDevice類的pair()方法和unpair()。
以A2DP為例,在connectInt裡,根據不同的profile來獲得profilemanger,然後調用 profilemanger.connect()函數,在這個函數裡調用了BluetoothA2dpService的connectSink()函數,最後調到Native方法
connectSinkNative()去建立連接。 
涉及到的一些類: 
CachedBluetoothDevice(搜索到的設備) 
BluetoothDevice(設備類) 
LocalBluetoothProfileManager(是一個抽像類,各種ProfileManger,實例化各種Profile的service) 
SettingsBtStatus(藍牙的狀態類) 
BluetoothA2dp(為LocalBluetoothProfileManager和BluetoothA2dpService建立映射關系) 
BluetoothA2dpService(最終的服務類,由它調用連接、斷開等Native函數,和底層通信)

 其他文件作用(接收與發送類似)
1.BluetoothOppReceiver.java 這個類裡描述的是藍牙傳輸文件過程中接收到的廣播事件。
2.BluetoothOppTransfer.java 管理文件傳輸的類
3. BluetoothOppService.java 藍牙傳輸文件後台的類
4. BluetoothOppObexClientSession.java 具體實現文件傳輸的類
  
通過源碼分析藍牙執行過程:(Bluetooth--->BT) 1、開啟 步驟1:首先從BTSettings開始,執行onCreate方法。因為是初始化狀態,所以if(action.equal(BTDevicePicker.ACTION_LAUNCH))不滿足,故執行else語句。 步驟2:初始化mEnable對像,調用BTEnable構造函數。通過LocalBTManager.getInstance調用init方法,再通過init方法調用BTAdapter.getDefaultAdapter()獲得適配器句柄。 步驟3:各種初始化完畢後,執行BTSettings中的onResume方法,調用BTEnabler.resume方法,該resume方法為組合框設置監聽事件。 步驟4:當藍牙開啟時,該組合框被選中,將響應監聽事件,執行BTEnabler.onPreferenceChange方法。該方法中會調用LocalBTManager.setBTEnabled方法。而setBTEnabled方法會調用BTAdapter.enable()方法,繼而調用BTService.enable()方法,繼而調用BTService.enable(true)方法。在該方法中, (1)當enable(true)方法返回true時,在setBTEnabled方法中會調用BTService中的setBTStateInt方法,繼而廣播出去,由BTEventRedirector類接收。 (2)開啟新的線程,主要的啟動過程是放在這個新啟動的線程裡面。 (3)開啟藍牙後,會調用CachedBTDeviceManager.onBTStateChanged方法來讀取上次關閉前搜索到的藍牙設備。 2.可檢測的 點擊“可檢測性”組合框,將觸發BTDiscoverableEnabler.onPreferenceChange方法,然後調用同個類中的setEnabled方法,來調用BTAdapter.setScanMode方法(其中傳遞SCAN_MODE_CONNECTABLE_DISCOVERABLE參數),繼而會調用BTService.setScanMode方法,在該方法中,會通過setDiscoverableTimeout方法設置檢測時間。 3.掃描 BTSettings的onResume方法繼續往下運行,將調用LocalBTManager.startScanning方法,該方法會調用BTAdapter.startDiscovery方法,繼而調用BTService.startDiscovery方法,再調用startDIscoveryNative方法。 4.連接 步驟1:在setting界面點擊連接,會調到CachedBluetoothDevice類的connect方法。 步驟2:而connect方法會調用connectWithoutResettingTimer()方法。 步驟3:而connectWithoutResettingTimer()方法會調用 connectInt方法。 步驟4:在connectInt裡,根據不同的profile來獲得profilemanger,然後調用 profilemanger.connect()函數 。此處的鏈接會涉及到的profile有A2DP AVRCP DUN HSP HFP 等。 同理如果配對或者解除配對,也會調到CachedBluetoothDevice類的pair()方法和unpair()。

2014年10月25日 星期六

求一個整數的二進制中1的個數(轉)

(此為轉貼連結網址在下方)
題目:輸入一個整數,求該整數的二進製表達中有多少個1。例如輸入10,由於其二進製表示為1010,有兩個1,因此輸出2。

分析:這是一道很基本的考查位運算的面試題。包括微軟在內的很多公司都曾採用過這道題。

一個很基本的想法是,我們先判斷整數的最右邊一位是不是1。接著把整數右移一位,原來處於右邊第二位的數字現在被移到第一位了,再判斷是不是1。這樣每次移動一位,直到這個整數變成0為止。現在的問題變成怎樣判斷一個整數的最右邊一位是不是1了。很簡單,如果它和整數1作與運算。由於1除了最右邊一位以外,其他所有位都為0。因此如果與運算的結果為1,表示整數的最右邊一位是1,否則是0。

得到的代碼如下:

////////////////////////////////////////////////// /////////////////////
// Get how many 1s in an integer's binary expression
////////////////////////////////////////////////// /////////////////////
int NumberOf1_Solution1(int i)
{
      int count = 0;
      while(i)
      {
            if(i & 1)
                  count ++;

            i = i >> 1;
      }

      return count;
}

可能有讀者會問,整數右移一位在數學上是和除以2是等價的。那可不可以把上面的代碼中的右移運算符換成除以2呢?答案是最好不要換成除法。因為除法的效率比移位運算要低的多,在實際編程中如果可以應盡可能地用移位運算符代替乘除法。

這個思路當輸入i是正數時沒有問題,但當輸入的i是一個負數時,不但不能得到正確的1的個數,還將導致死循環。以負數0x80000000為例,右移一位的時候,並不是簡單地把最高位的1移到第二位變成0x40000000,而是0xC0000000。這是因為移位前是個負數,仍然要保證移位後是個負數,因此移位後的最高位會設為1。如果一直做右移運算,最終這個數字就會變成0xFFFFFFFF而陷入死循環。

為了避免死循環,我們可以不右移輸入的數字i。首先i和1做與運算,判斷i的最低位是不是為1。接著把1左移一位得到2,再和i做與運算,就能判斷i的次高位是不是1……這樣反复左移,每次都能判斷i的其中一位是不是1。基於此,我們得到如下代碼:

////////////////////////////////////////////////// /////////////////////
// Get how many 1s in an integer's binary expression
////////////////////////////////////////////////// /////////////////////
int NumberOf1_Solution2(int i)
{
      int count = 0;
      unsigned int flag = 1;
      while(flag)
      {
            if(i & flag)
                  count ++;

            flag = flag << 1;
      }

      return count;
}

另外一種思路是如果一個整數不為0,那麼這個整數至少有一位是1。如果我們把這個整數減去1,那麼原來處在整數最右邊的1就會變成0,原來在1後面的所有的0都會變成1。其餘的所有位將不受到影響。舉個例子:一個二進制數1100,從右邊數起的第三位是處於最右邊的一個1。減去1後,第三位變成0,它後面的兩位0變成1,而前面的1保持不變,因此得到結果是1011。

我們發現減1的結果是把從最右邊一個1開始的所有位都取反了。這個時候如果我們再把原來的整數和減去1之後的結果做與運算,從原來整數最右邊一個1那一位開始所有位都會變成0。如1100&1011=1000。也就是說,把一個整數減去1,再和原整數做與運算,會把該整數最右邊一個1變成0。那麼一個整數的二進制有多少個1,就可以進行多少次這樣的操作。

這種思路對應的代碼如下:

////////////////////////////////////////////////// /////////////////////
// Get how many 1s in an integer's binary expression
////////////////////////////////////////////////// /////////////////////
int NumberOf1_Solution3(int i)
{
      int count = 0;

      while (i)
      {
            ++ count;
            i = (i - 1) & i;
      }

      return count;
}

擴展:如何用一個語句判斷一個整數是不是二的整數次冪?

PS:n&(n-1)==0;//二進制數只有一位位1,則該數是2的整數次冪.





簡單查表,相對來說效率也不錯。

int countBits(int value){
      int count=0;
      int bits4[]={0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
      while(value!=0){
            count+=bits4[value&0xf];
      value>>=4;
      }
      return count;
}





================================================== ====



這是一道《編程之美-微軟技術面試心得》中的題目,問題描述如下:

對於一個字節(8bit)的變量,求其二進製表示中“1”的個數,要求算法的執行效率盡可能地高。

《編程之美》中給出了五種解法,但是實際上從Wikipedia 上我們可以找到更優的算法。

這道題的本質相當於求二進制數的Hamming 權重,或者說是該二進制數與0 的Hamming 距離,這兩個概念在信息論和編碼理論中是相當有名的。在二進制的情況下,它們也經常被叫做population count 或者popcount 問題,比如gcc 中就提供了一個內建函數:

int __builtin_popcount (unsigned int x)

輸出整型數二進制中 1 的個數。但是GCC 的__builtin_popcount 的實現主要是基於查表法做的,跟編程之美中解法5 是一樣的。 Wikipedia 上的解法是基於分治法來做的,構造非常巧妙,通過有限次簡單地算術運算就能求得結果,特別適合那些受存儲空間限制的算法中使用:

/* ================================================ ===========================
* Problem:
* The fastest way to count how many 1s in a 32-bits integer.
*
* Algorithm:
* The problem equals to calculate the Hamming weight of a 32-bits integer,
* or the Hamming distance between a 32-bits integer and 0. In binary cases,
* it is also called the population count, or popcount.[1]
*
* The best solution known are based on adding counts in a tree pattern
* (divide and conquer). Due to space limit, here is an example for a
* 8-bits binary number A=01101100:[1]
* | Expression | Binary | Decimal | Comment |
* | A | 01101100 | | the original number |
* | B = A & 01010101 | 01000100 | 1,0,1,0 | every other bit from A |
* | C = (A>>1) & 01010101 | 00010100 | 0,1,1,0 | remaining bits from A |
* | D = B + C | 01011000 | 1,1,2,0 | # of 1s in each 2-bit of A |
* | E = D & 00110011 | 00010000 | 1,0 | every other count from D |
* | F = (D>>2) & 00110011 | 00010010 | 1,2 | remaining counts from D |
* | G = E + F | 00100010 | 2,2 | # of 1s in each 4-bit of A |
* | H = G & 00001111 | 00000010 | 2 | every other count from G |
* | I = (G>>4) & 00001111 | 00000010 | 2 | remaining counts from G |
* | J = H + I | 00000100 | 4 | No. of 1s in A |
* Hence A have 4 1s.
*
* [1] http://en.wikipedia.org/wiki/Hamming_weight
*
* 這個算法的設計思想用的是二分法,兩兩一組相加,之後四個四個一組相加,接著八個八個,最後就得到各位之和了。

* 設原整數值為x,
* 第一步:把x的32個bit分成16組(第32bit和第31bit一組,第30bit和第29bit一組……以此類推),然後將每一組的兩bit上的值(因為是二進制數,所以要么是0要么是1)相加並把結果還放在這兩bit的位置上,這樣,得到結果整數x1,x1的二進制(32bit)可以分為16組,每一組的數值就是原來整數x在那兩bit上1的個數。
* 第二步:把第一步得到的結果x1的32bit,分成8組(第32、31、30、29bit一組,第28、27、26、25bit一組……以此類推),然後每一組的四bit上的值相加並把結果還放在這四bit的位置上,這樣,又得到結果整數x2,x2的二進制可以分為8組,每一組的數值就是原來整數x在那四bit上的1的個數。
* ……
* 這樣一直分組計算下去,最終,把兩個16bit上1的個數相加,得到原來整數x的32bit上1的個數。

================================================== =========================
*/
#include <stdio.h>

typedef unsigned int UINT32;
const UINT32 m1 = 0x55555555; // 01010101010101010101010101010101
const UINT32 m2 = 0x33333333; // 00110011001100110011001100110011
const UINT32 m4 = 0x0f0f0f0f; // 00001111000011110000111100001111
const UINT32 m8 = 0x00ff00ff; // 00000000111111110000000011111111
const UINT32 m16 = 0x0000ffff; // 00000000000000001111111111111111
const UINT32 h01 = 0x01010101; // the sum of 256 to the power of 0, 1, 2, 3

/* This is a naive implementation, shown for comparison, and to help in
* understanding the better functions. It uses 20 arithmetic operations
* (shift, add, and). */
int popcount_1(UINT32 x)
{
  x = (x & m1) + ((x >> 1) & m1);
  x = (x & m2) + ((x >> 2) & m2);
  x = (x & m4) + ((x >> 4) & m4);
  x = (x & m8) + ((x >> 8) & m8);
  x = (x & m16) + ((x >> 16) & m16);
  return x;
}

/* This uses fewer arithmetic operations than any other known implementation
* on machines with slow multiplication. It uses 15 arithmetic operations. */
int popcount_2(UINT32 x)
{
  x -= (x >> 1) & m1; //put count of each 2 bits into those 2 bits
  x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits
  x = (x + (x >> 4)) & m4; //put count of each 8 bits into those 8 bits
  x += x >> 8; //put count of each 16 bits into their lowest 8 bits
  x += x >> 16; //put count of each 32 bits into their lowest 8 bits
  return x & 0x1f;
}

/* This uses fewer arithmetic operations than any other known implementation
* on machines with fast multiplication. It uses 12 arithmetic operations,
* one of which is a multiply. */
int popcount_3(UINT32 x)
{
  x -= (x >> 1) & m1; //put count of each 2 bits into those 2 bits
  x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits
  x = (x + (x >> 4)) & m4; //put count of each 8 bits into those 8 bits
  return (x * h01) >> 24; // left 8 bits of x + (x<<8) + (x<<16) + (x<<24)
}

int main()
{
  int i = 0x1ff12ee2;
  printf("i = %d = 0x%x/n", i, i);
  printf("popcount_1(%d) = %d/n", i, popcount_1(i));
  printf("popcount_2(%d) = %d/n", i, popcount_2(i));
  printf("popcount_3(%d) = %d/n", i, popcount_3(i));
  /* If compiled with other compiler than gcc, comment the line bellow. */
  printf("GCC's __builtin_popcount(%d) = %d/n", i, __builtin_popcount(i));
  return 0;
}

以上內容來源於http://blog.solrex.cn/articles/population-count-problem.html


================================================== =========



HAKMEM算法:

int Count(unsigned x)
{
    unsigned n;

    n = (x >> 1) & 033333333333;
    x = x - n;
    n = (n >> 1) & 033333333333;
    x = x - n;
    x = (x + (x >> 3)) & 030707070707;
    x = modu(x, 63);
    return x;
}

說明:首先是將二進制各位三個一組,求出每組中1的個數,然後相鄰兩組歸併,得到六個一組的1的個數,最後很巧妙的用除63取餘得到了結果。
因為2^6 = 64,也就是說x_0 + x_1 * 64 + x_2 * 64 * 64 = x_0 + x_1 + x_2 (mod 63),這裡的等號表示同餘。
這個程序只需要十條左右指令,而且不訪存,速度很快。

本文來自CSDN博客:http://blog.csdn.net/chinazjf/archive/2008/04/15/2294840.aspx

寫一個前置處理器的巨集,可交換兩個整數(如果你是屬於駭客級,就不要透過宣告在巨集外部的暫時變數)

#define swap(x,y) {x=x^y;y=x^y;x=x^y;}  //a,b數值交換

x=x^y
//表示將 x xor y 之後的值存至x  又因為 xor有可逆性所以可以看做 x在這等式之後成為x與y的綜合體
y=x^y
//因為可逆性,所以將這個綜合體x與y結合,會還原成原本的x,此時將結果存為y
x=x^y
//此時的y內存的結果已經為一開始的x了,所以x^y的結果為  x與y的綜合體在與x做運算,得到一開始的y,存為x。
swap結束

C++風格與藝術 CH10 前置處理器

#define name Substitue_text
name 為任意變數
Substitue_text 可以為任意內容,包含空白 括號等皆可

e.g.
#define FOR_ALL for (i=0;i<array_size;++i)

定義常數上const 較 define為佳
1. const 為C++語法 define不是
2. C++會立即檢查const的語法是否有錯,但define會在巨集呼叫才檢測
3. const 適用c++的有效範圍規定,但define一律是全域宣告

define在條件編譯和其他特定應用上較有優勢




2014年10月16日 星期四

20141017 C++閱讀紀錄 字元字串(寬字元寬字串)

字元使用 char
寬字元使用 wchar_t
e.g.
char simple; //普通的字元
wchar_t wide;  // 寬字元
simple = ''X';
wide = L'Ω';

//特殊狀況
char simple = 'ab';
std::cout << simple ;
則會產生overflow 但程式能可正常執行,且印出結果為 b;

使用字串方法
#include <string>
std::string name; //宣告字串 name
寬字串比照上面

C的字串與C轉C++ 請直接參考C++風格與藝術 第五章 說明

C++字串與C字串差異
C++字串較易使用,並已設計能防止眾多問題發生。
e.g. 字串長度限制 c++可自動沒有長度限制。
C的字串處理速度較C++快,因為string類別需要額外成本
但是幾乎所有程式在這個速度上的差距是可以忽略不記的。

int num = 0123;
std::cout << num ;
輸出為 83
因為會被誤以為是8進位