国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

android實現藍牙app代碼

2019-12-12 00:50:45
字體:
來源:轉載
供稿:網友

本文實例為大家分享了android實現藍牙app的具體代碼,供大家參考,具體內容如下

private BluetoothGatt bluetoothGatt;private BluetoothGattService gattService;private BluetoothGattCharacteristic gattCharacteristic;private BluetoothManager bluetoothManager;private BluetoothAdapter bluetoothAdapter;private List<BluetoothDevice> devices = new ArrayList<>();private UUID serviceUUID;  //不同設備 不同uuidprivate UUID characteristicUUID;   //不同設備 不同uuidprivate final UUID service4UUID= UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");  private final UUID charAUUID = UUID.fromString("0000fffa-0000-1000-8000-00805f9b34fb");private LightReceiver lightReceiver;private ScanReceiver scanReceiver;private ListView listView;private TextView tvrefresh;private String lightAction;@Overrideprotected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  Log.i("tag", "MainActivity  onCreate()");  //  listView = (ListView) findViewById(R.id.lv_bluetooth);  tvrefresh = (TextView) findViewById(R.id.tv_refresh_bluetooth);  tvrefresh.setOnClickListener(this);  openBluetooth();  registeLigthReceiver();  registeScanReceiver();}@Overrideprotected void onStart() {  super.onStart();  Log.i("tag", "MainActivity  onStart()");  bluetoothScan();}//返回@Overridepublic boolean onKeyUp(int keyCode, KeyEvent event) {  Log.i("tag", "MainActivity  onKeyUp()");  this.finish();  return super.onKeyUp(keyCode, event);}//重新掃描藍牙@Overridepublic void onClick(View view) {  switch (view.getId()) {    case R.id.tv_refresh_bluetooth:      //藍牙掃描      bluetoothScan();      break;    default:      break;  }}//打開本地藍牙private void openBluetooth() {  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();  }}//開始藍牙掃描  掃描到一個添加一個private void bluetoothScan() {  Log.i("tag", "bluetoothScan()");  if (bluetoothAdapter == null) {    openBluetooth();  }  if (!bluetoothAdapter.isDiscovering()) {    bluetoothAdapter.startDiscovery();  //回調  } else {    Toast.makeText(this, "掃描中..", Toast.LENGTH_SHORT).show();  }}//更新藍牙列表中的數據private void updateUi() {  Log.i("tag", "updateUi()");  if (devices != null && devices.size() > 0) {    BlueAdapter adapter = new BlueAdapter(this, devices);    listView.setAdapter(adapter);    adapter.notifyDataSetChanged();  } else {    Toast.makeText(this, "附近沒有藍牙", Toast.LENGTH_SHORT).show();  }}//取得gatt 對應的serviceprivate BluetoothGattService getGattService(BluetoothGatt gatt, UUID serviceUUID) {  List<BluetoothGattService> gattServices = gatt.getServices();  for (BluetoothGattService gattService : gattServices) {    if (gattService.getUuid().equals(serviceUUID)) {      return gattService;    }  }  return null;}//取得service對應的characteristicprivate BluetoothGattCharacteristic getGattCharacteristic(BluetoothGattService gattService, UUID characteristicUUID) {  List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();  for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {    if (gattCharacteristic.getUuid().equals(characteristicUUID)) {      return gattCharacteristic;    }  }  return null;}//注冊藍牙掃描監聽private void registeScanReceiver() {  Log.i("tag", "registeScanReceiver()");  scanReceiver = new ScanReceiver();  IntentFilter filter = new IntentFilter();  filter.addAction(BluetoothDevice.ACTION_FOUND);  filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  registerReceiver(scanReceiver, filter);}//定義藍牙掃描監聽類 添加device , 更新界面class ScanReceiver extends BroadcastReceiver {  @Override  public void onReceive(Context context, Intent intent) {    Log.i("tag", " BluetoothReceiver / ScanReceiver onReceive()  action=" + intent.getAction());    String scanAction = intent.getAction();    if (scanAction.equals(BluetoothDevice.ACTION_FOUND)) {      BluetoothDevice device = 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();      }    } else if (scanAction.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {      if (devices == null || devices.size() == 0) {        Toast.makeText(MainActivity1.this, "附近沒有發現藍牙設備", Toast.LENGTH_SHORT).show();      }    }  }}//注冊燈光監聽private void registeLigthReceiver() {  Log.i("tag", "registeReceiver()");  lightReceiver = new LightReceiver();  IntentFilter filter = new IntentFilter();  filter.addAction("openLight");  filter.addAction("closeLight");  registerReceiver(lightReceiver, filter);}//定義燈控監聽類class LightReceiver extends BroadcastReceiver {  @Override  public void onReceive(Context context, Intent intent) {    Log.i("tag", " BluetoothReceiver  /LightReceiver onReceive()  action=" + intent.getAction());    //    String address = intent.getStringExtra("bluetoothAddress");  //從adapter取得的數據    lightAction = intent.getAction();    // if()   不同設備  不同serviceUUID,不同的characteristicUUID 自己確定    serviceUUID=service4UUID;    characteristicUUID=charAUUID;    if (bluetoothAdapter == null) {      openBluetooth();    }    BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);      MyBluetoothGattCallback gattCallback = new MyBluetoothGattCallback();    bluetoothGatt = device.connectGatt(MainActivity1.this, false, gattCallback);  //回調  }}//藍牙連接/通信回調class MyBluetoothGattCallback extends android.bluetooth.BluetoothGattCallback {  @Override  public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {    super.onConnectionStateChange(gatt, status, newState);    Log.i("tag", "MyBluetoothGattCallback  onConnectionStateChange()  newState=" + newState);    if (newState == BluetoothProfile.STATE_CONNECTED) {      gatt.discoverServices();       //連接成功,開始搜索服務,一定要調用此方法,否則獲取不到服務      Log.i("tag", "MyBluetoothGattCallback  STATE_CONNECTED  ");    } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {      Log.i("tag", "MyBluetoothGattCallback  STATE_DISCONNECTED");    }  }  @Override  public void onServicesDiscovered(BluetoothGatt gatt, int status) {    super.onServicesDiscovered(gatt, status);    Log.i("tag", "MyBluetoothGattCallback  onServicesDiscovered() 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);      } else if (lightAction.equals("closeLight")) {        gattCharacteristic.setValue("closeLight"); //這里自己設置 藍牙模組需要的數據        gatt.writeCharacteristic(gattCharacteristic);      }      lightAction = "";      gatt.readRemoteRssi();    }  }}@Overrideprotected void onDestroy() {  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;  }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 温宿县| 长阳| 佛山市| 英德市| 康平县| 图木舒克市| 金坛市| 玉门市| 曲阜市| 泰州市| 石泉县| 盖州市| 东兴市| 昌宁县| 沙湾县| 商洛市| 冕宁县| 德钦县| 威远县| 喜德县| 册亨县| 枣阳市| 丰县| 日土县| 中方县| 塔河县| 屏边| 衡南县| 靖州| 扬中市| 通江县| 邳州市| 象州县| 武邑县| 抚州市| 长沙市| 柳江县| 张家界市| 龙南县| 剑阁县| 昌邑市|