android实现蓝牙app代码
本文实例为大家分享了android实现蓝牙app的具体代码,供大家参考,具体内容如下
privateBluetoothGattbluetoothGatt; privateBluetoothGattServicegattService; privateBluetoothGattCharacteristicgattCharacteristic; privateBluetoothManagerbluetoothManager; privateBluetoothAdapterbluetoothAdapter; privateListdevices=newArrayList<>(); privateUUIDserviceUUID;//不同设备不同uuid privateUUIDcharacteristicUUID;//不同设备不同uuid privatefinalUUIDservice4UUID=UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"); privatefinalUUIDcharAUUID=UUID.fromString("0000fffa-0000-1000-8000-00805f9b34fb"); privateLightReceiverlightReceiver; privateScanReceiverscanReceiver; privateListViewlistView; privateTextViewtvrefresh; privateStringlightAction; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i("tag","MainActivityonCreate()"); // listView=(ListView)findViewById(R.id.lv_bluetooth); tvrefresh=(TextView)findViewById(R.id.tv_refresh_bluetooth); tvrefresh.setOnClickListener(this); openBluetooth(); registeLigthReceiver(); registeScanReceiver(); } @Override protectedvoidonStart(){ super.onStart(); Log.i("tag","MainActivityonStart()"); bluetoothScan(); } //返回 @Override publicbooleanonKeyUp(intkeyCode,KeyEventevent){ Log.i("tag","MainActivityonKeyUp()"); this.finish(); returnsuper.onKeyUp(keyCode,event); } //重新扫描蓝牙 @Override publicvoidonClick(Viewview){ switch(view.getId()){ caseR.id.tv_refresh_bluetooth: //蓝牙扫描 bluetoothScan(); break; default: break; } } //打开本地蓝牙 privatevoidopenBluetooth(){ Log.i("tag","openLocalBluetooth()"); //检查手机是否支持蓝牙4.0 if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){ Toast.makeText(this,"手机不支持蓝牙4.0",Toast.LENGTH_SHORT).show(); finish(); } //调用系统服务的方式,请求开启蓝牙 bluetoothManager=(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter=bluetoothManager.getAdapter(); //开启蓝牙 if(!bluetoothAdapter.isEnabled()){ bluetoothAdapter.enable(); } } //开始蓝牙扫描扫描到一个添加一个 privatevoidbluetoothScan(){ Log.i("tag","bluetoothScan()"); if(bluetoothAdapter==null){ openBluetooth(); } if(!bluetoothAdapter.isDiscovering()){ bluetoothAdapter.startDiscovery();//回调 }else{ Toast.makeText(this,"扫描中..",Toast.LENGTH_SHORT).show(); } } //更新蓝牙列表中的数据 privatevoidupdateUi(){ Log.i("tag","updateUi()"); if(devices!=null&&devices.size()>0){ BlueAdapteradapter=newBlueAdapter(this,devices); listView.setAdapter(adapter); adapter.notifyDataSetChanged(); }else{ Toast.makeText(this,"附近没有蓝牙",Toast.LENGTH_SHORT).show(); } } //取得gatt对应的service privateBluetoothGattServicegetGattService(BluetoothGattgatt,UUIDserviceUUID){ List gattServices=gatt.getServices(); for(BluetoothGattServicegattService:gattServices){ if(gattService.getUuid().equals(serviceUUID)){ returngattService; } } returnnull; } //取得service对应的characteristic privateBluetoothGattCharacteristicgetGattCharacteristic(BluetoothGattServicegattService,UUIDcharacteristicUUID){ List gattCharacteristics=gattService.getCharacteristics(); for(BluetoothGattCharacteristicgattCharacteristic:gattCharacteristics){ if(gattCharacteristic.getUuid().equals(characteristicUUID)){ returngattCharacteristic; } } returnnull; } //注册蓝牙扫描监听 privatevoidregisteScanReceiver(){ Log.i("tag","registeScanReceiver()"); scanReceiver=newScanReceiver(); IntentFilterfilter=newIntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); registerReceiver(scanReceiver,filter); } //定义蓝牙扫描监听类添加device,更新界面 classScanReceiverextendsBroadcastReceiver{ @Override publicvoidonReceive(Contextcontext,Intentintent){ Log.i("tag","BluetoothReceiver/ScanReceiveronReceive()action="+intent.getAction()); StringscanAction=intent.getAction(); if(scanAction.equals(BluetoothDevice.ACTION_FOUND)){ BluetoothDevicedevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if(!devices.contains(device)){ devices.add(device); if(CacheUtils.getBlueDeviceString(MainActivity1.this,device.getAddress()).equals("")){ CacheUtils.putBlueDeviceString(MainActivity1.this,device.getAddress(),device.getName()); } updateUi(); } }elseif(scanAction.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){ if(devices==null||devices.size()==0){ Toast.makeText(MainActivity1.this,"附近没有发现蓝牙设备",Toast.LENGTH_SHORT).show(); } } } } //注册灯光监听 privatevoidregisteLigthReceiver(){ Log.i("tag","registeReceiver()"); lightReceiver=newLightReceiver(); IntentFilterfilter=newIntentFilter(); filter.addAction("openLight"); filter.addAction("closeLight"); registerReceiver(lightReceiver,filter); } //定义灯控监听类 classLightReceiverextendsBroadcastReceiver{ @Override publicvoidonReceive(Contextcontext,Intentintent){ Log.i("tag","BluetoothReceiver/LightReceiveronReceive()action="+intent.getAction()); // Stringaddress=intent.getStringExtra("bluetoothAddress");//从adapter取得的数据 lightAction=intent.getAction(); //if()不同设备不同serviceUUID,不同的characteristicUUID自己确定 serviceUUID=service4UUID; characteristicUUID=charAUUID; if(bluetoothAdapter==null){ openBluetooth(); } BluetoothDevicedevice=bluetoothAdapter.getRemoteDevice(address); MyBluetoothGattCallbackgattCallback=newMyBluetoothGattCallback(); bluetoothGatt=device.connectGatt(MainActivity1.this,false,gattCallback);//回调 } } //蓝牙连接/通信回调 classMyBluetoothGattCallbackextendsandroid.bluetooth.BluetoothGattCallback{ @Override publicvoidonConnectionStateChange(BluetoothGattgatt,intstatus,intnewState){ super.onConnectionStateChange(gatt,status,newState); Log.i("tag","MyBluetoothGattCallbackonConnectionStateChange()newState="+newState); if(newState==BluetoothProfile.STATE_CONNECTED){ gatt.discoverServices();//连接成功,开始搜索服务,一定要调用此方法,否则获取不到服务 Log.i("tag","MyBluetoothGattCallbackSTATE_CONNECTED"); }elseif(newState==BluetoothProfile.STATE_DISCONNECTED){ Log.i("tag","MyBluetoothGattCallbackSTATE_DISCONNECTED"); } } @Override publicvoidonServicesDiscovered(BluetoothGattgatt,intstatus){ super.onServicesDiscovered(gatt,status); Log.i("tag","MyBluetoothGattCallbackonServicesDiscovered()status="+status); if(lightAction.equals("openLight")||lightAction.equals("closeLight")){//避免不停更新 if(gattService==null||gattCharacteristic==null||!serviceUUID.equals(service4UUID)||!characteristicUUID.equals(charAUUID)){ gattService=getGattService(gatt,serviceUUID); if(gattService!=null){ gattCharacteristic=getGattCharacteristic(gattService,characteristicUUID); if(gattCharacteristic!=null){ gatt.setCharacteristicNotification(gattCharacteristic,true); gatt.connect(); } } } if(lightAction.equals("openLight")){ gattCharacteristic.setValue("openLight");//这里自己设置蓝牙模组需要的数据 gatt.writeCharacteristic(gattCharacteristic); }elseif(lightAction.equals("closeLight")){ gattCharacteristic.setValue("closeLight");//这里自己设置蓝牙模组需要的数据 gatt.writeCharacteristic(gattCharacteristic); } lightAction=""; gatt.readRemoteRssi(); } } } @Override protectedvoidonDestroy(){ super.onDestroy(); Log.i("tag","onDestroy()"); if(bluetoothAdapter!=null){ bluetoothAdapter.disable(); bluetoothAdapter=null; } if(bluetoothGatt!=null){ bluetoothGatt.disconnect(); bluetoothGatt.close(); bluetoothGatt=null; } if(lightReceiver!=null){ unregisterReceiver(lightReceiver); lightReceiver=null; } if(scanReceiver!=null){ unregisterReceiver(scanReceiver); scanReceiver=null; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。