標籤:
最近公司在搞IBeacon,因為公司另一個學android的走了,而剩下的人中,只有我接觸過java、android,所以只有我來做這個了。
聲明,我是一個C#的程式員,java、android都是弱項,只是略有涉及,不懂、錯誤之處,多多指教。
一開始,我在網上搜IBeacon的資料(使用百度,唉,看來我還是2B程式員啊),最詳細的就只有兩個,而這兩個都是同一個人的,hellogv,播客地址:http://my.csdn.net/hellogv
我找到的兩個博文,
http://blog.csdn.net/hellogv/article/details/24267685
http://blog.csdn.net/hellogv/article/details/24661777
因為一開是沒有接觸過這個東西,所以看不懂啊。只好把代碼下載下來,去實際運行一下。
當然,我先下載的是搜尋基站的那個,不然沒有基站,我上哪裡去通訊的???!!!
對了,這個BLE是在android 4.3.1版本及以上才能使用哦。
好了,廢話少說。
(1)開啟藍芽
這步不多說什麼了。
擷取BluetoothManager、BluetoothAdapter
1 /** 2 * Initializes a reference to the local Bluetooth adapter. 3 * 4 * @return Return true if the initialization is successful. 5 */ 6 public boolean initialize() 7 { 8 // Use this check to determine whether BLE is supported on the device. Then you can 9 // selectively disable BLE-related features. 10 if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))11 {12 Log.e(TAG, "Unable to initialize Bluetooth.");13 return false;14 }15 // For API level 18 and above, get a reference to BluetoothAdapter through16 // BluetoothManager.17 if (mBluetoothManager == null)18 {19 mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);20 if (mBluetoothManager == null)21 {22 Log.e(TAG, "Unable to initialize BluetoothManager.");23 return false;24 }25 }26 27 mBluetoothAdapter = mBluetoothManager.getAdapter();28 if (mBluetoothAdapter == null)29 {30 Log.e(TAG, "Unable to obtain a BluetoothAdapter.");31 return false;32 }33 34 return true;35 }36
然後開啟藍芽
public boolean OpenBlue() { //開啟藍芽 if (!mBluetoothAdapter.isEnabled()) return mBluetoothAdapter.enable(); else return true; }
因為我寫C#習慣了,vs代碼樣式就是這樣的,所以,嘿嘿,能看就行啦哈
(2)掃描
1 private void scanLeDevice(final boolean enable) 2 { 3 if (enable)//enable =true就是說要開始掃描 4 { 5 // Stops scanning after a pre-defined scan period. 6 // 下邊的代碼是為了在 SCAN_PERIOD 後,停止掃描的 7 // 如果需要不停的掃描,可以注釋掉 8 mHandler.postDelayed(new Runnable() 9 {10 @Override11 public void run()12 {13 mScanning = false;14 mBluetoothAdapter.stopLeScan(mLeScanCallback);15 // 這個是重設menu,將 menu中的停止按鈕->掃描按鈕16 invalidateOptionsMenu();17 }18 }, SCAN_PERIOD);19 20 mScanning = true;//此變數指示掃描是否進行21 mBluetoothAdapter.startLeScan(mLeScanCallback);//這句就是開始掃描了22 }23 else24 {25 mScanning = false;26 mBluetoothAdapter.stopLeScan(mLeScanCallback);//這句就是停止掃描27 }28 // 這個是重設menu,將 menu中的掃描按鈕->停止按鈕29 invalidateOptionsMenu();30 }
這裡有個變數 mLeScanCallback,這個是什麼呢?
1 // Device scan callback. 2 private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() 3 { 4 @Override 5 public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) 6 { 7 iBeacon iBeacon = fromScanData(device, rssi, scanRecord);20 }21 };22
通過探索呢,這個東西就是一個回呼函數,當藍芽接收到某廣播時,就會調用 mLeScanCallback.onLeScan()函數。device當然就是廣播的裝置了,rssi是訊號強度,scanRecord是廣播的資訊。
然後通過解析scanRecord就可以知道裝置的詳情了。formScanData我就不多說了,在大神的源碼裡有。
擷取到IBeacon以後,你就可以把他放到列表裡,該怎麼顯示就是你的問題了。
android IBeacon 開發(一)