一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Android - android實現(xiàn)藍(lán)牙app代碼

android實現(xiàn)藍(lán)牙app代碼

2022-02-25 15:23tangzheng828 Android

這篇文章主要為大家詳細(xì)介紹了android實現(xiàn)藍(lán)牙app的代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了android實現(xiàn)藍(lán)牙app的具體代碼,供大家參考,具體內(nèi)容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
private BluetoothGatt bluetoothGatt;
private BluetoothGattService gattService;
private BluetoothGattCharacteristic gattCharacteristic;
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private List<BluetoothDevice> devices = new ArrayList<>();
 
private UUID serviceUUID;  //不同設(shè)備 不同uuid
private UUID characteristicUUID;   //不同設(shè)備 不同uuid
private 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;
 
@Override
protected 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();
 
}
 
@Override
protected void onStart() {
  super.onStart();
  Log.i("tag", "MainActivity  onStart()");
  bluetoothScan();
}
 
//返回
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
  Log.i("tag", "MainActivity  onKeyUp()");
  this.finish();
  return super.onKeyUp(keyCode, event);
}
 
//重新掃描藍(lán)牙
@Override
public void onClick(View view) {
  switch (view.getId()) {
    case R.id.tv_refresh_bluetooth:
      //藍(lán)牙掃描
      bluetoothScan();
      break;
    default:
      break;
  }
}
 
//打開本地藍(lán)牙
private void openBluetooth() {
  Log.i("tag", "openLocalBluetooth()");
  //檢查手機(jī)是否支持藍(lán)牙4.0
  if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(this, "手機(jī)不支持藍(lán)牙4.0", Toast.LENGTH_SHORT).show();
    finish();
  }
  //調(diào)用系統(tǒng)服務(wù)的方式,請求開啟藍(lán)牙
  bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
  bluetoothAdapter = bluetoothManager.getAdapter();
  //開啟藍(lán)牙
  if (!bluetoothAdapter.isEnabled()) {
    bluetoothAdapter.enable();
  }
}
 
//開始藍(lán)牙掃描  掃描到一個添加一個
private void bluetoothScan() {
  Log.i("tag", "bluetoothScan()");
  if (bluetoothAdapter == null) {
    openBluetooth();
  }
  if (!bluetoothAdapter.isDiscovering()) {
    bluetoothAdapter.startDiscovery();  //回調(diào)
  } else {
    Toast.makeText(this, "掃描中..", Toast.LENGTH_SHORT).show();
  }
}
 
//更新藍(lán)牙列表中的數(shù)據(jù)
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, "附近沒有藍(lán)牙", Toast.LENGTH_SHORT).show();
  }
}
 
//取得gatt 對應(yīng)的service
private 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對應(yīng)的characteristic
private BluetoothGattCharacteristic getGattCharacteristic(BluetoothGattService gattService, UUID characteristicUUID) {
  List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
  for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
    if (gattCharacteristic.getUuid().equals(characteristicUUID)) {
      return gattCharacteristic;
    }
  }
  return null;
}
 
//注冊藍(lán)牙掃描監(jiān)聽
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);
}
 
//定義藍(lán)牙掃描監(jiān)聽類 添加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, "附近沒有發(fā)現(xiàn)藍(lán)牙設(shè)備", Toast.LENGTH_SHORT).show();
      }
    }
  }
}
 
//注冊燈光監(jiān)聽
private void registeLigthReceiver() {
  Log.i("tag", "registeReceiver()");
  lightReceiver = new LightReceiver();
  IntentFilter filter = new IntentFilter();
  filter.addAction("openLight");
  filter.addAction("closeLight");
  registerReceiver(lightReceiver, filter);
}
 
//定義燈控監(jiān)聽類
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取得的數(shù)據(jù)
    lightAction = intent.getAction();
    // if()   不同設(shè)備  不同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);  //回調(diào)
 
  }
}
 
//藍(lán)牙連接/通信回調(diào)
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();       //連接成功,開始搜索服務(wù),一定要調(diào)用此方法,否則獲取不到服務(wù)
      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"); //這里自己設(shè)置 藍(lán)牙模組需要的數(shù)據(jù)
        gatt.writeCharacteristic(gattCharacteristic);
      } else if (lightAction.equals("closeLight")) {
        gattCharacteristic.setValue("closeLight"); //這里自己設(shè)置 藍(lán)牙模組需要的數(shù)據(jù)
        gatt.writeCharacteristic(gattCharacteristic);
      }
      lightAction = "";
      gatt.readRemoteRssi();
    }
  }
}
 
@Override
protected 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;
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:https://blog.csdn.net/tangzheng828/article/details/52672345

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美一区二区三区四区五区六区 | 国产精品免费综合一区视频 | 男人把大ji巴放进男人免费视频 | 欧美18一videos极品 | 末代皇帝无删减版在线观看 | 国产一二在线观看视频网站 | 好紧好爽再叫浪一点点潘金莲 | 亚1洲二区三区四区免费 | 精品视频99 | 天天曰 | 护士柔佳 | 精品91自产拍在线观看99re | 韩国漂亮美女三级在线观看 | 黄漫免费观看 | 日本伊人色 | 色呦呦在线免费观看 | 国产成人免费在线视频 | 韩国情事伦理片观看地址 | 日本人成动漫网站在线观看 | 男人天堂2023 | 久操久操久操 | 亚洲同性男男gay1069 | 黑人巨荃大战乌克兰美女 | 91禁漫 | 精品麻豆| 好大好硬好深好爽想要吃奶 | 欧美撒尿屁股嘘嘘撒尿 | 成人黄色免费网站 | 亚洲va韩国va欧美va天堂 | 国产成人h综合亚洲欧美在线 | 欧美日韩中文字幕久久伊人 | 高人先生免费观看全集 | 成功精品影院 | 国产精品四虎在线观看免费 | 东北老妇露脸xxxxx | 性满足久久久久久久久 | 九九精品视频在线播放 | 国产成人久久 | freexxxx性护士第一次 | 国产精品模特hd在线 | 亚洲精品国产在线网站 |