日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

Android4.0蓝牙使能的详细解析

發(fā)布時(shí)間:2023/12/19 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android4.0蓝牙使能的详细解析 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

毫無(wú)疑問(wèn),bluetooth的打開(kāi)是在Settings中進(jìn)行的操作。因此,冤有頭,債有主,我們來(lái)到了Settings.java中,果然發(fā)現(xiàn)了相關(guān)的代碼如下:

mBluetoothEnabler =new BluetoothEnabler(context, new Switch(context));

于是,我們得以進(jìn)入真正的藍(lán)牙操作的殿堂,好好進(jìn)去看看吧。

1、BluetoothEnabler的構(gòu)造函數(shù)public BluetoothEnabler(Context context,Switch switch_) {mContext = context;mSwitch = switch_;//很簡(jiǎn)單了,去調(diào)用一個(gè)LocalBluetoothManager類的getInstance,其實(shí)會(huì)構(gòu)造該類的 LocalBluetoothManager manager =LocalBluetoothManager.getInstance(context);if (manager == null) {// Bluetooth is not supported mLocalAdapter = null;mSwitch.setEnabled(false);} else {//構(gòu)造成功后,通過(guò)manager得到bluetooth的adapter mLocalAdapter =manager.getBluetoothAdapter();}//同時(shí)新建一個(gè)intent,用于接收ACTION_STATE_CHANGED mIntentFilter = newIntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);}2、LocalBluetoothManager類的getInstancepublic static synchronizedLocalBluetoothManager getInstance(Context context) {if (sInstance == null) {//2.1同樣的,這個(gè)會(huì)去調(diào)用LocalBluetoothAdapter的getInstance,也會(huì)構(gòu)造該類 LocalBluetoothAdapter adapter =LocalBluetoothAdapter.getInstance();if (adapter == null) {return null;}// This will be around as long asthis process is Context appContext =context.getApplicationContext();//2.2構(gòu)造LocalBluetoothManager類 sInstance = newLocalBluetoothManager(adapter, appContext);}return sInstance;}2.1LocalBluetoothAdapter的getInstancestatic synchronized LocalBluetoothAdaptergetInstance() {if (sInstance == null) {//2.1.1通過(guò)BluetoothAdapter得到DefaultAdapter BluetoothAdapter adapter =BluetoothAdapter.getDefaultAdapter();if (adapter != null) {//2.1.2若有該DefaultAdapter,則構(gòu)造LocalBluetoothAdapter sInstance = newLocalBluetoothAdapter(adapter);}}return sInstance;}2.1.1BluetoothAdapter得到DefaultAdapterpublic static synchronized BluetoothAdaptergetDefaultAdapter() {if (sAdapter == null) {IBinder b =ServiceManager.getService(BluetoothAdapter.BLUETOOTH_SERVICE);if (b != null) {IBluetooth service =IBluetooth.Stub.asInterface(b);sAdapter = newBluetoothAdapter(service);}}return sAdapter;}2.1.2構(gòu)造LocalBluetoothAdapter//其實(shí)就是 mAdapter的初始化而已 privateLocalBluetoothAdapter(BluetoothAdapter adapter) {mAdapter = adapter;}2.2構(gòu)造LocalBluetoothManager類//管理本地藍(lán)牙類,用來(lái)在藍(lán)牙API子類上面再封裝一個(gè)接口 privateLocalBluetoothManager(LocalBluetoothAdapter adapter, Context context) {mContext = context;//mLocalAdapter初始化為DefaultAdapter中得到的值 mLocalAdapter= adapter;//構(gòu)造CachedBluetoothDeviceManager,用來(lái)管理遠(yuǎn)程藍(lán)牙設(shè)備 mCachedDeviceManager = newCachedBluetoothDeviceManager(context);//2.2.1構(gòu)建BluetoothEventManager,該類是用來(lái)管理廣播消息和回調(diào)函數(shù)的,即分發(fā)不同的消息去對(duì)UI進(jìn)行處理 mEventManager = newBluetoothEventManager(mLocalAdapter,mCachedDeviceManager, context);//2.2.2該類提供對(duì)不同LocalBluetoothProfile object的訪問(wèn) mProfileManager = newLocalBluetoothProfileManager(context,mLocalAdapter,mCachedDeviceManager, mEventManager);}2.2.1構(gòu)建BluetoothEventManagerBluetoothEventManager(LocalBluetoothAdapteradapter,CachedBluetoothDeviceManagerdeviceManager, Context context) {mLocalAdapter = adapter;mDeviceManager = deviceManager;//創(chuàng)建兩個(gè)IntentFilter mAdapterIntentFilter = newIntentFilter();//這里沒(méi)有對(duì)mProfileIntentFilter進(jìn)行初始化,這個(gè)在LocalBluetoothProfileManager的addProfile中實(shí)現(xiàn) mProfileIntentFilter = newIntentFilter();//創(chuàng)建一個(gè)Handler的Hash表 mHandlerMap = new HashMap<String,Handler>();mContext = context;//注冊(cè)對(duì)adapter和Device的幾個(gè)廣播消息的處理回調(diào)函數(shù)//add action到mAdapterIntentFilter// Bluetooth on/off broadcasts addHandler(BluetoothAdapter.ACTION_STATE_CHANGED, newAdapterStateChangedHandler());// Discovery broadcasts addHandler(BluetoothAdapter.ACTION_DISCOVERY_STARTED, newScanningStateChangedHandler(true));addHandler(BluetoothAdapter.ACTION_DISCOVERY_FINISHED, newScanningStateChangedHandler(false));addHandler(BluetoothDevice.ACTION_FOUND, new DeviceFoundHandler());addHandler(BluetoothDevice.ACTION_DISAPPEARED, newDeviceDisappearedHandler());addHandler(BluetoothDevice.ACTION_NAME_CHANGED, newNameChangedHandler());// Pairing broadcasts addHandler(BluetoothDevice.ACTION_BOND_STATE_CHANGED, newBondStateChangedHandler());addHandler(BluetoothDevice.ACTION_PAIRING_CANCEL, newPairingCancelHandler());// Fine-grained state broadcasts addHandler(BluetoothDevice.ACTION_CLASS_CHANGED, newClassChangedHandler());addHandler(BluetoothDevice.ACTION_UUID,new UuidChangedHandler());// Dock event broadcasts addHandler(Intent.ACTION_DOCK_EVENT,new DockEventHandler());//mAdapterIntentFilter的接收處理函數(shù) mContext.registerReceiver(mBroadcastReceiver, mAdapterIntentFilter);}2.2.2構(gòu)造LocalBluetoothProfileManager類LocalBluetoothProfileManager(Contextcontext,LocalBluetoothAdapter adapter,CachedBluetoothDeviceManagerdeviceManager,BluetoothEventManager eventManager){mContext = context;//各個(gè)類之間進(jìn)行關(guān)聯(lián) mLocalAdapter = adapter;mDeviceManager = deviceManager;mEventManager = eventManager;// pass this reference to adapter andevent manager (circular dependency) mLocalAdapter.setProfileManager(this);mEventManager.setProfileManager(this);ParcelUuid[] uuids =adapter.getUuids();// uuids may be null if Bluetooth isturned offif (uuids != null) {//假如已經(jīng)有了uuid,根據(jù)uuid來(lái)add并new對(duì)應(yīng)的profile,只針對(duì)A2DP,HFP,HSP,OPP四個(gè)profile,HID和PAN在下面,每次都add updateLocalProfiles(uuids);}// Always add HID and PAN profiles//加入HID和PAN兩個(gè)profile mHidProfile = new HidProfile(context,mLocalAdapter);addProfile(mHidProfile,HidProfile.NAME,BluetoothInputDevice.ACTION_CONNECTION_STATE_CHANGED);mPanProfile = new PanProfile(context);addPanProfile(mPanProfile,PanProfile.NAME,BluetoothPan.ACTION_CONNECTION_STATE_CHANGED);Log.d(TAG,"LocalBluetoothProfileManager construction complete");}好吧,其實(shí)我們被騙了,剛剛只是一個(gè)路引,不是真正的操作,真正的操作向來(lái)都是從你滑動(dòng)界面那個(gè)on/off鍵開(kāi)始的,因此我們決定把這個(gè)鍵的處理給揪出來(lái)。在Settings界面上一共就只有兩個(gè)on/off鍵,一個(gè)是wifi,另一個(gè)就是藍(lán)牙了,我們從這個(gè)代碼入手:case HEADER_TYPE_SWITCH://其實(shí)寫這個(gè)代碼的人也比較心虛,假如switch多一點(diǎn),下面就要重寫了// Would need a differenttreatment if the main menu had more switchesif (header.id ==R.id.wifi_settings) {mWifiEnabler.setSwitch(holder.switch_);} else {//這個(gè)就是處理了,上面的路引沒(méi)有白做啊 mBluetoothEnabler.setSwitch(holder.switch_);}3、mBluetoothEnabler.setSwitch分析public void setSwitch(Switch switch_) {//若是和上次相同,則不做任何事情,可以理解,代碼也懶嘛if (mSwitch == switch_) return;//把上次的switch的changelistener清空 mSwitch.setOnCheckedChangeListener(null);mSwitch = switch_;//重設(shè)這次的switch的changelistener mSwitch.setOnCheckedChangeListener(this);int bluetoothState =BluetoothAdapter.STATE_OFF;//獲取getBluetoothState,這個(gè)過(guò)程也會(huì)同步一下state,防止改變if (mLocalAdapter != null)bluetoothState = mLocalAdapter.getBluetoothState();//根據(jù)狀態(tài)設(shè)置一下兩個(gè)標(biāo)志位boolean isOn = bluetoothState ==BluetoothAdapter.STATE_ON;boolean isOff = bluetoothState ==BluetoothAdapter.STATE_OFF;//設(shè)置checked的狀態(tài)位。注意,假如這里狀態(tài)發(fā)生了改變,則會(huì)調(diào)用this.onCheckedChanged來(lái)進(jìn)行處理 mSwitch.setChecked(isOn);if(WirelessSettings.isRadioAllowed(mContext, Settings.System.RADIO_BLUETOOTH)) {//有bluetooth或者不是airplane,則該switch不變灰,否則,灰的。 mSwitch.setEnabled(isOn || isOff);} else {mSwitch.setEnabled(false);}}4、onCheckedChanged在switch狀態(tài)發(fā)生改變后,會(huì)調(diào)用這個(gè)地方的回調(diào)函數(shù)進(jìn)行處理。public void onCheckedChanged(CompoundButtonbuttonView, boolean isChecked) {// Show toast message if Bluetooth isnot allowed in airplane mode//若是打開(kāi)的話,就需要檢查一下是否allow Bluetooth(radio,airplane的check)if (isChecked &&!WirelessSettings.isRadioAllowed(mContext,Settings.System.RADIO_BLUETOOTH)) {Toast.makeText(mContext,R.string.wifi_in_airplane_mode, Toast.LENGTH_SHORT).show();// Reset switch to off//若是不對(duì)的話,reset為off buttonView.setChecked(false);}if (mLocalAdapter != null) {//4.1設(shè)置scanmode,放心,它會(huì)判斷state的,不是STATE_ON,會(huì)直接返回false的 mLocalAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE);//4.2使能或不使能Bluetooth了 mLocalAdapter.setBluetoothEnabled(isChecked);}//過(guò)程中還是會(huì)反灰,直到setBluetoothEnabled的結(jié)果返回會(huì)改變switch的狀態(tài) mSwitch.setEnabled(false);}4.1設(shè)置scanmod會(huì)調(diào)用adapter中的setScanMode,直接去看就可以了,事實(shí)上就是設(shè)置了兩個(gè)property標(biāo)志,沒(méi)什么public boolean setScanMode(int mode) {//這里把這個(gè)代碼寫出來(lái)就是證明一下,STATE_ON才會(huì)真正做下去,否則免談if (getState() != STATE_ON) returnfalse;//這里會(huì)調(diào)用對(duì)應(yīng)server中的setScanModereturn setScanMode(mode, 120);}public synchronized boolean setScanMode(intmode, int duration) {//這里有個(gè)permission,好像和2.3中不一樣,注意一下 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,"NeedWRITE_SECURE_SETTINGS permission");boolean pairable;boolean discoverable;switch (mode) {case BluetoothAdapter.SCAN_MODE_NONE:pairable = false;discoverable = false;break;caseBluetoothAdapter.SCAN_MODE_CONNECTABLE://開(kāi)始就是這里了,可pairable,但是不可discoverable pairable = true;discoverable = false;break;caseBluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:pairable = true;discoverable = true;if (DBG) Log.d(TAG, "BTDiscoverable for " + duration + " seconds");break;default:Log.w(TAG, "Requested invalidscan mode " + mode);return false;}//設(shè)置這兩個(gè)property標(biāo)志 setPropertyBoolean("Discoverable", discoverable);setPropertyBoolean("Pairable", pairable);return true;}4.2setBluetoothEnabled分析public void setBluetoothEnabled(booleanenabled) {//根據(jù)enabled的標(biāo)志設(shè)置是enable還是disable,在2.3中,這個(gè)地方就是bt_enable哦,這里還不知道,我們?cè)诘?步進(jìn)行詳細(xì)的分析boolean success = enabled? mAdapter.enable(): mAdapter.disable();//成功了,設(shè)置對(duì)應(yīng)的狀態(tài)位if (success) {setBluetoothStateInt(enabled?BluetoothAdapter.STATE_TURNING_ON:BluetoothAdapter.STATE_TURNING_OFF);} else {if (Utils.V) {Log.v(TAG,"setBluetoothEnabled call, manager didn't return " +"success forenabled: " + enabled);}//同步一下設(shè)置的狀態(tài) syncBluetoothState();}}}5、mAdapter.enable或者mAdapter.disable就先分析enable吧,它會(huì)調(diào)用對(duì)應(yīng)server端的enable(ture),我們來(lái)看看源碼public synchronized boolean enable(booleansaveSetting) {mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,"Need BLUETOOTH_ADMIN permission");// Airplane mode can prevent Bluetoothradio from being turned on.//檢查是否是飛行模式if (mIsAirplaneSensitive &&isAirplaneModeOn() && !mIsAirplaneToggleable) {return false;}//5.1注意與2.3的不同,在2.3中,這里會(huì)調(diào)用enablethread去調(diào)用native的bt_enable,而4.0沒(méi)有這么做。沒(méi)事,我們來(lái)分析4.0怎么做的。 mBluetoothState.sendMessage(BluetoothAdapterStateMachine.USER_TURN_ON,saveSetting);return true;}5.1mBluetoothState.sendMessage簡(jiǎn)單理解一下,mBluetoothState是BluetoothAdapterStateMachine類。因此,在分析的之前,簡(jiǎn)單說(shuō)一下,它其實(shí)就是類似一個(gè)狀態(tài)轉(zhuǎn)換圖,根據(jù)你所處于的狀態(tài),然后再判斷收到的操作,進(jìn)行不同的處理。根據(jù)構(gòu)造函數(shù)中的setInitialState(mPowerOff);可以知道初始狀態(tài)是PowerOff。但是從它給出的狀態(tài)機(jī)可以看出,在PowerOff的狀態(tài)時(shí),它是通過(guò)TURN_HOT/TURN_ON來(lái)改變到HotOff狀態(tài)的,然后才會(huì)收到USER_TURN_ON,去該變到BluetootOn的狀態(tài)。因此,可以肯定的是我們這里的USER_TURN_ON不是它收到的第一個(gè)message,因此我們?nèi)ゼm結(jié)一下它是從哪里開(kāi)始改變PowerOff的狀態(tài):extra1,然后再來(lái)看這里的處理吧:5.2。extra1、mAdapter.enable之前的狀態(tài)機(jī)轉(zhuǎn)變眾所周知,android在啟動(dòng)之后會(huì)啟動(dòng)一個(gè)serverThread的線程,通過(guò)這個(gè)線程會(huì)啟動(dòng)一系列的服務(wù)。我們的藍(lán)牙服務(wù)也是在這里啟動(dòng)的,android4.0其實(shí)在這個(gè)地方對(duì)狀態(tài)機(jī)進(jìn)行了修改,我們來(lái)看一下源碼:該代碼位于framworks/base/services/java/com/android/server/systemserver.javaBluetoothServicebluetooth = null;BluetoothA2dpServicebluetoothA2dp = null;//模擬器上是不支持Bluetooth的,工廠測(cè)試模式也沒(méi)有Bluetooth(這個(gè)不了解)// Skip Bluetooth if we have anemulator kernel// TODO: Use a more reliable checkto see if this product should// support Bluetooth - see bug988521if(SystemProperties.get("ro.kernel.qemu").equals("1")) {Slog.i(TAG, "No BluetoohService (emulator)");} else if (factoryTest ==SystemServer.FACTORY_TEST_LOW_LEVEL) {Slog.i(TAG, "No BluetoothService (factory test)");} else {Slog.i(TAG, "BluetoothService");//新建Bluetoothservice,并把他加入到ServiceManager中 bluetooth = newBluetoothService(context);ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE,bluetooth);//extra1.1在啟動(dòng)Bluetooth服務(wù)后進(jìn)行一些初始化,呵呵,這里就對(duì)狀態(tài)機(jī)進(jìn)行了改變 bluetooth.initAfterRegistration();//新建了BluetoothA2dpService,并把之加入到了ServiceManager中 bluetoothA2dp= new BluetoothA2dpService(context, bluetooth);ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,bluetoothA2dp);//extra1.2同樣的要在之后做些init的工作 bluetooth.initAfterA2dpRegistration();//得到是否飛行int airplaneModeOn =Settings.System.getInt(mContentResolver,Settings.System.AIRPLANE_MODE_ON, 0);//看Bluetooth是否on,若是打開(kāi)的狀態(tài)(沒(méi)有飛行),則這里會(huì)調(diào)用enable去打開(kāi)int bluetoothOn =Settings.Secure.getInt(mContentResolver,Settings.Secure.BLUETOOTH_ON, 0);if (airplaneModeOn == 0&& bluetoothOn != 0) {bluetooth.enable();}}extra1.1initAfterRegistration分析public synchronized voidinitAfterRegistration() {//得到default的adapter mAdapter =BluetoothAdapter.getDefaultAdapter();//創(chuàng)建BluetoothAdapterStateMachine,初始化幾個(gè)狀態(tài),并設(shè)初始狀態(tài)位POWEROFF,這里同時(shí)新建了一個(gè)EventLoop mBluetoothState = newBluetoothAdapterStateMachine(mContext, this, mAdapter);mBluetoothState.start();//根據(jù)這個(gè)xml的bool變量來(lái)決定是否先期TURN_HOT,該變量位于frameworks/base/core/res/res/values/config.xml中,默認(rèn)為trueif (mContext.getResources().getBoolean(com.android.internal.R.bool.config_bluetooth_adapter_quick_switch)) {//extra1.2發(fā)送TURN_HOT的狀態(tài)變化message mBluetoothState.sendMessage(BluetoothAdapterStateMachine.TURN_HOT);}//得到對(duì)應(yīng)的EventLoop mEventLoop =mBluetoothState.getBluetoothEventLoop();}extra1.2 TURN_HOT message的處理/*** Bluetooth module's power is off,firmware is not loaded.*/private class PowerOff extends State {@Overridepublic void enter() {if (DBG) log("Enter PowerOff:" + getCurrentMessage().what);}@Overridepublic boolean processMessage(Messagemessage) {log("PowerOff process message:" + message.what);boolean retValue = HANDLED;switch(message.what) {……case TURN_HOT://extra1.3這里就是我們尋找了千年的bt_enable所在的地方。我們?nèi)タ纯?/span>if (prepareBluetooth()) {//extra1.5轉(zhuǎn)變狀態(tài)到warmup,在prepareBluetooth真正完成后,這個(gè)狀態(tài)還會(huì)發(fā)生改變 transitionTo(mWarmUp);}break;……extra1.3prepareBluetooth分析看英文注釋就知道了,不解釋/*** Turn on Bluetooth Module, Loadfirmware, and do all the preparation* needed to get the Bluetooth Moduleready but keep it not discoverable* and not connectable.* The last step of this method sets upthe local service record DB.* There will be a event reporting thestatus of the SDP setup.*/private boolean prepareBluetooth() {//extra1.4首先還是調(diào)用了enableNative的本地方法,到這里你會(huì)發(fā)現(xiàn)終于和2.3相似了(不過(guò)請(qǐng)注意調(diào)用的時(shí)機(jī)不同了,這個(gè)在初始化,而2.3在界面的on/off滑動(dòng)的時(shí)候),它還是會(huì)調(diào)用bt_enable,這個(gè)就會(huì)調(diào)用對(duì)應(yīng)的set_bluetooth_power了if(mBluetoothService.enableNative() != 0) {return false;}// try to start event loop, give 2attempts//嘗試兩次去start event loopint retryCount = 2;boolean eventLoopStarted = false;while ((retryCount-- > 0)&& !eventLoopStarted) {mEventLoop.start();// it may take a moment for theother thread to do its// thing. Check periodically for a while.int pollCount = 5;while ((pollCount-- > 0)&& !eventLoopStarted) {if(mEventLoop.isEventLoopRunning()) {eventLoopStarted =true;break;}try {Thread.sleep(100);} catch(InterruptedException e) {log("prepareBluetooth sleep interrupted: " + pollCount);break;}}}//出錯(cuò)處理if (!eventLoopStarted) {mBluetoothService.disableNative();return false;}// get BluetoothService ready//建立native data以及SDP相關(guān)的一些操作,這里將會(huì)產(chǎn)生PropertyChanged的UUIDs的signal,對(duì)該信號(hào)的處理會(huì)對(duì)狀態(tài)發(fā)生改變,詳細(xì)分析見(jiàn)extra1.5if(!mBluetoothService.prepareBluetooth()) {mEventLoop.stop();mBluetoothService.disableNative();return false;}//設(shè)置一個(gè)prepare的超時(shí)處理,在該時(shí)間內(nèi)沒(méi)有收到UUID changed的signal將會(huì)進(jìn)行錯(cuò)誤處理 sendMessageDelayed(PREPARE_BLUETOOTH_TIMEOUT,PREPARE_BLUETOOTH_TIMEOUT_TIME);return true;}}extra1.4bt_enable分析intbt_enable() {LOGV(__FUNCTION__);int ret = -1;int hci_sock = -1;int attempt;//power的設(shè)置,on。不解釋,可加入對(duì)應(yīng)板子的gpio口的處理,默認(rèn)就只用了rfkill的處理if (set_bluetooth_power(1) < 0) gotoout;//開(kāi)始hciattach服務(wù),這個(gè)我們也做了修改,加入了rtk_h5 LOGI("Starting hciattachdaemon");if (property_set("ctl.start","hciattach") < 0) {LOGE("Failed to starthciattach");set_bluetooth_power(0);goto out;}// Try for 10 seconds, this can onlysucceed once hciattach has sent the// firmware and then turned on hci devicevia HCIUARTSETPROTO ioctlfor (attempt = 1000; attempt > 0; attempt--) {//創(chuàng)建hci_sock hci_sock = create_hci_sock();if (hci_sock < 0) goto out;//調(diào)用ioctl的HCIDEVUP,來(lái)判斷hciattach是否已經(jīng)ok了。 ret = ioctl(hci_sock, HCIDEVUP,HCI_DEV_ID);LOGI("bt_enable: ret: %d, errno:%d", ret, errno);if (!ret) {break;} else if (errno == EALREADY) {LOGW("Bluetoothd alreadystarted, unexpectedly!");break;}close(hci_sock);//等待10 ms后再試一次 usleep(100000); // 100 ms retry delay }//10s都沒(méi)有搞定,需要做個(gè)失敗的處理if (attempt == 0) {LOGE("%s: Timeout waiting for HCIdevice to come up, error- %d, ",__FUNCTION__, ret);if (property_set("ctl.stop","hciattach") < 0) {LOGE("Error stoppinghciattach");}set_bluetooth_power(0);goto out;}//啟動(dòng)bluetoothd服務(wù) LOGI("Starting bluetoothddeamon");if (property_set("ctl.start","bluetoothd") < 0) {LOGE("Failed to startbluetoothd");set_bluetooth_power(0);goto out;}ret = 0;out://關(guān)閉hci_sockif (hci_sock >= 0) close(hci_sock);return ret;}extra 1.5 PropetyChanged的UUIDs的處理event_filter是用來(lái)對(duì)bluez的dbus的signal進(jìn)行監(jiān)聽(tīng)的,有signal產(chǎn)生后,會(huì)在這里進(jìn)行處理。因此,我們直接到這里看看該怎么處理。//Called by dbus during WaitForAndDispatchEventNative() staticDBusHandlerResult event_filter(DBusConnection *conn, DBusMessage *msg,void*data) {native_data_t *nat;JNIEnv *env;DBusError err;DBusHandlerResult ret;//err的一個(gè)初始化 dbus_error_init(&err);//得到參數(shù) nat = (native_data_t *)data;nat->vm->GetEnv((void**)&env,nat->envVer);if (dbus_message_get_type(msg) !=DBUS_MESSAGE_TYPE_SIGNAL) {LOGV("%s: not interested (not asignal).", __FUNCTION__);returnDBUS_HANDLER_RESULT_NOT_YET_HANDLED;}LOGV("%s: Received signal %s:%s from%s", __FUNCTION__,dbus_message_get_interface(msg),dbus_message_get_member(msg),dbus_message_get_path(msg));env->PushLocalFrame(EVENT_LOOP_REFS);……//PropertyChanged這個(gè)signal的處理 } else if (dbus_message_is_signal(msg,"org.bluez.Adapter","PropertyChanged")) {//由msg解析參數(shù) jobjectArray str_array =parse_adapter_property_change(env, msg);if (str_array != NULL) {/* Check if bluetoothd has(re)started, if so update the path. */jstring property =(jstring)env->GetObjectArrayElement(str_array, 0);const char *c_property =env->GetStringUTFChars(property, NULL);//檢查Property是否startedif (!strncmp(c_property,"Powered", strlen("Powered"))) {//若是powered,則看value是否是true,是ture就得到對(duì)應(yīng)的path jstring value =(jstring)env->GetObjectArrayElement(str_array, 1);const char *c_value =env->GetStringUTFChars(value, NULL);if (!strncmp(c_value,"true", strlen("true")))nat->adapter =get_adapter_path(nat->conn);env->ReleaseStringUTFChars(value, c_value);}env->ReleaseStringUTFChars(property, c_property);//extra1.6調(diào)用對(duì)應(yīng)的method_onPropertyChanged函數(shù),該method對(duì)應(yīng)的onPropertyChanged函數(shù) env->CallVoidMethod(nat->me,method_onPropertyChanged,str_array);} elseLOG_AND_FREE_DBUS_ERROR_WITH_MSG(&err, msg);goto success;……extra1.6真正的處理函數(shù)onPropertyChanged分析/*** Called by native code on aPropertyChanged signal from* org.bluez.Adapter. This method is alsocalled from* {@link BluetoothAdapterStateMachine} toset the "Pairable"* property when Bluetooth is enabled.** @param propValues a string arraycontaining the key and one or more* values.*//*package*/ void onPropertyChanged(String[]propValues) {BluetoothAdapterPropertiesadapterProperties =mBluetoothService.getAdapterProperties();//先f(wàn)ill up cacheif (adapterProperties.isEmpty()) {// We have got a property changebefore// we filled up our cache. adapterProperties.getAllProperties();}log("Property Changed: " +propValues[0] + " : " + propValues[1]);String name = propValues[0];……//對(duì)UUIDs的處理 } else if(name.equals("Devices") || name.equals("UUIDs")) {String value = null;int len =Integer.valueOf(propValues[1]);if (len > 0) {StringBuilder str = newStringBuilder();for (int i = 2; i <propValues.length; i++) {str.append(propValues[i]);str.append(",");}value = str.toString();}//把name和value值加入到property的map中 adapterProperties.setProperty(name,value);//extra1.7有UUIDs的change signal會(huì)刷新Bluetooth的Stateif (name.equals("UUIDs")){mBluetoothService.updateBluetoothState(value);}//對(duì)Pairable和Discoverable的處理 } else if(name.equals("Pairable") || name.equals("Discoverable")) {adapterProperties.setProperty(name,propValues[1]);if(name.equals("Discoverable")) {//5.6發(fā)送SCAN_MODE_CHANGED的msg,去改變狀態(tài)機(jī) mBluetoothState.sendMessage(BluetoothAdapterStateMachine.SCAN_MODE_CHANGED); }//設(shè)置對(duì)應(yīng)的property String pairable =name.equals("Pairable") ? propValues[1] :adapterProperties.getProperty("Pairable");String discoverable =name.equals("Discoverable") ? propValues[1] :adapterProperties.getProperty("Discoverable");// This shouldn't happen, unlessAdapter Properties are null.if (pairable == null ||discoverable == null)return;int mode =BluetoothService.bluezStringToScanMode(pairable.equals("true"),discoverable.equals("true"));if (mode >= 0) {//當(dāng)pairable和discoverable均為true的時(shí)候,會(huì)發(fā)送一個(gè)ACTION_SCAN_MODE_CHANGED的廣播消息 Intent intent = newIntent(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);intent.putExtra(BluetoothAdapter.EXTRA_SCAN_MODE, mode);intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);mContext.sendBroadcast(intent,BLUETOOTH_PERM);}}……extra1.7 UUIDs改變帶來(lái)的State的刷新/*** This function is called from BluetoothEvent Loop when onPropertyChanged* for adapter comes in with UUID property.* @param uuidsThe uuids of adapter asreported by Bluez.*//*package*/ synchronized voidupdateBluetoothState(String uuids) {ParcelUuid[] adapterUuids =convertStringToParcelUuid(uuids);//為什么必須包含所有已經(jīng)有的uuid??感覺(jué)有點(diǎn)反了,再看看if (mAdapterUuids != null &&BluetoothUuid.containsAllUuids(adapterUuids, mAdapterUuids)) {//放SERVICE_RECORD_LOADED的信息,此時(shí),處于warm up狀態(tài),看extra1.8分析狀態(tài)如何繼續(xù)改變 mBluetoothState.sendMessage(BluetoothAdapterStateMachine.SERVICE_RECORD_LOADED); }}extra1.8 UUIDs對(duì)狀態(tài)機(jī)改變/*** Turning on Bluetooth module's power,loading firmware, starting* event loop thread to listen on Bluetoothmodule event changes.*/private class WarmUp extends State {@Overridepublic void enter() {if (DBG) log("Enter WarmUp:" + getCurrentMessage().what);}@Overridepublic boolean processMessage(Messagemessage) {log("WarmUp process message:" + message.what);boolean retValue = HANDLED;switch(message.what) {case SERVICE_RECORD_LOADED://可以看到,首先會(huì)把當(dāng)時(shí)從poweroff過(guò)來(lái)的一個(gè)超時(shí)message拿remove了。 removeMessages(PREPARE_BLUETOOTH_TIMEOUT);//轉(zhuǎn)到hotoff狀態(tài),在hotoff狀態(tài)仍會(huì)接收到多個(gè)SERVICE_RECORD_LOADED的msg,但是那個(gè)狀態(tài)下該msg將沒(méi)有任何handled,因此會(huì)一直處于hotoff狀態(tài) transitionTo(mHotOff);break;……5.2mAdapter.enable中mBluetoothState.sendMessage后的狀態(tài)機(jī)處理由extra的分析可知,此時(shí),Bluetooth的State已經(jīng)處于HotOff狀態(tài)了,所以,從這里開(kāi)始處理State的變換。/*** Bluetooth Module has powered, firmwareloaded, event loop started,* SDP loaded, but the modules staysnon-discoverable and* non-connectable.*/private class HotOff extends State {@Overridepublic void enter() {if (DBG) log("Enter HotOff:" + getCurrentMessage().what);}@Overridepublic boolean processMessage(Messagemessage) {log("HotOff process message:" + message.what);boolean retValue = HANDLED;switch(message.what) {case USER_TURN_ON://發(fā)出BluetoothAdapter.STATE_TURNING_ON的廣播消息 broadcastState(BluetoothAdapter.STATE_TURNING_ON);if ((Boolean) message.obj){//就是把Settings.Secure.BLUETOOTH_ON設(shè)為1。用于標(biāo)志Bluetooth enable了 persistSwitchSetting(true);}// let it fall toTURN_ON_CONTINUE://$FALL-THROUGH$//注意上面沒(méi)有break哦case TURN_ON_CONTINUE://這里就是把Bluetooth設(shè)為connectable就是Powered=1,這里就把prepareBluetooth中設(shè)置的不可連接重新設(shè)置回來(lái)了。這個(gè)重連會(huì)產(chǎn)生一些新的變化,它會(huì)發(fā)送WRITE_SCAN_ENABLE的cmd,因此在該cmd_complete時(shí)會(huì)有一些新的處理:5.3,它會(huì)再次引起狀態(tài)機(jī)的改變:5.6 mBluetoothService.switchConnectable(true);//進(jìn)入到Switching狀態(tài) transitionTo(mSwitching);break;……5.3 WRITE_SCAN_ENABLE在cmd_complete后的處理在bluez中是用cmd_complete函數(shù)來(lái)監(jiān)視發(fā)出cmd完成后的處理的。該函數(shù)具體如下:staticinline void cmd_complete(int index, void *ptr){structdev_info *dev = &devs[index];evt_cmd_complete*evt = ptr;uint16_topcode = btohs(evt->opcode);uint8_tstatus = *((uint8_t *) ptr + EVT_CMD_COMPLETE_SIZE);switch(opcode) {……//WRITE_SCAN_ENABLE命令完成的處理函數(shù),會(huì)再發(fā)一個(gè)READ_SCAN_ENABLE的命令 casecmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_SCAN_ENABLE):hci_send_cmd(dev->sk,OGF_HOST_CTL, OCF_READ_SCAN_ENABLE,0,NULL);break;//5.4緊接著就是對(duì)READ_SCAN_ENABLE命令完成的處理,它是通過(guò)read_scan_complete來(lái)實(shí)現(xiàn)的 casecmd_opcode_pack(OGF_HOST_CTL, OCF_READ_SCAN_ENABLE):ptr+= sizeof(evt_cmd_complete);read_scan_complete(index,status, ptr);break;……}5.4 read_scan命令完成的處理staticvoid read_scan_complete(int index, uint8_t status, void *ptr){structbtd_adapter *adapter;read_scan_enable_rp*rp = ptr;DBG("hci%dstatus %u", index, status);//由index得到對(duì)應(yīng)的adapter adapter= manager_find_adapter_by_id(index);if(!adapter) {error("Unableto find matching adapter");return;}//5.5這里算是一個(gè)通知adapter,mode改變了。 adapter_mode_changed(adapter,rp->enable);}5.5通知adapter,mode發(fā)生了改變voidadapter_mode_changed(struct btd_adapter *adapter, uint8_t scan_mode){constgchar *path = adapter_get_path(adapter);gbooleandiscoverable, pairable;DBG("old0x%02x new 0x%02x", adapter->scan_mode, scan_mode);//若相同,則nothing todoif(adapter->scan_mode == scan_mode){#ifdefBOARD_HAVE_BLUETOOTH_BCM/*we may reset scan_mode already inbtd_adapter_stop(), so comes to here*/set_mode_complete(adapter);#endifreturn;}//把discoverable的timeout清空 adapter_remove_discov_timeout(adapter);//這里開(kāi)始,是設(shè)為SCAN_PAGE| SCAN_INQUIRYswitch(scan_mode) {caseSCAN_DISABLED:adapter->mode= MODE_OFF;discoverable= FALSE;pairable= FALSE;break;caseSCAN_PAGE:adapter->mode= MODE_CONNECTABLE;discoverable= FALSE;pairable= adapter->pairable;break;case(SCAN_PAGE | SCAN_INQUIRY)://設(shè)一下模式,在有reply要求的情況下,該步驟還是很重要的 adapter->mode= MODE_DISCOVERABLE;discoverable= TRUE;pairable= adapter->pairable;//還要設(shè)一個(gè)discoverable的時(shí)間if(adapter->discov_timeout != 0)adapter_set_discov_timeout(adapter,adapter->discov_timeout);break;caseSCAN_INQUIRY:/*Address the scenario where a low-level application like* hciconfig changed the scan mode */if(adapter->discov_timeout != 0)adapter_set_discov_timeout(adapter,adapter->discov_timeout);/*ignore, this event should not be sent */default:/*ignore, reserved */return;}/*If page scanning gets toggled emit the Pairable property *///這里會(huì)發(fā)一個(gè)property_changed的pairable的signalif((adapter->scan_mode & SCAN_PAGE) != (scan_mode & SCAN_PAGE))emit_property_changed(connection,adapter->path,ADAPTER_INTERFACE,"Pairable",DBUS_TYPE_BOOLEAN,&pairable);if(!discoverable)adapter_set_limited_discoverable(adapter,FALSE);//這里會(huì)發(fā)一個(gè)property_changed的discoverable的signal emit_property_changed(connection,path,ADAPTER_INTERFACE,"Discoverable",DBUS_TYPE_BOOLEAN,&discoverable);adapter->scan_mode= scan_mode;set_mode_complete(adapter);}5.6 WRTIE_SCAN_ENABLE最終引起的狀態(tài)機(jī)的變化在此之前,狀態(tài)機(jī)處于switching的狀態(tài),收到了SCAN_MODE_CHANGED的msg。private class Switching extends State {@Overridepublic void enter() {if (DBG) log("Enter Switching:" + getCurrentMessage().what);}@Overridepublic boolean processMessage(Messagemessage) {log("Switching processmessage: " + message.what);boolean retValue = HANDLED;switch(message.what) {case SCAN_MODE_CHANGED:// This event matchesmBluetoothService.switchConnectable action//mPublicState在hotoff到swtiching狀態(tài)變化時(shí)已經(jīng)被設(shè)為STATE_TURNING_ON了,所以這里if沒(méi)有問(wèn)題if (mPublicState ==BluetoothAdapter.STATE_TURNING_ON) {// set pairable if it'snot//設(shè)置為pairable假如還沒(méi)有設(shè)置的話,這個(gè)會(huì)先在bluez中檢查一下當(dāng)前是否pairable,我們?cè)谇懊嬉呀?jīng)設(shè)置好了,所以,這里只是一個(gè)檢查而已,沒(méi)有什么實(shí)際性的工作 mBluetoothService.setPairable();//初始化bond state和profile state,這個(gè)會(huì)在adapter pairable之后,bluetooth turn on之前發(fā)生 mBluetoothService.initBluetoothAfterTurningOn();//這邊正式進(jìn)入到bluetoothon的狀態(tài),終于進(jìn)了這里,哎。。。 transitionTo(mBluetoothOn);//發(fā)送STATE_ON的broadcast broadcastState(BluetoothAdapter.STATE_ON);// run bluetooth nowthat it's turned on// Note runBluetoothshould be called only in adapter STATE_ON//連接那些可以自動(dòng)連接的設(shè)備,通知battery,藍(lán)牙打開(kāi)了 mBluetoothService.runBluetooth();}break;……

?


本文轉(zhuǎn)自農(nóng)夫山泉?jiǎng)e墅博客園博客,原文鏈接:http://www.cnblogs.com/yaowen/p/4980587.html,如需轉(zhuǎn)載請(qǐng)自行聯(lián)系原作者


總結(jié)

以上是生活随笔為你收集整理的Android4.0蓝牙使能的详细解析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。