




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、程序結(jié)合了網(wǎng)上的開源程序。com.example.android.bluetoothlegatt包中的代碼有修改,res文件夾和AndroidManifest.xml中的代碼沒有修改.下面直接上代碼,并把修改的地方用紅色指出來。/* Copyright(C)2013TheAndroidOpenSourceProject* LicensedundertheApacheLicense,Version2.0(the"License");* youmaynotusethisfileexceptincompliancewiththeLicense.* Youmayobtainacop
2、yoftheLicenseat* http:/licenses/LICENSE-2.0* Unlessrequiredbyapplicablelaworagreedtoinwriting,software* distributedundertheLicenseisdistributedonan"ASIS"BASIS,* WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.* SeetheLicenseforthespecificlanguagegoverningpermiss
3、ionsand* limitationsundertheLicense.* /packagecom.example.android.bluetoothlegatt;importandroid.app.Activity;importandroid.app.ListActivity;importandroid.bluetooth.BluetoothAdapter;importandroid.bluetooth.BluetoothDevice;importandroid.bluetooth.BluetoothManager;importandroid.content.Context;importan
4、droid.content.Intent;importandroid.content.pm.PackageManager;importandroid.os.Bundle;importandroid.os.Handler;importandroid.view.LayoutInflater;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.BaseAdapter;importandroid.widg
5、et.ListView;importandroid.widget.TextView;importandroid.widget.Toast;importjava.util.ArrayList;/*ActivityforscanninganddisplayingavailableBluetoothLEdevices.*/publicclassDeviceScanActivityextendsListActivityprivateLeDeviceListAdaptermLeDeviceListAdapter;/適配器adapter,存放搜尋到的設(shè)備信息privateBluetoothAdapterm
6、BluetoothAdapter;privatebooleanmScanning;privateHandlermHandler;privatestaticfinalintREQUEST_ENABLE_BT=1;/10秒后停止查找搜索.privatestaticfinallongSCAN_PERIOD=10000;OverridepublicvoidonCreate(BundlesavedInstanceState)super.onCreate(savedInstanceState);getActionBar().setTitle(R.string.title_devices);BLEDevic
7、eScanmHandler=newHandler();/檢查當(dāng)前手機(jī)是否支持ble藍(lán)牙,如果不支持退出程序ifR.string.ble_not_supported,(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)Toast.makeText(this,Toast.LENGTH_SHORT).show();finish();/初始化Bluetoothadapter,通過藍(lán)牙管理器得到一個參考藍(lán)牙適配器/(API必須在以上android4.3或以上和版本)finalBluetoothManager
8、bluetoothManager=(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);mBluetoothAdapter=bluetoothManager.getAdapter();R.string.error_bluetooth_not_supported,/檢查設(shè)備上是否支持藍(lán)牙if(mBluetoothAdapter=null)Toast.makeText(this,Toast.LENGTH_SHORT).show();finish();return;/選項(xiàng)菜單(optionsMenu)。在Menu對象的方法來添加菜
9、單或者是子菜單。OverridepublicbooleanonCreateOptionsMenu(Menumenu)getMenuInflater().inflate(R.menu.main,menu);/mScanning代表搜尋與否,初始值為FALSEif(!mScanning)menu.findItem(R.id.menu_stop).setVisible(false);menu.findItem(R.id.menu_scan).setVisible(true);/正在搜索menu.findItem(R.id.menu_refresh).setActionView(null);elsem
10、enu.findItem(R.id.menu_stop).setVisible(true);/停止搜索menu.findItem(R.id.menu_scan).setVisible(false);menu.findItem(R.id.menu_refresh).setActionView(R.layout.actionbar_indeterminate_progress);returntrue;響應(yīng)菜單項(xiàng)單擊事件,切換搜索與否OverridepublicbooleanonOptionsItemSelected(MenuItemitem)switch(item.getItemId()caseR
11、.id.menu_scan:mLeDeviceListAdapter.clear();清空適配器,重新搜索scanLeDevice(true);break;caseR.id.menu_stop:scanLeDevice(false);break;returntrue;恢復(fù),Activity時(shí)候被回調(diào)。OverrideprotectedvoidonResume()super.onResume();/為了確保設(shè)備上藍(lán)牙能使用,如果當(dāng)前藍(lán)牙設(shè)備沒啟用,彈出對話框向用戶要求授予權(quán)限來啟用/EnsuresBluetoothisenabledonthedevice.IfBluetoothisnotcurr
12、entlyenabled,/fireanintenttodisplayadialogaskingtheusertograntpermissiontoenableit.if(!mBluetoothAdapter.isEnabled()if(!mBluetoothAdapter.isEnabled()IntentenableBtIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);/Initializeslistviewada
13、pter.mLeDeviceListAdapter=newLeDeviceListAdapter();/新建適配器setListAdapter(mLeDeviceListAdapter);/數(shù)據(jù)綁定scanLeDevice(true);)/子activity完成后,需要帶回?cái)?shù)據(jù)給主activity,需要回調(diào)該方法OverrideprotectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata)/UserchosenottoenableBluetooth.當(dāng)運(yùn)算符兩邊的表達(dá)式的結(jié)果都為true時(shí),整個運(yùn)算結(jié)果才為truei
14、f(requestCode=REQUEST_ENABLE_BT&&resultCode=Activity.RESULT_CANCELED)finish();return;)super.onActivityResult(requestCode,resultCode,data);)/暫彳factivity時(shí)候被回調(diào)OverrideprotectedvoidonPause()super.onPause();scanLeDevice(false);mLeDeviceListAdapter.clear();)/ListView中的條目短按和長按事件,他們的處理方式是不同的。對于短按事件,
15、處理起來比較簡單,/我們只需要覆蓋ListActivity的onListItemClick()方法OverrideprotectedvoidonListItemClick(ListViewl,Viewv,intposition,longid)finalBluetoothDevicedevice=mLeDeviceListAdapter.getDevice(position);if(device=null)return;finalIntentintent=newIntent(this,DeviceControlActivity.class);intent.putExtra(DeviceContr
16、olActivity.EXTRAS_DEVICE_NAME,device.getName();intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS,device.getAddress();/putExtra("A",B)中,AB為鍵值對,第一個參數(shù)為鍵名,第二個參數(shù)為鍵對應(yīng)的值。/順便提一下,如果想取出Intent對象中的這些值,需要在你的另一個Activity中用getXXXXXExtra方法,/注意需要使用對應(yīng)類型的方法,參數(shù)為鍵名if(mScanning)mBluetoothAdapter.stopLe
17、Scan(mLeScanCallback);mScanning=false;)startActivity(intent);/啟動activity)privatevoidscanLeDevice(finalbooleanenable)if(enable)/Stopsscanningafterapre-definedscanperiod./mHandler.postDelayed(newRunnable()Overridepublicvoidrun()mScanning=false;mBluetoothAdapter.stopLeScan(mLeScanCallback);invalidateOp
18、tionsMenu();),SCAN_PERIOD);mScanning=true;mBluetoothAdapter.startLeScan(mLeScanCallback);elsemScanning=false;mBluetoothAdapter.stopLeScan(mLeScanCallback);invalidateOptionsMenu();在運(yùn)行時(shí)更改選項(xiàng)菜單隨時(shí)動態(tài)改變OptionMenu就要實(shí)現(xiàn)onPrepareOptionsMenu()方法繼承BaseAdapter,實(shí)現(xiàn)adapter,存放listview中的數(shù)據(jù)。/實(shí)現(xiàn)自己的adapter/Adapterforhold
19、ingdevicesfoundthroughscanning.privateclassLeDeviceListAdapterextendsBaseAdapterprivateArrayList<BluetoothDevice>mLeDevices;/數(shù)組privateLayoutInflatermInflator;publicLeDeviceListAdapter()/構(gòu)造函數(shù)super();mLeDevices=newArrayList<BluetoothDevice>();mInflator=DeviceScanActivity.this.getLayoutInfl
20、ater();/M象中的方法,addDevicepublicvoidaddDevice(BluetoothDevicedevice)if(!mLeDevices.contains(device)mLeDevices.add(device);)publicBluetoothDevicegetDevice(intposition)returnmLeDevices.get(position);)publicvoidclear()mLeDevices.clear();)OverridepublicintgetCount()returnmLeDevices.size();)OverridepublicO
21、bjectgetItem(inti)returnmLeDevices.get(i);)OverridepubliclonggetItemId(inti)returni;)OverridepublicViewgetView(inti,Viewview,ViewGroupviewGroup)ViewHolderviewHolder;/GeneralListViewoptimizationcode.if(view=null)view=mInflator.inflate(R.layout.listitem_device,null);viewHolder=newViewHolder();viewHold
22、er.deviceAddress=(TextView)view.findViewById(R.id.device_address);viewHolder.deviceName=(TextView)view.findViewById(R.id.device_name);view.setTag(viewHolder);/View中的setTag(Onbect)表示給View添加一個格外的數(shù)據(jù),以后可以用getTag()將這個數(shù)據(jù)取出來。elseviewHolder=(ViewHolder)view.getTag();BluetoothDevicedevice=mLeDevices.get(i);f
23、inalStringdeviceName=device.getName();if(deviceName!=null&&deviceName.length()>0)viewHolder.deviceName.setText(deviceName);elseviewHolder.deviceName.setText(R.string.unknown_device);viewHolder.deviceAddress.setText(device.getAddress();returnview;)/Devicescancallback.privateBluetoothAdapte
24、r.LeScanCallbackmLeScanCallback=newBluetoothAdapter.LeScanCallback()OverridepublicvoidonLeScan(finalBluetoothDevicedevice,intrssi,byte口scanRecord)runOnUiThread(newRunnable()Overridepublicvoidrun()mLeDeviceListAdapter.addDevice(device);mLeDeviceListAdapter.notifyDataSetChanged();););staticclassViewHo
25、lderTextViewdeviceName;TextViewdeviceAddress;* Unlessrequiredbyapplicablelaworagreedtoinwriting,software* distributedundertheLicenseisdistributedonan"ASIS"BASIS,* WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.* SeetheLicenseforthespecificlanguagegoverningpermissionsand* lim
26、itationsundertheLicense.*/packagecom.example.android.bluetoothlegatt;importjava.util.HashMap;/* ThisclassincludesasmallsubsetofstandardGATTattributesfordemonstrationpurposes.*/publicclassSampleGattAttributesprivatestaticHashMap<String,String>attributes=newHashMap();publicstaticStringHEART_RATE
27、_MEASUREMENT="6e400001-b5a3-f393-e0a9-e50e24dcca9e"publicstaticStringCLIENT_CHARACTERISTIC_CONFIG=“00002902-0000-1000-8000-00805f9b34fb"static/SampleServices.attributes.put("0000180d-0000-1000-8000-00805f9b34fb","HeartRateService");attributes.put("0000180a-000
28、0-1000-8000-00805f9b34fb","DeviceInformationService");/SampleCharacteristics.attributes.put(HEART_RATE_MEASUREMENT,"HeartRateMeasurement");attributes.put(“00002a29-0000-1000-8000-00805f9b34fb","ManufacturerNameString");)publicstaticStringlookup(Stringuuid,Stri
29、ngdefaultName)Stringname=attributes.get(uuid);returnname=null?defaultName:name;)http:/www.apache.Org/licenses/LICENSE-2.0* Unlessrequiredbyapplicablelaworagreedtoinwriting,software* distributedundertheLicenseisdistributedonan"ASIS"BASIS,* WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpres
30、sorimplied.* SeetheLicenseforthespecificlanguagegoverningpermissionsand* limitationsundertheLicense.*/packagecom.example.android.bluetoothlegatt;importandroid.app.Activity;importandroid.bluetooth.BluetoothGattCharacteristic;importandroid.bluetooth.BluetoothGattService;importandroid.content.Broadcast
31、Receiver;importandroid.content.ComponentName;importandroid.content.Context;importandroid.content.Intent;importandroid.content.IntentFilter;importandroid.content.ServiceConnection;importandroid.os.Bundle;importandroid.os.IBinder;importandroid.util.Log;importandroid.view.Menu;importandroid.view.MenuIt
32、em;importandroid.view.View;importandroid.widget.EditText;importandroid.widget.ExpandableListView;importandroid.widget.SimpleExpandableListAdapter;importandroid.widget.TextView;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;/* ForagivenBLEdevice,thisActivityprovidestheuserinte
33、rfacetoconnect,displaydata,*anddisplayGATTservicesandcharacteristicssupportedbythedevice.TheActivity*communicateswithcodeBluetoothLeService,whichinturninteractswiththe* BluetoothLEAPI.*/publicclassDeviceControlActivityextendsActivityprivatefinalstaticStringTAG=DeviceControlActivity.class.getSimpleNa
34、me();publicstaticfinalStringEXTRAS_DEVICE_NAME="DEVICE_NAME"publicstaticfinalStringEXTRAS_DEVICE_ADDRESS="DEVICE_ADDRESS"privateTextViewmConnectionState;privateTextViewmDataField;privateStringmDeviceName;privateStringmDeviceAddress;privateExpandableListViewmGattServicesList;priva
35、teBluetoothLeServicemBluetoothLeService;privateArrayList<ArrayList<BluetoothGattCharacteristic>>mGattCharacteristics=newArrayList<ArrayList<BluetoothGattCharacteristic>>();privatebooleanmConnected=false;privateBluetoothGattCharacteristicmNotifyCharacteristic;privatefinalStrin
36、gLIST_NAME="NAME"privatefinalStringLIST_UUID="UUID"/CodetomanageServicelifecycle.這個對象,是綁定service的第二個參數(shù)privatefinalServiceConnectionmServiceConnection=newServiceConnection()OverridepublicvoidonServiceConnected(ComponentNamecomponentName,IBinderservice)mBluetoothLeService=(Bluetoot
37、hLeService.LocalBinder)service).getService();初始化完成,返回TRUEif(!mBluetoothLeService.initialize()Log.e(TAG,"UnabletoinitializeBluetooth");finish();/Automaticallyconnectstothedeviceuponsuccessfulstart-upinitialization.因?yàn)橐呀?jīng)初始化完成,直接調(diào)用方法根據(jù)地址連接mBluetoothLeService.connect(mDeviceAddress);Overridepub
38、licvoidonServiceDisconnected(ComponentNamecomponentName)mBluetoothLeService=null;/HandlesvariouseventsfiredbytheService./ACTION_GATT_CONNECTED:connectedtoaGATTserver./ACTION_GATT_DISCONNECTED:disconnectedfromaGATTserver./ACTION_GATT_SERVICES_DISCOVERED:discoveredGATTservices./ACTION_DATA_AVAILABLE:r
39、eceiveddatafromthedevice.Thiscanbearesultofread/ornotificationoperations.廣播接收器privatefinalBroadcastReceivermGattUpdateReceiver=newBroadcastReceiver()OverridepublicvoidonReceive(Contextcontext,Intentintent)finalStringaction=intent.getAction();/這個intent應(yīng)該是從service來的if(BluetoothLeService.ACTION_GATT_CO
40、NNECTED.equals(action)mConnected=true;updateConnectionState(R.string.connected);invalidateOptionsMenu();elseif(BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)mConnected=false;updateConnectionState(R.string.disconnected);invalidateOptionsMenu();clearUI();elseif(BluetoothLeService.ACTION_GA
41、TT_SERVICES_DISCOVERED.equals(action)/Showallthesupportedservicesandcharacteristicsontheuserinterface.displayGattServices(mBluetoothLeService.getSupportedGattServices();elseif(BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA);/put
42、Extra("A",B)中,AB為鍵值對,第一個參數(shù)為鍵名,第二個參數(shù)為鍵對應(yīng)的值。順便提一下,如果想取出Intent對象中的這些值,需要在你的另一個Activity中用getXXXXXExtra方法,注意需要使用對應(yīng)類型的方法,參數(shù)為鍵名;/IfagivenGATTcharacteristicisselected,checkforsupportedfeatures.Thissample/demonstrates'Read'and'Notify'features.See/http:/listofsupportedcharacteristicf
43、eatures.privatefinalExpandableListView.OnChildClickListenerservicesListClickListner=newExpandableListView.OnChildClickListener()OverridepublicbooleanonChildClick(ExpandableListViewparent,Viewv,intgroupPosition,intchildPosition,longid)if(mGattCharacteristics!=null)if(groupPosition=2&&childPos
44、ition=0)/響應(yīng)第一個子列表項(xiàng),表示讀取藍(lán)牙/問題是:長一些的字符串,能馬上讀取,短字符串,需要發(fā)送多次。finalBluetoothGattCharacteristiccharacteristic=mGattCharacteristics.get(groupPosition).get(childPosition);finalintcharaProp=characteristic.getProperties();if(charaProp|BluetoothGattCharacteristic.PROPERTY_READ)>0)/Ifthereisanactivenotificati
45、onona/characteristic,clear/itfirstsoitdoesn'tupdatethedatafieldonthe/userinterface.System.out.println("infor");if(mNotifyCharacteristic!=null)System.out.println("inif");mBluetoothLeService.setCharacteristicNotification(mNotifyCharacteristic,false);mNotifyCharacteristic=null;m
46、BluetoothLeService.readCharacteristic(characteristic);if(charaProp|BluetoothGattCharacteristic.PROPERTY_NOTIFY)>0)System.out.println("inif");mNotifyCharacteristic=characteristic;mBluetoothLeService.setCharacteristicNotification(characteristic,true);returntrue;if(groupPosition=2&&
47、;childPosition=1)/響應(yīng)第二個子列表項(xiàng)表示寫藍(lán)牙設(shè)備System.out.println("setdown");Stringstr="a"bytesrtbyte=str.getBytes();writeCharacteristic(srtbyte);/調(diào)用寫數(shù)據(jù)函數(shù)returntrue;returnfalse;);publicvoidwriteCharacteristic(bytei)/寫數(shù)據(jù)藍(lán)牙設(shè)備for(ArrayList<BluetoothGattCharacteristic>LumChar0:mGattCharacte
48、ristics)for(BluetoothGattCharacteristicLumChar:LumChar0)if(LumChar=null)System.out.println("LumCharnull");return;)LumChar.setValue(i);booleanstatus=BluetoothLeService.mBluetoothGatt.writeCharacteristic(LumChar);System.out.println("WriteStatus:"+status);System.out.println("OK
49、");)privatevoidclearUI()mGattServicesList.setAdapter(SimpleExpandableListAdapter)null);mDataField.setText(R.string.no_data);)OverridepublicvoidonCreate(BundlesavedInstanceState)super.onCreate(savedInstanceState);setContentView(R.layout.gatt_services_characteristics);finalIntentintent=getIntent(
50、);/得到從另一個activity來的intent/根據(jù)鍵值得到數(shù)據(jù)mDeviceName=intent.getStringExtra(EXTRAS_DEVICE_NAME);mDeviceAddress=intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);/SetsupUIreferences./(TextView)findViewById(R.id.device_address).setText(mDeviceAddress);mGattServicesList=(ExpandableListView)findViewById(R.id.gatt_services_list);mGattServicesList.setOnChildClickListener(servicesListClickListner);mConnectionState=(TextView)findViewById(R.id.connection_state);mDataField=(TextView)findViewById(R.id.da
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 期貨市場品牌建設(shè)與維護(hù)服務(wù)考核試卷
- 木材加工行業(yè)人才培養(yǎng)計(jì)劃考核試卷
- 攝影器材行業(yè)市場動態(tài)監(jiān)測與競爭情報(bào)分析考核試卷
- 辦公室員工職業(yè)發(fā)展與培訓(xùn)體系建設(shè)案例考核試卷
- 天然氣開采項(xiàng)目財(cái)務(wù)管理與成本控制考核試卷
- 固體飲料的無添加與天然成分趨勢考核試卷
- 木材貿(mào)易風(fēng)險(xiǎn)管理與防范考核試卷
- 搪瓷衛(wèi)生潔具的顧客滿意度調(diào)查考核試卷
- 放射性金屬礦選礦實(shí)驗(yàn)方法與技術(shù)考核試卷
- 鋼板出售轉(zhuǎn)讓合同范本
- 2023年2024年演出經(jīng)紀(jì)人之演出經(jīng)紀(jì)實(shí)務(wù)考試題庫附答案(達(dá)標(biāo)題)
- DG-T 076-2024 采茶機(jī)標(biāo)準(zhǔn)規(guī)范
- 《分娩機(jī)轉(zhuǎn)》課件
- 軍隊(duì)文職備考(面試)近年考試真題(參考300題)
- 金融業(yè)稅收優(yōu)惠政策指引
- 乳腺癌課件教學(xué)課件
- 第五期健康講座乳腺癌與宮頸癌防治知識
- 2025年神經(jīng)內(nèi)科??谱o(hù)士培訓(xùn)計(jì)劃范文
- 葉圣陶杯作文
- 電子商務(wù)平臺供貨方案及風(fēng)險(xiǎn)控制措施
- 文獻(xiàn)檢索與利用
評論
0/150
提交評論