-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAndroid_bluetooth.txt
419 lines (374 loc) · 15.4 KB
/
Android_bluetooth.txt
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package com.luoxn28.bluetooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
public static final int RECV_VIEW = 0;
public static final int NOTICE_VIEW = 1;
private BluetoothAdapter bluetoothAdapter = null;
private ConnectThread connectThread = null;
private ConnectedThread connectedThread = null;
private TextView noticeView = null;
private Button turnOnOff = null;
private TextView led0, led1, led2, led3, led4;
ScrollView scrollView = null;
private TextView recvView = null;
private Button clearRecvView = null;
private EditText sendText = null;
private Button send = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取BluetoothAdapter
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device does not support Bluetooth
return;
}
// 注册监听事件
noticeView = (TextView) findViewById(R.id.notice_view);
turnOnOff = (Button) findViewById(R.id.turn_on_off);
led0 = (TextView) findViewById(R.id.led0);
led1 = (TextView) findViewById(R.id.led1);
led2 = (TextView) findViewById(R.id.led2);
led3 = (TextView) findViewById(R.id.led3);
led4 = (TextView) findViewById(R.id.led4);
scrollView = (ScrollView) findViewById(R.id.scroll_view);
recvView = (TextView) findViewById(R.id.recv_view);
clearRecvView = (Button) findViewById(R.id.clear_recv_view);
sendText = (EditText) findViewById(R.id.send_text);
send = (Button) findViewById(R.id.send);
turnOnOff.setOnClickListener(this);
clearRecvView.setOnClickListener(this);
send.setOnClickListener(this);
if (!bluetoothAdapter.isEnabled()) {
noticeView.setText("蓝牙未开启");
}
else {
noticeView.setText("蓝牙已开启");
}
noticeView.setBackgroundColor(Color.GRAY);
led0.setBackgroundColor(Color.GRAY);
led1.setBackgroundColor(Color.GRAY);
led2.setBackgroundColor(Color.GRAY);
led3.setBackgroundColor(Color.GRAY);
led4.setBackgroundColor(Color.GRAY);
}
private boolean isOn = false;
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.turn_on_off: // 发送'0'或者'1'都可以
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Toast.makeText(this, "蓝牙未开启", Toast.LENGTH_SHORT).show();
break;
}
if (connectedThread == null) {
Toast.makeText(this, "未连接设备", Toast.LENGTH_SHORT).show();
break;
}
String turn_string = "1@#";
connectedThread.write(turn_string.getBytes());
if (isOn == false) {
isOn = true; // 打开了
turnOnOff.setText("OFF");
led1.setText("");
led2.setText("");
led3.setText("");
led4.setText("");
}
else {
isOn = false; // 关闭了
turnOnOff.setText("ON");
led1.setText("LED1");
led2.setText("LED2");
led3.setText("LED3");
led4.setText("LED4");
}
break;
case R.id.clear_recv_view: // 清空接收框
recvView.setText("");
break;
case R.id.send: // 发送数据,默认以"@#"结尾
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Toast.makeText(this, "蓝牙未开启", Toast.LENGTH_SHORT).show();
return;
}
if (connectedThread == null) {
Toast.makeText(this, "未连接设备", Toast.LENGTH_SHORT).show();
break;
}
String inputText = sendText.getText().toString() + "@#"; // 发送给单片机数据以"@#结尾",这样单片机知道一条数据发送结束
//Toast.makeText(MainActivity.this, inputText, Toast.LENGTH_SHORT).show();
connectedThread.write(inputText.getBytes());
break;
default:
break;
}
}
private android.os.Handler handler = new android.os.Handler() {
public void handleMessage(Message msg) {
Bundle bundle = null;
switch (msg.what) {
case RECV_VIEW:
if (isOn == false) {
isOn = true;
turnOnOff.setText("OFF");
}
bundle = msg.getData();
String recv = bundle.getString("recv");
recvView.append(recv + "\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN); // 滚动到底部
if (recv.isEmpty() || recv.contains(" ") || recv.contains("#")) {
break;
}
int num = Integer.valueOf(recv) / 2; // 0-60s
if (num <= 20) {
led1.setText("");
led2.setText("");
led3.setText("");
led4.setText("");
led1.setBackgroundColor(Color.RED);
led2.setBackgroundColor(Color.RED);
led3.setBackgroundColor(Color.GREEN);
led4.setBackgroundColor(Color.GREEN);
}
else if (num < 30) {
int n = 30 - num;
led1.setText("" + n);
led2.setText("" + n);
if (num < 28) {
led3.setBackgroundColor(Color.GREEN);
led4.setBackgroundColor(Color.GREEN);
}
else {
led3.setBackgroundColor(Color.YELLOW);
led4.setBackgroundColor(Color.YELLOW);
}
}
else if (num <= 50) {
led1.setText("");
led2.setText("");
led3.setText("");
led4.setText("");
led1.setBackgroundColor(Color.GREEN);
led2.setBackgroundColor(Color.GREEN);
led3.setBackgroundColor(Color.RED);
led4.setBackgroundColor(Color.RED);
}
else {
int n = 60 - num;
led3.setText("" + n);
led4.setText("" + n);
if (num < 58) {
led1.setBackgroundColor(Color.GREEN);
led2.setBackgroundColor(Color.GREEN);
}
else {
led1.setBackgroundColor(Color.YELLOW);
led2.setBackgroundColor(Color.YELLOW);
}
}
break;
case NOTICE_VIEW:
bundle = msg.getData();
String notice = bundle.getString("notice");
noticeView.setText(notice);
break;
default:
break;
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.start_bluetooth) {
if (bluetoothAdapter != null) {
// 开启蓝牙
int REQUEST_ENABLE_BT = 1;
if (!bluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
noticeView.setText("开启蓝牙成功");
//Toast.makeText(this, "开启蓝牙成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "蓝牙已开启", Toast.LENGTH_SHORT).show();
}
}
return true;
}
else if (id == R.id.show_devices) {
if (bluetoothAdapter != null) {
if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(this, "蓝牙未开启", Toast.LENGTH_SHORT).show();
return true;
}
// 查询配对设备
List<String> devices = new ArrayList<String>();
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : bondedDevices) {
devices.add(device.getName() + "-" + device.getAddress());
}
StringBuilder text = new StringBuilder();
for (String device : devices) {
text.append(device + "\n");
}
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
return true;
}
else if (id == R.id.find_devices) {
Toast.makeText(this, "该功能暂时不可用", Toast.LENGTH_SHORT).show();
}
else if (id == R.id.connect_devices) {
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Toast.makeText(this, "蓝牙未开启", Toast.LENGTH_SHORT).show();
return true;
}
// 查询配对设备 建立连接,只能连接第一个配对的设备
List<String> devices = new ArrayList<String>();
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : bondedDevices) {
connectThread = new ConnectThread(device);
connectThread.start();
//Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show();
break;
}
}
return super.onOptionsItemSelected(item);
}
private class ConnectThread extends Thread {
private final String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";
private final BluetoothSocket socket;
private final BluetoothDevice device;
public ConnectThread(BluetoothDevice device) {
this.device = device;
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
} catch (IOException e) {
e.printStackTrace();
}
this.socket = tmp;
}
public void run() {
bluetoothAdapter.cancelDiscovery();
try {
socket.connect();
connectedThread = new ConnectedThread(socket);
connectedThread.start();
} catch (IOException e) {
try {
socket.close();
} catch (IOException ee) {
ee.printStackTrace();
}
return;
}
//manageConnectedSocket(socket);
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 客户端与服务器建立连接成功后,用ConnectedThread收发数据
private class ConnectedThread extends Thread {
private final BluetoothSocket socket;
private final InputStream inputStream;
private final OutputStream outputStream;
public ConnectedThread(BluetoothSocket socket) {
this.socket = socket;
InputStream input = null;
OutputStream output = null;
try {
input = socket.getInputStream();
output = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
this.inputStream = input;
this.outputStream = output;
}
public void run() {
StringBuilder recvText = new StringBuilder();
byte[] buff = new byte[1024];
int bytes;
Bundle tmpBundle = new Bundle();
Message tmpMessage = new Message();
tmpBundle.putString("notice", "连接成功");
tmpMessage.what = NOTICE_VIEW;
tmpMessage.setData(tmpBundle);
handler.sendMessage(tmpMessage);
while (true) {
try {
bytes = inputStream.read(buff);
String str = new String(buff, "ISO-8859-1");
str = str.substring(0, bytes);
// 收到数据,单片机发送上来的数据以"#"结束,这样手机知道一条数据发送结束
//Log.e("read", str);
if (!str.endsWith("#")) {
recvText.append(str);
continue;
}
recvText.append(str.substring(0, str.length() - 1)); // 去除'#'
Bundle bundle = new Bundle();
Message message = new Message();
bundle.putString("recv", recvText.toString());
message.what = RECV_VIEW;
message.setData(bundle);
handler.sendMessage(message);
recvText.replace(0, recvText.length(), "");
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public void write(byte[] bytes) {
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}